markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Renaming columnsWe can also rename the columns of a DataFrameThis is helpful because the names that sometimes come with datasets areunbearable…For example, the original name for the North East unemployment rategiven by the Bureau of Labor Statistics was `LASRD910000000000003`…They have their reasons for using these names, but it can make our jobdifficult since we need to type it sometimes repeatedlyWe can rename columns by passing a dictionary to the `rename` methodThis dictionary contains the old names as the keys and new names as thevalues.See the example below
names = {"NorthEast": "NE", "MidWest": "MW", "South": "S", "West": "W"} unemp_region.rename(columns=names) unemp_region.head()
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
We renamed our columns… Why does the DataFrame still show the oldcolumn names?Many of the operations that pandas does creates a copy of your data bydefaultIt does this in order to protect your data and make sure you don’toverwrite information you’d like to keepWe can make these operations permanent by either1. Assigning the output back to the variable name `df = df.rename(columns=rename_dict)` or 1. Looking into whether the method has an `inplace` option. For example, `df.rename(columns=rename_dict, inplace=True)` There are times when setting `inplace=True` will make your code faster(e.g. if you have a very large DataFrame and you don’t want to copy allthe data), but that doesn’t always happenWe recommend using the first option until you get comfortable withpandas because operations that don’t alter your data are (usually)easier to reason about
names = {"NorthEast": "NE", "MidWest": "MW", "South": "S", "West": "W"} unemp_shortname = unemp_region.rename(columns=names) unemp_shortname.head()
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
Copyright 2020 The TensorFlow Hub Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
_____no_output_____
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
View on TensorFlow.org Run in Google Colab View on GitHub Download notebook See TF Hub model Classify text with BERTThis tutorial contains complete code to fine-tune BERT to perform sentiment analysis on a dataset of plain-text IMDB movie reviews.In addition to training a model, you will learn how to preprocess text into an appropriate format.In this notebook, you will:- Load the IMDB dataset- Load a BERT model from TensorFlow Hub- Build your own model by combining BERT with a classifier- Train your own model, fine-tuning BERT as part of that- Save your model and use it to classify sentencesIf you're new to working with the IMDB dataset, please see [Basic text classification](https://www.tensorflow.org/tutorials/keras/text_classification) for more details. About BERT[BERT](https://arxiv.org/abs/1810.04805) and other Transformer encoder architectures have been wildly successful on a variety of tasks in NLP (natural language processing). They compute vector-space representations of natural language that are suitable for use in deep learning models. The BERT family of models uses the Transformer encoder architecture to process each token of input text in the full context of all tokens before and after, hence the name: Bidirectional Encoder Representations from Transformers. BERT models are usually pre-trained on a large corpus of text, then fine-tuned for specific tasks. Setup TensorFlow Text"TensorFlow Text provides a collection of text related classes and ops ready to use with TensorFlow 2.0. The library can perform the preprocessing regularly required by text-based models, and includes other features useful for sequence modeling not provided by core TensorFlow" (https://www.tensorflow.org/text/guide/tf_text_intro)
# A dependency of the preprocessing for BERT inputs !pip install -q -U tensorflow-text
 |████████████████████████████████| 4.4 MB 5.3 MB/s [?25h
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
We will use the AdamW optimizer from [tensorflow/models](https://github.com/tensorflow/models). "TensorFlow Model Garden is a repository with a number of different implementations of state-of-the-art (SOTA) models and modeling solutions for TensorFlow users."
!pip install -q tf-models-official %tensorflow_version 2.x import tensorflow as tf device_name = tf.test.gpu_device_name() if device_name != '/device:GPU:0': raise SystemError('GPU device not found') print('Found GPU at: {}'.format(device_name)) import os import shutil import tensorflow_hub as hub # TFHub is a repository of trained machine learning models (https://www.tensorflow.org/hub) import tensorflow_text as text from official.nlp import optimization # to create AdamW optimizer import matplotlib.pyplot as plt tf.get_logger().setLevel('ERROR')
_____no_output_____
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
Sentiment analysisThis notebook trains a sentiment analysis model to classify movie reviews as *positive* or *negative*, based on the text of the review.You'll use the [Large Movie Review Dataset](https://ai.stanford.edu/~amaas/data/sentiment/) that contains the text of 50,000 movie reviews from the [Internet Movie Database](https://www.imdb.com/). Keras"Keras is the high-level API of TensorFlow 2: an approachable, highly-productive interface for solving machine learning problems, with a focus on modern deep learning. It provides essential abstractions and building blocks for developing and shipping machine learning solutions with high iteration velocity" (https://keras.io/about/). A useful hands-on colab detailing keras abstractions can be found [here](https://jaredwinick.github.io/what_is_tf_keras/). Additional details can be found [here](https://machinelearningmastery.com/tensorflow-tutorial-deep-learning-with-tf-keras/). Download the IMDB datasetLet's download and extract the dataset, then explore the directory structure.
url = 'https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz' dataset = tf.keras.utils.get_file('aclImdb_v1.tar.gz', url, untar=True, cache_dir='.', cache_subdir='') dataset_dir = os.path.join(os.path.dirname(dataset), 'aclImdb') print(dataset_dir) !ls ./aclImdb/train train_dir = os.path.join(dataset_dir, 'train') # remove unused folders to make it easier to load the data remove_dir = os.path.join(train_dir, 'unsup') shutil.rmtree(remove_dir)
Downloading data from https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz 84131840/84125825 [==============================] - 5s 0us/step 84140032/84125825 [==============================] - 5s 0us/step ./aclImdb labeledBow.feat pos unsupBow.feat urls_pos.txt neg unsup urls_neg.txt urls_unsup.txt
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
Next, you will use the `text_dataset_from_directory` utility to create a labeled `tf.data.Dataset`. The `tf.data.Dataset` API supports writing descriptive and efficient input pipelines. Dataset usage follows a common pattern:- Create a source dataset from your input data.- Apply dataset transformations to preprocess the data.- Iterate over the dataset and process the elements.More details can be found [here](https://www.tensorflow.org/api_docs/python/tf/data/Dataset).The IMDB dataset has already been divided into train and test, but it lacks a validation set. Let's create a validation set using an 80:20 split of the training data by using the `validation_split` argument below.Note: When using the `validation_split` and `subset` arguments, make sure to either specify a random seed, or to pass `shuffle=False`, so that the validation and training splits have no overlap. PrefetchingPrefetching overlaps the preprocessing and model execution of a training step. While the model is executing training step s, the input pipeline is reading the data for step s+1. Doing so reduces the step time to the maximum (as opposed to the sum) of the training and the time it takes to extract the data.The tf.data API provides the tf.data.Dataset.prefetch transformation. It can be used to decouple the time when data is produced from the time when data is consumed. In particular, the transformation uses a background thread and an internal buffer to prefetch elements from the input dataset ahead of the time they are requested. The number of elements to prefetch should be equal to (or possibly greater than) the number of batches consumed by a single training step. You could either manually tune this value, or set it to tf.data.AUTOTUNE, which will prompt the tf.data runtime to tune the value dynamically at runtime. [Source](https://www.tensorflow.org/guide/data_performanceprefetching)
AUTOTUNE = tf.data.AUTOTUNE batch_size = 32 seed = 42 raw_train_ds = tf.keras.preprocessing.text_dataset_from_directory( 'aclImdb/train', batch_size=batch_size, validation_split=0.2, subset='training', seed=seed) class_names = raw_train_ds.class_names print(class_names) train_ds = raw_train_ds.cache().prefetch(buffer_size=AUTOTUNE) val_ds = tf.keras.preprocessing.text_dataset_from_directory( 'aclImdb/train', batch_size=batch_size, validation_split=0.2, subset='validation', seed=seed) val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE) test_ds = tf.keras.preprocessing.text_dataset_from_directory( 'aclImdb/test', batch_size=batch_size) test_ds = test_ds.cache().prefetch(buffer_size=AUTOTUNE)
Found 25000 files belonging to 2 classes. Using 20000 files for training. ['neg', 'pos'] Found 25000 files belonging to 2 classes. Using 5000 files for validation. Found 25000 files belonging to 2 classes.
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
Let's take a look at a few reviews.
for text_batch, label_batch in train_ds.take(1): for i in range(3): print(f'Review: {text_batch.numpy()[i]}') label = label_batch.numpy()[i] print(f'Label : {label} ({class_names[label]})')
Review: b'"Pandemonium" is a horror movie spoof that comes off more stupid than funny. Believe me when I tell you, I love comedies. Especially comedy spoofs. "Airplane", "The Naked Gun" trilogy, "Blazing Saddles", "High Anxiety", and "Spaceballs" are some of my favorite comedies that spoof a particular genre. "Pandemonium" is not up there with those films. Most of the scenes in this movie had me sitting there in stunned silence because the movie wasn\'t all that funny. There are a few laughs in the film, but when you watch a comedy, you expect to laugh a lot more than a few times and that\'s all this film has going for it. Geez, "Scream" had more laughs than this film and that was more of a horror film. How bizarre is that?<br /><br />*1/2 (out of four)' Label : 0 (neg) Review: b"David Mamet is a very interesting and a very un-equal director. His first movie 'House of Games' was the one I liked best, and it set a series of films with characters whose perspective of life changes as they get into complicated situations, and so does the perspective of the viewer.<br /><br />So is 'Homicide' which from the title tries to set the mind of the viewer to the usual crime drama. The principal characters are two cops, one Jewish and one Irish who deal with a racially charged area. The murder of an old Jewish shop owner who proves to be an ancient veteran of the Israeli Independence war triggers the Jewish identity in the mind and heart of the Jewish detective.<br /><br />This is were the flaws of the film are the more obvious. The process of awakening is theatrical and hard to believe, the group of Jewish militants is operatic, and the way the detective eventually walks to the final violent confrontation is pathetic. The end of the film itself is Mamet-like smart, but disappoints from a human emotional perspective.<br /><br />Joe Mantegna and William Macy give strong performances, but the flaws of the story are too evident to be easily compensated." Label : 0 (neg) Review: b'Great documentary about the lives of NY firefighters during the worst terrorist attack of all time.. That reason alone is why this should be a must see collectors item.. What shocked me was not only the attacks, but the"High Fat Diet" and physical appearance of some of these firefighters. I think a lot of Doctors would agree with me that,in the physical shape they were in, some of these firefighters would NOT of made it to the 79th floor carrying over 60 lbs of gear. Having said that i now have a greater respect for firefighters and i realize becoming a firefighter is a life altering job. The French have a history of making great documentary\'s and that is what this is, a Great Documentary.....' Label : 1 (pos)
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
Loading models from TensorFlow HubHere you can choose which BERT model you will load from TensorFlow Hub and fine-tune. There are multiple BERT models available. - [BERT-Base](https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/3), [Uncased](https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/3) and [seven more models](https://tfhub.dev/google/collections/bert/1) with trained weights released by the original BERT authors. - [Small BERTs](https://tfhub.dev/google/collections/bert/1) have the same general architecture but fewer and/or smaller Transformer blocks, which lets you explore tradeoffs between speed, size and quality. - [ALBERT](https://tfhub.dev/google/collections/albert/1): four different sizes of "A Lite BERT" that reduces model size (but not computation time) by sharing parameters between layers.The model documentation on TensorFlow Hub has more details and references to theresearch literature. Follow the links above, or click on the [`tfhub.dev`](http://tfhub.dev) URLprinted after the next cell execution.The suggestion is to start with a Small BERT (with fewer parameters) since they are faster to fine-tune. If you like a small model but with higher accuracy, ALBERT might be your next option. If you want even better accuracy, chooseone of the classic BERT sizes or their recent refinements like Electra, Talking Heads, or a BERT Expert.Aside from the models available below, there are [multiple versions](https://tfhub.dev/google/collections/transformer_encoders_text/1) of the models that are larger and can yield even better accuracy, but they are too big to be fine-tuned on a single GPU. You will be able to do that on the [Solve GLUE tasks using BERT on a TPU colab](https://www.tensorflow.org/text/tutorials/bert_glue).You'll see in the code below that switching the tfhub.dev URL is enough to try any of these models, because all the differences between them are encapsulated in the SavedModels from TF Hub.
#@title Choose a BERT model to fine-tune bert_model_name = "small_bert/bert_en_uncased_L-4_H-512_A-8" #@param ["bert_en_uncased_L-12_H-768_A-12", "bert_en_cased_L-12_H-768_A-12", "bert_multi_cased_L-12_H-768_A-12", "small_bert/bert_en_uncased_L-2_H-128_A-2", "small_bert/bert_en_uncased_L-2_H-256_A-4", "small_bert/bert_en_uncased_L-2_H-512_A-8", "small_bert/bert_en_uncased_L-2_H-768_A-12", "small_bert/bert_en_uncased_L-4_H-128_A-2", "small_bert/bert_en_uncased_L-4_H-256_A-4", "small_bert/bert_en_uncased_L-4_H-512_A-8", "small_bert/bert_en_uncased_L-4_H-768_A-12", "small_bert/bert_en_uncased_L-6_H-128_A-2", "small_bert/bert_en_uncased_L-6_H-256_A-4", "small_bert/bert_en_uncased_L-6_H-512_A-8", "small_bert/bert_en_uncased_L-6_H-768_A-12", "small_bert/bert_en_uncased_L-8_H-128_A-2", "small_bert/bert_en_uncased_L-8_H-256_A-4", "small_bert/bert_en_uncased_L-8_H-512_A-8", "small_bert/bert_en_uncased_L-8_H-768_A-12", "small_bert/bert_en_uncased_L-10_H-128_A-2", "small_bert/bert_en_uncased_L-10_H-256_A-4", "small_bert/bert_en_uncased_L-10_H-512_A-8", "small_bert/bert_en_uncased_L-10_H-768_A-12", "small_bert/bert_en_uncased_L-12_H-128_A-2", "small_bert/bert_en_uncased_L-12_H-256_A-4", "small_bert/bert_en_uncased_L-12_H-512_A-8", "small_bert/bert_en_uncased_L-12_H-768_A-12", "albert_en_base", "electra_small", "electra_base", "experts_pubmed", "experts_wiki_books", "talking-heads_base"] map_name_to_handle = { 'bert_en_uncased_L-12_H-768_A-12': 'https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/3', 'bert_en_cased_L-12_H-768_A-12': 'https://tfhub.dev/tensorflow/bert_en_cased_L-12_H-768_A-12/3', 'bert_multi_cased_L-12_H-768_A-12': 'https://tfhub.dev/tensorflow/bert_multi_cased_L-12_H-768_A-12/3', 'small_bert/bert_en_uncased_L-2_H-128_A-2': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-2_H-128_A-2/1', 'small_bert/bert_en_uncased_L-2_H-256_A-4': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-2_H-256_A-4/1', 'small_bert/bert_en_uncased_L-2_H-512_A-8': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-2_H-512_A-8/1', 'small_bert/bert_en_uncased_L-2_H-768_A-12': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-2_H-768_A-12/1', 'small_bert/bert_en_uncased_L-4_H-128_A-2': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-4_H-128_A-2/1', 'small_bert/bert_en_uncased_L-4_H-256_A-4': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-4_H-256_A-4/1', 'small_bert/bert_en_uncased_L-4_H-512_A-8': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-4_H-512_A-8/1', 'small_bert/bert_en_uncased_L-4_H-768_A-12': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-4_H-768_A-12/1', 'small_bert/bert_en_uncased_L-6_H-128_A-2': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-6_H-128_A-2/1', 'small_bert/bert_en_uncased_L-6_H-256_A-4': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-6_H-256_A-4/1', 'small_bert/bert_en_uncased_L-6_H-512_A-8': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-6_H-512_A-8/1', 'small_bert/bert_en_uncased_L-6_H-768_A-12': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-6_H-768_A-12/1', 'small_bert/bert_en_uncased_L-8_H-128_A-2': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-8_H-128_A-2/1', 'small_bert/bert_en_uncased_L-8_H-256_A-4': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-8_H-256_A-4/1', 'small_bert/bert_en_uncased_L-8_H-512_A-8': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-8_H-512_A-8/1', 'small_bert/bert_en_uncased_L-8_H-768_A-12': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-8_H-768_A-12/1', 'small_bert/bert_en_uncased_L-10_H-128_A-2': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-10_H-128_A-2/1', 'small_bert/bert_en_uncased_L-10_H-256_A-4': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-10_H-256_A-4/1', 'small_bert/bert_en_uncased_L-10_H-512_A-8': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-10_H-512_A-8/1', 'small_bert/bert_en_uncased_L-10_H-768_A-12': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-10_H-768_A-12/1', 'small_bert/bert_en_uncased_L-12_H-128_A-2': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-12_H-128_A-2/1', 'small_bert/bert_en_uncased_L-12_H-256_A-4': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-12_H-256_A-4/1', 'small_bert/bert_en_uncased_L-12_H-512_A-8': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-12_H-512_A-8/1', 'small_bert/bert_en_uncased_L-12_H-768_A-12': 'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-12_H-768_A-12/1', 'albert_en_base': 'https://tfhub.dev/tensorflow/albert_en_base/2', 'electra_small': 'https://tfhub.dev/google/electra_small/2', 'electra_base': 'https://tfhub.dev/google/electra_base/2', 'experts_pubmed': 'https://tfhub.dev/google/experts/bert/pubmed/2', 'experts_wiki_books': 'https://tfhub.dev/google/experts/bert/wiki_books/2', 'talking-heads_base': 'https://tfhub.dev/tensorflow/talkheads_ggelu_bert_en_base/1', } map_model_to_preprocess = { 'bert_en_uncased_L-12_H-768_A-12': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'bert_en_cased_L-12_H-768_A-12': 'https://tfhub.dev/tensorflow/bert_en_cased_preprocess/3', 'small_bert/bert_en_uncased_L-2_H-128_A-2': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-2_H-256_A-4': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-2_H-512_A-8': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-2_H-768_A-12': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-4_H-128_A-2': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-4_H-256_A-4': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-4_H-512_A-8': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-4_H-768_A-12': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-6_H-128_A-2': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-6_H-256_A-4': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-6_H-512_A-8': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-6_H-768_A-12': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-8_H-128_A-2': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-8_H-256_A-4': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-8_H-512_A-8': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-8_H-768_A-12': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-10_H-128_A-2': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-10_H-256_A-4': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-10_H-512_A-8': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-10_H-768_A-12': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-12_H-128_A-2': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-12_H-256_A-4': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-12_H-512_A-8': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'small_bert/bert_en_uncased_L-12_H-768_A-12': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'bert_multi_cased_L-12_H-768_A-12': 'https://tfhub.dev/tensorflow/bert_multi_cased_preprocess/3', 'albert_en_base': 'https://tfhub.dev/tensorflow/albert_en_preprocess/3', 'electra_small': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'electra_base': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'experts_pubmed': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'experts_wiki_books': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', 'talking-heads_base': 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', } tfhub_handle_encoder = map_name_to_handle[bert_model_name] tfhub_handle_preprocess = map_model_to_preprocess[bert_model_name] print(f'BERT model selected : {tfhub_handle_encoder}') print(f'Preprocess model auto-selected: {tfhub_handle_preprocess}')
BERT model selected : https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-4_H-512_A-8/1 Preprocess model auto-selected: https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
The preprocessing modelText inputs need to be transformed to numeric token ids and arranged in several Tensors before being input to BERT. TensorFlow Hub provides a matching preprocessing model for each of the BERT models discussed above, which implements this transformation using TF ops from the TF.text library. It is not necessary to run pure Python code outside your TensorFlow model to preprocess text.The preprocessing model must be the one referenced by the documentation of the BERT model, which you can read at the URL printed above. For BERT models from the drop-down above, the preprocessing model is selected automatically.Note: You will load the preprocessing model into a [hub.KerasLayer](https://www.tensorflow.org/hub/api_docs/python/hub/KerasLayer) to compose your fine-tuned model. More information on Keras layers can be found [here](https://keras.io/api/layers/). "Layers are the basic building blocks of neural networks in Keras. A layer consists of a tensor-in tensor-out computation function (the layer's call method) and some state, held in TensorFlow variables (the layer's weights)."[hub.KerasLayer](https://www.tensorflow.org/hub/api_docs/python/hub/KerasLayer) is the preferred API to load a TF2-style [SavedModel](https://www.tensorflow.org/guide/saved_model) from TF Hub into a Keras model.
bert_preprocess_model = hub.KerasLayer(tfhub_handle_preprocess)
_____no_output_____
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
Let's try the preprocessing model on some text and see the output:
text_test = ['this is such an amazing movie!'] text_preprocessed = bert_preprocess_model(text_test) print(f'Keys : {list(text_preprocessed.keys())}') print(f'Shape : {text_preprocessed["input_word_ids"].shape}') print(f'Word Ids : {text_preprocessed["input_word_ids"][0, :12]}') print(f'Input Mask : {text_preprocessed["input_mask"][0, :12]}') print(f'Type Ids : {text_preprocessed["input_type_ids"][0, :12]}')
Keys : ['input_type_ids', 'input_mask', 'input_word_ids'] Shape : (1, 128) Word Ids : [ 101 2023 2003 2107 2019 6429 3185 999 102 0 0 0] Input Mask : [1 1 1 1 1 1 1 1 1 0 0 0] Type Ids : [0 0 0 0 0 0 0 0 0 0 0 0]
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
As you can see, now you have the 3 outputs from the preprocessing that a BERT model would use (`input_words_id`, `input_mask` and `input_type_ids`).Some other important points:- The input is truncated to 128 tokens. The number of tokens can be customized, and you can see more details on the [Solve GLUE tasks using BERT on a TPU colab](https://www.tensorflow.org/text/tutorials/bert_glue).- The `input_type_ids` only have one value (0) because this is a single sentence input. For a multiple sentence input, it would have one number for each input.Since this text preprocessor is a TensorFlow model, It can be included in your model directly. Using the BERT modelBefore putting BERT into your own model, let's take a look at its outputs. You will load it from TF Hub and see the returned values.
bert_model = hub.KerasLayer(tfhub_handle_encoder) bert_results = bert_model(text_preprocessed) print(f'Loaded BERT: {tfhub_handle_encoder}') print(f'Pooled Outputs Shape:{bert_results["pooled_output"].shape}') print(f'Pooled Outputs Values:{bert_results["pooled_output"][0, :12]}') print(f'Sequence Outputs Shape:{bert_results["sequence_output"].shape}') print(f'Sequence Outputs Values:{bert_results["sequence_output"][0, :12]}')
Loaded BERT: https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-4_H-512_A-8/1 Pooled Outputs Shape:(1, 512) Pooled Outputs Values:[ 0.7626282 0.9928099 -0.18611862 0.3667383 0.15233758 0.655044 0.9681154 -0.94862705 0.0021616 -0.9877732 0.06842764 -0.97630596] Sequence Outputs Shape:(1, 128, 512) Sequence Outputs Values:[[-0.28946292 0.34321183 0.33231512 ... 0.21300802 0.7102092 -0.05771042] [-0.28741995 0.31980985 -0.23018652 ... 0.5845511 -0.21329862 0.72692007] [-0.6615692 0.68876815 -0.8743301 ... 0.1087728 -0.26173076 0.47855455] ... [-0.22561137 -0.2892573 -0.07064426 ... 0.47566032 0.8327724 0.40025347] [-0.2982421 -0.27473164 -0.05450544 ... 0.4884972 1.0955367 0.18163365] [-0.4437818 0.00930662 0.07223704 ... 0.17290089 1.1833239 0.07897975]]
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
The BERT models return a map with 3 important keys: `pooled_output`, `sequence_output`, `encoder_outputs`:- `pooled_output` represents each input sequence as a whole. The shape is `[batch_size, H]`. You can think of this as an embedding for the entire movie review.- `sequence_output` represents each input token in the context. The shape is `[batch_size, seq_length, H]`. You can think of this as a contextual embedding for every token in the movie review.- `encoder_outputs` are the intermediate activations of the `L` Transformer blocks. `outputs["encoder_outputs"][i]` is a Tensor of shape `[batch_size, seq_length, 1024]` with the outputs of the i-th Transformer block, for `0 <= i < L`. The last value of the list is equal to `sequence_output`.For the fine-tuning you are going to use the `pooled_output` array. Define your modelYou will create a very simple fine-tuned model, with the preprocessing model, the selected BERT model, one Dense and a Dropout layer.Note: for more information about the base model's input and output you can follow the model's URL for documentation. Here specifically, you don't need to worry about it because the preprocessing model will take care of that for you.
def build_classifier_model(): text_input = tf.keras.layers.Input(shape=(), dtype=tf.string, name='text') preprocessing_layer = hub.KerasLayer(tfhub_handle_preprocess, name='preprocessing') encoder_inputs = preprocessing_layer(text_input) encoder = hub.KerasLayer(tfhub_handle_encoder, trainable=True, name='BERT_encoder') outputs = encoder(encoder_inputs) net = outputs['pooled_output'] net = tf.keras.layers.Dropout(0.1)(net) net = tf.keras.layers.Dense(1, activation=None, name='classifier')(net) return tf.keras.Model(text_input, net)
_____no_output_____
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
Let's check that the model runs with the output of the preprocessing model.
classifier_model = build_classifier_model() bert_raw_result = classifier_model(tf.constant(text_test)) print(tf.sigmoid(bert_raw_result))
tf.Tensor([[0.5890199]], shape=(1, 1), dtype=float32)
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
The output is meaningless, of course, because the model has not been trained yet.Let's take a look at the model's structure.
tf.keras.utils.plot_model(classifier_model)
_____no_output_____
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
Model trainingYou now have all the pieces to train a model, including the preprocessing module, BERT encoder, data, and classifier. Loss functionSince this is a binary classification problem and the model outputs a probability (a single-unit layer), you'll use `losses.BinaryCrossentropy` loss function. More information on the BinaryCrossentropy loss can be found [here](https://www.tensorflow.org/api_docs/python/tf/keras/losses/BinaryCrossentropy).
loss = tf.keras.losses.BinaryCrossentropy(from_logits=True) metrics = tf.metrics.BinaryAccuracy()
_____no_output_____
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
OptimizerFor fine-tuning, let's use the same optimizer that BERT was originally trained with: the "Adaptive Moments" (Adam). This optimizer minimizes the prediction loss and does regularization by weight decay (not using moments), which is also known as [AdamW](https://arxiv.org/abs/1711.05101).For the learning rate (`init_lr`), you will use the same schedule as BERT pre-training: linear decay of a notional initial learning rate, prefixed with a linear warm-up phase over the first 10% of training steps (`num_warmup_steps`). In line with the BERT paper, the initial learning rate is smaller for fine-tuning (best of 5e-5, 3e-5, 2e-5).
epochs = 3 steps_per_epoch = tf.data.experimental.cardinality(train_ds).numpy() num_train_steps = steps_per_epoch * epochs num_warmup_steps = int(0.1*num_train_steps) init_lr = 3e-5 optimizer = optimization.create_optimizer(init_lr=init_lr, num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, optimizer_type='adamw')
_____no_output_____
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
Loading the BERT model and trainingUsing the `classifier_model` you created earlier, you can compile the model with the loss, metric and optimizer.
classifier_model.compile(optimizer=optimizer, loss=loss, metrics=metrics)
_____no_output_____
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
Note: training time will vary depending on the complexity of the BERT model you have selected.
print(f'Training model with {tfhub_handle_encoder}') history = classifier_model.fit(x=train_ds, validation_data=val_ds, epochs=epochs)
Training model with https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-4_H-512_A-8/1 Epoch 1/3 625/625 [==============================] - 290s 453ms/step - loss: 0.4603 - binary_accuracy: 0.7601 - val_loss: 0.3787 - val_binary_accuracy: 0.8374 Epoch 2/3 625/625 [==============================] - 279s 447ms/step - loss: 0.3213 - binary_accuracy: 0.8560 - val_loss: 0.3574 - val_binary_accuracy: 0.8452 Epoch 3/3 625/625 [==============================] - 280s 448ms/step - loss: 0.2537 - binary_accuracy: 0.8921 - val_loss: 0.3812 - val_binary_accuracy: 0.8478
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
Evaluate the modelLet's see how the model performs. Two values will be returned. Loss (a number which represents the error, lower values are better), and accuracy.
loss, accuracy = classifier_model.evaluate(test_ds) print(f'Loss: {loss}') print(f'Accuracy: {accuracy}')
782/782 [==============================] - 152s 195ms/step - loss: 0.3684 - binary_accuracy: 0.8516 Loss: 0.3683711290359497 Accuracy: 0.8515999913215637
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
Plot the accuracy and loss over timeBased on the `History` object returned by `model.fit()`. You can plot the training and validation loss for comparison, as well as the training and validation accuracy. More information on the History object can be found [here](https://machinelearningmastery.com/display-deep-learning-model-training-history-in-keras/).
history_dict = history.history print(history_dict.keys()) acc = history_dict['binary_accuracy'] val_acc = history_dict['val_binary_accuracy'] loss = history_dict['loss'] val_loss = history_dict['val_loss'] epochs = range(1, len(acc) + 1) fig = plt.figure(figsize=(10, 6)) fig.tight_layout() plt.subplot(2, 1, 1) # "bo" is for "blue dot" plt.plot(epochs, loss, 'r', label='Training loss') # b is for "solid blue line" plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') # plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.subplot(2, 1, 2) plt.plot(epochs, acc, 'r', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend(loc='lower right')
dict_keys(['loss', 'binary_accuracy', 'val_loss', 'val_binary_accuracy'])
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
In this plot, the red lines represent the training loss and accuracy, and the blue lines are the validation loss and accuracy. Export for inferenceNow you just save your fine-tuned model for later use.
dataset_name = 'imdb' saved_model_path = './{}_bert'.format(dataset_name.replace('/', '_')) classifier_model.save(saved_model_path, include_optimizer=False)
WARNING:absl:Found untraced functions such as restored_function_body, restored_function_body, restored_function_body, restored_function_body, restored_function_body while saving (showing 5 of 310). These functions will not be directly callable after loading.
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
Let's reload the model, so you can try it side by side with the model that is still in memory.
reloaded_model = tf.saved_model.load(saved_model_path)
_____no_output_____
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
Here you can test your model on any sentence you want, just add to the examples variable below.
def print_my_examples(inputs, results): result_for_printing = \ [f'input: {inputs[i]:<30} : score: {results[i][0]:.6f}' for i in range(len(inputs))] print(*result_for_printing, sep='\n') print() examples = [ 'this is such an amazing movie!', # this is the same sentence tried earlier 'The movie was great!', 'The movie was meh.', 'The movie was okish.', 'The movie was terrible...' ] reloaded_results = tf.sigmoid(reloaded_model(tf.constant(examples))) original_results = tf.sigmoid(classifier_model(tf.constant(examples))) print('Results from the saved model:') print_my_examples(examples, reloaded_results) print('Results from the model in memory:') print_my_examples(examples, original_results)
_____no_output_____
BSD-3-Clause
Classify_text_with_bert.ipynb
Abudhagir/DeepLearningTutorials
Develop Model In this noteook, we will go through the steps to load the ResNet152 model, pre-process the images to the required format and call the model to find the top predictions.
import PIL import numpy as np import torch import torch.nn as nn import torchvision import wget from PIL import Image from torchvision import models, transforms print(torch.__version__) print(torchvision.__version__)
0.4.1.post2 0.2.1
MIT
Pytorch/00_DevelopModel.ipynb
simonzhaoms/AKSDeploymentTutorial
We download the synset for the model. This translates the output of the model to a specific label.
!wget "http://data.dmlc.ml/mxnet/models/imagenet/synset.txt"
--2018-10-09 07:00:23-- http://data.dmlc.ml/mxnet/models/imagenet/synset.txt Resolving data.dmlc.ml... 54.208.175.7 Connecting to data.dmlc.ml|54.208.175.7|:80... connected. HTTP request sent, awaiting response... 200 OK Length: 31675 (31K) [text/plain] Saving to: ‘synset.txt.3’ synset.txt.3 100%[===================>] 30.93K --.-KB/s in 0.002s 2018-10-09 07:00:24 (14.7 MB/s) - ‘synset.txt.3’ saved [31675/31675]
MIT
Pytorch/00_DevelopModel.ipynb
simonzhaoms/AKSDeploymentTutorial
We first load the model which we imported torchvision. This can take about 10s.
%%time model = models.resnet152(pretrained=True)
CPU times: user 1.29 s, sys: 450 ms, total: 1.74 s Wall time: 1.74 s
MIT
Pytorch/00_DevelopModel.ipynb
simonzhaoms/AKSDeploymentTutorial
You can print the summary of the model in the below cell. We cleared the output here for brevity. When you run the cell you should see a list of the layers and the size of the model in terms of number of parameters at the bottom of the output.
model=model.cuda() print(model) print('Number of parameters {}'.format(sum([param.view(-1).size()[0] for param in model.parameters()])))
ResNet( (conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (maxpool): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False) (layer1): Sequential( (0): Bottleneck( (conv1): Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (downsample): Sequential( (0): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (1): Bottleneck( (conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (2): Bottleneck( (conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) ) (layer2): Sequential( (0): Bottleneck( (conv1): Conv2d(256, 128, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (downsample): Sequential( (0): Conv2d(256, 512, kernel_size=(1, 1), stride=(2, 2), bias=False) (1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (1): Bottleneck( (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (2): Bottleneck( (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (3): Bottleneck( (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (4): Bottleneck( (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (5): Bottleneck( (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (6): Bottleneck( (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (7): Bottleneck( (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) ) (layer3): Sequential( (0): Bottleneck( (conv1): Conv2d(512, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (downsample): Sequential( (0): Conv2d(512, 1024, kernel_size=(1, 1), stride=(2, 2), bias=False) (1): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (1): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (2): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (3): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (4): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (5): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (6): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (7): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (8): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (9): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (10): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (11): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (12): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (13): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (14): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (15): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (16): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (17): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (18): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (19): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (20): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (21): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (22): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (23): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (24): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (25): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (26): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (27): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (28): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (29): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (30): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (31): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (32): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (33): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (34): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (35): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) ) (layer4): Sequential( (0): Bottleneck( (conv1): Conv2d(1024, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False) (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (downsample): Sequential( (0): Conv2d(1024, 2048, kernel_size=(1, 1), stride=(2, 2), bias=False) (1): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (1): Bottleneck( (conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (2): Bottleneck( (conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) ) (avgpool): AvgPool2d(kernel_size=7, stride=1, padding=0) (fc): Linear(in_features=2048, out_features=1000, bias=True) ) Number of parameters 60192808
MIT
Pytorch/00_DevelopModel.ipynb
simonzhaoms/AKSDeploymentTutorial
Let's test our model with an image of a Lynx.
wget.download('https://upload.wikimedia.org/wikipedia/commons/thumb/6/68/Lynx_lynx_poing.jpg/220px-Lynx_lynx_poing.jpg') img_path = '220px-Lynx_lynx_poing.jpg' print(Image.open(img_path).size) Image.open(img_path)
(220, 330)
MIT
Pytorch/00_DevelopModel.ipynb
simonzhaoms/AKSDeploymentTutorial
Below, we load the image. Then we compose transformation which resize the image to (224, 224) and then convert it to a PyTorch tensor and normalize the pixel values.
img = Image.open(img_path).convert('RGB') preprocess_input = transforms.Compose([ torchvision.transforms.Resize((224, 224), interpolation=PIL.Image.BICUBIC), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) img = Image.open(img_path) img = preprocess_input(img)
_____no_output_____
MIT
Pytorch/00_DevelopModel.ipynb
simonzhaoms/AKSDeploymentTutorial
Let's make a label look up function to make it easy to lookup the classes from the synset file
def create_label_lookup(): with open('synset.txt', 'r') as f: label_list = [l.rstrip() for l in f] def _label_lookup(*label_locks): return [label_list[l] for l in label_locks] return _label_lookup label_lookup = create_label_lookup()
_____no_output_____
MIT
Pytorch/00_DevelopModel.ipynb
simonzhaoms/AKSDeploymentTutorial
We will apply softmax to the output of the model to get probabilities for each label
softmax = nn.Softmax(dim=1).cuda()
_____no_output_____
MIT
Pytorch/00_DevelopModel.ipynb
simonzhaoms/AKSDeploymentTutorial
Now, let's call the model on our image to predict the top 3 labels. This will take a few seconds.
model = model.eval() %%time with torch.no_grad(): img = img.unsqueeze(0) image_gpu = img.type(torch.float).cuda() outputs = model(image_gpu) probabilities = softmax(outputs) label_lookup = create_label_lookup() probabilities_numpy = probabilities.cpu().numpy().squeeze() top_results = np.flip(np.sort(probabilities_numpy), 0)[:3] labels = label_lookup(*np.flip(probabilities_numpy.argsort(),0)[:3]) dict(zip(labels, top_results))
_____no_output_____
MIT
Pytorch/00_DevelopModel.ipynb
simonzhaoms/AKSDeploymentTutorial
WHAT IS TORCH.NN REALLY
"""MINIST data setup """ from pathlib import Path DATA_PATH = Path("./data") PATH = DATA_PATH/"mnist.pkl" # PATH = DATA_PATH / "mnist" # PATH.mkdir(parents=True, exist_ok=True) # URL = "http://deeplearning.net/data/mnist/" # FILENAME = "mnist.pkl.gz" # if not (PATH / FILENAME).exists(): # content = requests.get(URL + FILENAME).content # (PATH / FILENAME).open("wb").write(content) import pickle with open(PATH.as_posix(), "rb") as f: ((x_train, y_train), (x_valid, y_valid), _) = pickle.load(f, encoding="latin-1") from matplotlib import pyplot import numpy as np pyplot.imshow(x_train[0].reshape((28, 28)), cmap="gray") print(x_train.shape) import torch x_train, y_train, x_valid, y_valid = map( torch.tensor, (x_train, y_train, x_valid, y_valid) ) # https://www.geeksforgeeks.org/python-map-function/ n, c = x_train.shape # x_train, x_train.shape, y_train.min(), y_train.max() print(x_train, y_train) print(x_train.shape) print(y_train.min(), y_train.max()) """Neural net from scratch (no torch.nn) """ import math weights = torch.randn(784, 10) / math.sqrt(784) weights.requires_grad_() bias = torch.zeros(10, requires_grad=True) def log_softmax(x): # https://discuss.pytorch.org/t/what-is-the-difference-between-log-softmax-and-softmax/11801 # https://stackoverflow.com/questions/44790670/torch-sum-a-tensor-along-an-axis # https://stackoverflow.com/questions/57237352/what-does-unsqueeze-do-in-pytorch # https://pytorch.org/docs/stable/notes/broadcasting.html return x - x.exp().sum(-1).log().unsqueeze(-1) def model(xb): # https://stackoverflow.com/questions/5919530/what-is-the-pythonic-way-to-calculate-dot-product return log_softmax(xb @ weights + bias) bs = 64 # batch size xb = x_train[0:bs] # a mini-batch from x preds = model(xb) # predictions # preds[0], preds.shape print(preds[0], preds.shape) # negative log-likelihood # https://stats.stackexchange.com/questions/198038/cross-entropy-or-log-likelihood-in-output-layer def nll(input, target): # https://blog.csdn.net/u010496337/article/details/50574154 return -input[range(target.shape[0]), target].mean() loss_func = nll yb = y_train[0:bs] print(loss_func(preds, yb)) def accuracy(out, yb): preds = torch.argmax(out, dim=1) return (preds==yb).float().mean() # Can only calculate the mean of floating types print(accuracy(preds, yb)) # from IPython.core.debugger import set_trace lr = 0.5 # learning rate epochs = 2 # how many epochs to train for for epoch in range(epochs): for i in range((n - 1) // bs + 1): # set_trace() start_i = i * bs end_i = start_i + bs xb = x_train[start_i:end_i] yb = y_train[start_i:end_i] pred = model(xb) loss = loss_func(pred, yb) loss.backward() with torch.no_grad(): weights -= weights.grad * lr bias -= bias.grad * lr weights.grad.zero_() bias.grad.zero_() print(loss_func(model(xb), yb), accuracy(model(xb), yb)) """Using torch.nn.functional - making our code one or more of: shorter, more understandable, and/or more flexible. """ # This module contains all the functions in the torch.nn library # (whereas other parts of the library contain classes) import torch.nn.functional as F loss_func = F.cross_entropy def model(xb): return xb @ weights + bias print(loss_func(model(xb), yb), accuracy(model(xb), yb)) """Refactor using nn.Module """ from torch import nn class Mnist_Logistic(nn.Module): def __init__(self): super().__init__() self.weights = nn.Parameter(torch.randn(784, 10) / math.sqrt(784)) self.bias = nn.Parameter(torch.zeros(10)) def forward(self, xb): return xb @ self.weights + self.bias model = Mnist_Logistic() print(loss_func(model(xb), yb)) def fit(): for epoch in range(epochs): for i in range((n - 1) // bs + 1): start_i = i * bs end_i = start_i + bs xb = x_train[start_i:end_i] yb = y_train[start_i:end_i] pred = model(xb) loss = loss_func(pred, yb) loss.backward() with torch.no_grad(): for p in model.parameters(): p -= p.grad * lr model.zero_grad() fit() print(loss_func(model(xb), yb)) """Refactor using nn.Linear """ class Mnist_Logistic(nn.Module): def __init__(self): super().__init__() self.lin = nn.Linear(784, 10) def forward(self, xb): return self.lin(xb) model = Mnist_Logistic() fit() print(loss_func(model(xb), yb)) """Refactor using optim """ from torch import optim def get_model(): model = Mnist_Logistic() return model, optim.SGD(model.parameters(), lr=lr) model, opt = get_model() print(loss_func(model(xb), yb)) for epoch in range(epochs): for i in range((n - 1) // bs + 1): start_i = i * bs end_i = start_i + bs xb = x_train[start_i:end_i] yb = y_train[start_i:end_i] pred = model(xb) loss = loss_func(pred, yb) loss.backward() opt.step() opt.zero_grad() print(loss_func(model(xb), yb)) """Refactor using Dataset - PyTorch’s TensorDataset is a Dataset wrapping tensors. By defining a length and way of indexing, this also gives us a way to iterate, index, and slice along the first dimension of a tensor. This will make it easier to access both the independent and dependent variables in the same line as we train. """ from torch.utils.data import TensorDataset train_ds = TensorDataset(x_train, y_train) model, opt = get_model() for epoch in range(epochs): for i in range((n - 1) // bs + 1): xb, yb = train_ds[i * bs: i * bs + bs] pred = model(xb) loss = loss_func(pred, yb) loss.backward() opt.step() opt.zero_grad() print(loss_func(model(xb), yb)) """Refactor using DataLoader -Pytorch’s DataLoader is responsible for managing batches. You can create a DataLoader from any Dataset. DataLoader makes it easier to iterate over batches. Rather than having to use train_ds[i*bs : i*bs+bs], the DataLoader gives us each minibatch automatically. """ from torch.utils.data import DataLoader train_ds = TensorDataset(x_train, y_train) train_dl = DataLoader(train_ds, batch_size=bs) model, opt = get_model() for epoch in range(epochs): for xb, yb in train_dl: pred = model(xb) loss = loss_func(pred, yb) loss.backward() opt.step() opt.zero_grad() print(loss_func(model(xb), yb)) """Add Validation - Shuffling the training data is important to prevent correlation between batches and overfitting """ train_ds = TensorDataset(x_train, y_train) train_dl = DataLoader(train_ds, batch_size=bs, shuffle=True) valid_ds = TensorDataset(x_valid, y_valid) valid_dl = DataLoader(valid_ds, batch_size=bs * 2) model, opt = get_model() for epoch in range(epochs): # Note that we always call model.train() before training, and model.eval() before inference, # because these are used by layers such as nn.BatchNorm2d and nn.Dropout # to ensure appropriate behaviour for these different phases model.train() for xb, yb in train_dl: pred = model(xb) loss = loss_func(pred, yb) loss.backward() opt.step() opt.zero_grad() model.eval() with torch.no_grad(): valid_loss = sum(loss_func(model(xb), yb) for xb, yb in valid_dl) print(epoch, valid_loss / len(valid_dl)) """Create fit() and get_data() """ def loss_batch(model, loss_func, xb, yb, opt=None): loss = loss_func(model(xb), yb) if opt is not None: loss.backward() opt.step() opt.zero_grad() return loss.item(), len(xb) def get_data(train_ds, valid_ds, bs): return ( DataLoader(train_ds, batch_size=bs, shuffle=True), DataLoader(valid_ds, batch_size=bs * 2), ) import numpy as np def fit(epochs, model, loss_func, opt, train_dl, valid_dl): for epoch in range(epochs): model.train() for xb, yb in train_dl: loss_batch(model, loss_func, xb, yb, opt) model.eval() with torch.no_grad(): losses, nums = zip( *[loss_batch(model, loss_func, xb, yb) for xb, yb in valid_dl] ) val_loss = np.sum(np.multiply(losses, nums)) / np.sum(nums) print(epoch, val_loss) train_dl, valid_dl = get_data(train_ds, valid_ds, bs) model, opt = get_model() fit(epochs, model, loss_func, opt, train_dl, valid_dl) """Switch to CNN """ class Mnist_CNN(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(1, 16, kernel_size=3, stride=2, padding=1) self.conv2 = nn.Conv2d(16, 16, kernel_size=3, stride=2, padding=1) self.conv3 = nn.Conv2d(16, 10, kernel_size=3, stride=2, padding=1) def forward(self, xb): xb = xb.view(-1, 1, 28, 28) xb = F.relu(self.conv1(xb)) xb = F.relu(self.conv2(xb)) xb = F.relu(self.conv3(xb)) xb = F.avg_pool2d(xb, 4) return xb.view(-1, xb.size(1)) lr = 0.1 model = Mnist_CNN() opt = optim.SGD(model.parameters(), lr=lr, momentum=0.9) fit(epochs, model, loss_func, opt, train_dl, valid_dl) """nn Sequential """ class Lambda(nn.Module): def __init__(self, func): super().__init__() self.func = func def forward(self, x): return self.func(x) def preprocess(x): return x.view(-1, 1, 28, 28) model = nn.Sequential( Lambda(preprocess), nn.Conv2d(1, 16, kernel_size=3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(16, 16, kernel_size=3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(16, 10, kernel_size=3, stride=2, padding=1), nn.ReLU(), nn.AvgPool2d(4), Lambda(lambda x: x.view(x.size(0), -1)), ) opt = optim.SGD(model.parameters(), lr=lr, momentum=0.9) fit(epochs, model, loss_func, opt, train_dl, valid_dl) """Wrapping DataLoader """ def preprocess(x, y): return x.view(-1, 1, 28, 28), y class WrappedDataLoader: def __init__(self, dl, func): self.dl = dl self.func = func def __len__(self): return len(self.dl) def __iter__(self): batches = iter(self.dl) for b in batches: yield (self.func(*b)) train_dl, valid_dl = get_data(train_ds, valid_ds, bs) train_dl = WrappedDataLoader(train_dl, preprocess) valid_dl = WrappedDataLoader(valid_dl, preprocess) model = nn.Sequential( nn.Conv2d(1, 16, kernel_size=3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(16, 16, kernel_size=3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(16, 10, kernel_size=3, stride=2, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1), Lambda(lambda x: x.view(x.size(0), -1)), ) opt = optim.SGD(model.parameters(), lr=lr, momentum=0.9) fit(epochs, model, loss_func, opt, train_dl, valid_dl) """Using your GPU """ dev = torch.device( "cuda") if torch.cuda.is_available() else torch.device("cpu") def preprocess(x, y): return x.view(-1, 1, 28, 28).to(dev), y.to(dev) train_dl, valid_dl = get_data(train_ds, valid_ds, bs) train_dl = WrappedDataLoader(train_dl, preprocess) valid_dl = WrappedDataLoader(valid_dl, preprocess) model.to(dev) opt = optim.SGD(model.parameters(), lr=lr, momentum=0.9) fit(epochs, model, loss_func, opt, train_dl, valid_dl)
_____no_output_____
MIT
src/DQN/pytorch_tutorial/06-WHAT IS TORCH.NN REALLY.ipynb
BepfCp/RL-imple
Integrated Project 1: Video Game The goal of this project is to:
import pandas as pd import numpy as np from scipy import stats as st import matplotlib.pyplot as plt import matplotlib.patches as mpatches import re, math
_____no_output_____
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
Project Description You work for the online store Ice, which sells video games all over the world. User and expert reviews, genres, platforms (e.g. Xbox or PlayStation), and historical data on game sales are available from open sources. You need to identify patterns that determine whether a game succeeds or not. This will allow you to spot potential big winners and plan advertising campaigns.In front of you is data going back to 2016. Let’s imagine that it’s December 2016 and you’re planning a campaign for 2017.(The important thing is to get experience working with data. It doesn't really matter whether you're forecasting 2017 sales based on data from 2016 or 2027 sales based on data from 2026.)The dataset contains the abbreviation ESRB. The Entertainment Software Rating Board evaluates a game's content and assigns an age rating such as Teen or Mature. Table of Contents - [The Goal](goal)- [Step 0](imports): Imports- [Step 1](step1): Open the data file and study the general information - [Step 1 conclusion](step1con)- [Step 2](step2): Prepare the data - [Names](step2name) - [Year of Release](step2year) - [Sales](step2sales) - [Score](step2scores) - [Ratings](step2ratings) - [Step 2 conclusion](step2con)- [Step 3](step3): Analyze the data - [Step 3 conclusion](step3con)- [Step 4](step4): Analyze the data - [Step 4 conclusion](step4con)- [Step 5](step5): Test the hypotheses - [Hypothesis 1](step5h1): The average revenue from users of Ultimate and Surf calling plans differs - [Hypothesis 2](step5h2): The average revenue from users in NY-NJ area is different from that of the users from other regions - [Step 5 conclusion](step5con)- [Step 6](step6): Write an overall conclusion Step 1. Open the data file and study the general information
raw_games_data = pd.read_csv('/datasets/games.csv') games_data = raw_games_data games_data.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 16715 entries, 0 to 16714 Data columns (total 11 columns): Name 16713 non-null object Platform 16715 non-null object Year_of_Release 16446 non-null float64 Genre 16713 non-null object NA_sales 16715 non-null float64 EU_sales 16715 non-null float64 JP_sales 16715 non-null float64 Other_sales 16715 non-null float64 Critic_Score 8137 non-null float64 User_Score 10014 non-null object Rating 9949 non-null object dtypes: float64(6), object(5) memory usage: 1.4+ MB
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
Step 1 conclusion We do have some nulls, and in some columns, such as the Ratings, there are a lot. To work with the information, we will need to replace the column names with lowercase text, and acknowledge the following issues:Name:- There are two nulls, and in the information, they are also lacking genres, critic/user scores, and an ESRB rating. Because there are only 2 of 16715 entries, these should be removed.Year_of_Release:- We need to fill in the nulls. Some of the sports games have the year in the name (for example, 'Madden NFL 2004') so we will try to utilize those. Then we will try to fill in games with multiple platforms, but the year is only missing from one of the platforms. Otherwise, we will fill based on the mode.- We need to change the types of this column to integers.Genre:- The only nulls are from the same two nulls mentioned in the Name column. so these will be taken care of as well.Sales:- The sales has a significant amount of zeros. These may be the result of consoles not sold in some countries, or the game itself not being sold in some countries. We would want to look at this further to see if something is going on here. Specifically for the Other sales, this seems to be the lowest category of purchasers of video games, and the zero seems to be more of an acceptable amount here.Scores:- Scores have a large amount of missing data. This will need to be filled in, most likely with averages based on the copies sold. Popular games that sell well will likely be higher rated.- Critic score will need to be changed to an integer as it is a 0 to 100 score, and the user score will need to be changed to a float. - TBDs in the user score column oddly seem related games that are based off of movies/TV and brands. This may be an issue related to Rating: - ESRB rating also has a significant number of missing values. We will likely need to figure out the most common with the mode. Some are more intuitive than others, such as shooters would tend to be more M for Mature. Step 2. Prepare the data First for the entire dataset, we will need to replace the column names with lowercase text.
games_data.columns = [x.lower() for x in games_data.columns]
_____no_output_____
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
Name The two nulls of the set may just be failures in the data gather process, as the name of the game is the principle identifier. Because there are only 2 of 16715 entries, these should be removed.
games_data.drop(games_data[games_data['name'].isnull()].index, inplace=True)
_____no_output_____
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
Year of Release The years may be missing because this data seems focused on sales. The data may not prioritize the year then. First, we can attempt to draw information directly from the title. Some of the sports games, such as 'Madden NFL 2004' have the year in the name.
check_years = games_data.query('year_of_release.isnull()') for i, row in check_years.iterrows(): try: year = int(x = re.findall("[0-9][0-9][0-9][0-9]", row['name'])) except: continue games_data.loc[i, 'year_of_release'] = year check_years = games_data.query('year_of_release.isnull()') for i, row in check_years.iterrows(): try: year = int(row['name'][-2:]) except: continue if year > 80: year += 1900 elif year < 20: year += 2000 else: continue games_data.loc[i, 'year_of_release'] = year
_____no_output_____
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
After that, we can try to see if some years are missing, but the same game but for a different platform has the year.
check_years = games_data.query('year_of_release.isnull()') check_against = games_data.query('year_of_release.notnull()') for i, row in check_years.iterrows(): name = row['name'] multiplatform = check_against.query('name == @name') if len(multiplatform): year = list(multiplatform['year_of_release'])[0] games_data.loc[i, 'year_of_release'] = year
_____no_output_____
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
Anything left over we can fill by using the mode based on the platform. As platforms are done in generations, they typically are popular for only a few consecutive years until the next console is released. Therefore, it should be fine to use the mode.
check_years = games_data.query('year_of_release.isnull()') check_against = games_data.query('year_of_release.notnull()') keys = check_against.platform.unique() values = list(check_against.groupby('platform')['year_of_release'].agg(pd.Series.mode)) reference = {keys[i]: values[i] for i in range(len(keys))} for i,val in check_years.platform.iteritems(): replace = reference[val] if not isinstance(replace, float): replace = replace[0] games_data.loc[i,'year_of_release'] = replace
_____no_output_____
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
Lastly, because they are years, we need to change them to integers.
games_data['year_of_release'] = pd.to_numeric(games_data['year_of_release'], downcast='integer')
_____no_output_____
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
Sales Lets take a look at the sales by platform.
check = games_data[['platform', 'na_sales', 'eu_sales', 'jp_sales']] values = check.groupby('platform').mean() print(values)
na_sales eu_sales jp_sales platform 2600 0.681203 0.041128 0.000000 3DO 0.000000 0.000000 0.033333 3DS 0.160558 0.118231 0.193596 DC 0.104423 0.032500 0.164615 DS 0.177778 0.087815 0.081623 GB 1.166531 0.487959 0.868571 GBA 0.228151 0.091545 0.057579 GC 0.240036 0.069622 0.038813 GEN 0.713704 0.204444 0.098889 GG 0.000000 0.000000 0.040000 N64 0.435799 0.128715 0.107273 NES 1.285102 0.215816 1.006633 NG 0.000000 0.000000 0.120000 PC 0.097053 0.146242 0.000175 PCFX 0.000000 0.000000 0.030000 PS 0.281136 0.178454 0.116809 PS2 0.270171 0.157006 0.064415 PS3 0.295635 0.248152 0.060248 PS4 0.277398 0.359923 0.040714 PSP 0.090298 0.055153 0.063507 PSV 0.029256 0.030512 0.050953 SAT 0.004162 0.003121 0.186474 SCD 0.166667 0.060000 0.075000 SNES 0.256192 0.079665 0.487657 TG16 0.000000 0.000000 0.080000 WS 0.000000 0.000000 0.236667 Wii 0.376439 0.198644 0.052523 WiiU 0.259184 0.170952 0.088503 X360 0.477393 0.214548 0.009849 XB 0.226566 0.073968 0.001675 XOne 0.377004 0.208866 0.001377
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
Initially the zeros look like problems with our data, but after some research, it appears that these represent a lack of console based sales. For example, the Atari 2600 shows zero sales for Japan, but the Atari 2600 was not sold in Japan. Instead, a console labelled the Atari 2800 was. Similarly, the Game Gear (Presumably the GG item) was a Japanese based handheld console, which is why there are zero sales in NA and EU.We would like to use the total sales later on, so we should add a global sales column.
games_data.insert(loc=8, column='total_sales', value=0.0) for i, row in games_data.iterrows(): games_data.loc[i,'total_sales'] = row['na_sales'] + row['eu_sales'] + row['jp_sales'] + row['other_sales'] games_data.sort_values(['total_sales'], ascending=False)
_____no_output_____
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
Scores Similar to the years, the scores may not be prioritized in the origination of the data. Because the scores have a lot of missing data, filling directly by an average may significantly weight the data and give biased results. We want to localize the information so we will get rolling averages by genre and total sales. Theoretically, the community of gamers likely are based on genre, so gamers interested in racing games would likely pick up more racing games and have a better understanding of what makes a racing game good or bad. Similarly, better scoring games should get better traction in sales, so that will be the other factor.First we will start with the critic scores.
check = games_data.sort_values(['genre', 'total_sales'], ascending=(True, False)) check_critic_null = check.query('critic_score.isnull()') for i, row in check_critic_null.iterrows(): up, down, new_val = 1, 1, np.nan genre = row['genre'] try: while pd.isna(check.loc[i-up, 'critic_score']): if check.loc[i-up, 'genre'] != genre: up = -1 break up += 1 except: up=-1 try: while pd.isna(check.loc[i+down, 'critic_score']): if check.loc[i+down, 'genre'] != genre: down = -1 break down += 1 except: down=-1 if up != -1 and down != -1: new_val = int((check.loc[i-up, 'critic_score'] + check.loc[i+down, 'critic_score'])/2) elif up != -1: new_val = check.loc[i-up, 'critic_score'] elif down != -1: new_val = check.loc[i+down, 'critic_score'] elif pd.notna(check.loc[i, 'user_score']) and check.loc[i, 'user_score'] != 'tbd': new_val = int(float(check.loc[i, 'user_score'])*10) games_data.loc[i, 'critic_score'] = new_val games_data.info()
<class 'pandas.core.frame.DataFrame'> Int64Index: 16713 entries, 0 to 16714 Data columns (total 12 columns): name 16713 non-null object platform 16713 non-null object year_of_release 16713 non-null int16 genre 16713 non-null object na_sales 16713 non-null float64 eu_sales 16713 non-null float64 jp_sales 16713 non-null float64 other_sales 16713 non-null float64 total_sales 16713 non-null float64 critic_score 14354 non-null float64 user_score 10014 non-null object rating 9949 non-null object dtypes: float64(6), int16(1), object(5) memory usage: 2.2+ MB
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
Left over NaN values should be because there are no genre specific scores. This is certainly possible with the amount of missing values. Now we should try to base it on the total sales and not have it genre specific. Lastly, if there are still values left, we should use the user value to determine the critic value.
check = games_data.sort_values(['total_sales'], ascending=False) check_critic_null = check.query('critic_score.isnull()') for i, row in check_critic_null.iterrows(): up, down, new_val = 1, 1, np.nan try: while pd.isna(check.loc[i-up, 'critic_score']): up += 1 except: up=-1 try: while pd.isna(check.loc[i+down, 'critic_score']): down += 1 except: down=-1 if up != -1 and down != -1: new_val = int((check.loc[i-up, 'critic_score'] + check.loc[i+down, 'critic_score'])/2) elif up != -1: new_val = check.loc[i-up, 'critic_score'] elif down != -1: new_val = check.loc[i+down, 'critic_score'] elif pd.notna(check.loc[i, 'user_score']) and check.loc[i, 'user_score'] != 'tbd': new_val = int(float(check.loc[i, 'user_score'])*10) if new_val != np.nan: games_data.loc[i, 'critic_score'] = new_val games_data.info()
<class 'pandas.core.frame.DataFrame'> Int64Index: 16713 entries, 0 to 16714 Data columns (total 12 columns): name 16713 non-null object platform 16713 non-null object year_of_release 16713 non-null int16 genre 16713 non-null object na_sales 16713 non-null float64 eu_sales 16713 non-null float64 jp_sales 16713 non-null float64 other_sales 16713 non-null float64 total_sales 16713 non-null float64 critic_score 16713 non-null float64 user_score 10014 non-null object rating 9949 non-null object dtypes: float64(6), int16(1), object(5) memory usage: 2.2+ MB
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
Now we can repeat the same process with user scores. In user scores, there are TBD values. These values are most likely due to the sample size requirements of the score. Looking at the data, a majority of the TBD values appear to be on low selling games, and therefore are 'waiting' for a certain number of user scores to determine it is an acceptable sized survey. We can treat these the same as if they were NaN values.
check_user_null = check.query('user_score.isnull()') for i, row in check_user_null.iterrows(): up, down, new_val = 1, 1, -1 genre = row['genre'] try: while pd.isna(check.loc[i-up, 'user_score']) or check.loc[i-up, 'user_score'] == 'tbd': if check.loc[i-up, 'genre'] != genre: up = -1 break up += 1 except: up=-1 try: while pd.isna(check.loc[i+down, 'user_score']) or check.loc[i+down, 'user_score'] == 'tbd': if check.loc[i+down, 'genre'] != genre: down = -1 break down += 1 except: down=-1 if up != -1 and down != -1: new_val = (float(check.loc[i-up, 'user_score']) + float(check.loc[i+down, 'user_score']))/2 elif up != -1: new_val = check.loc[i-up, 'user_score'] elif down != -1: new_val = check.loc[i+down, 'user_score'] if new_val != -1: games_data.loc[i, 'user_score'] = round(float(new_val),1) games_data.info() for i, row in games_data.iterrows(): if row['user_score'] == 'tbd' or row['user_score'] is np.nan: games_data.loc[i, 'user_score'] = round(row['critic_score']/10, 1)
_____no_output_____
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
The critic score are integers on a scale from 1 to 100, and the user scores are floats from 0.0 to 10.0, so we need to cast them as such.
games_data['critic_score'] = pd.to_numeric(games_data['critic_score'], downcast='integer') games_data['user_score'] = pd.to_numeric(games_data['user_score'], downcast='float') games_data.info()
<class 'pandas.core.frame.DataFrame'> Int64Index: 16713 entries, 0 to 16714 Data columns (total 12 columns): name 16713 non-null object platform 16713 non-null object year_of_release 16713 non-null int16 genre 16713 non-null object na_sales 16713 non-null float64 eu_sales 16713 non-null float64 jp_sales 16713 non-null float64 other_sales 16713 non-null float64 total_sales 16713 non-null float64 critic_score 16713 non-null int8 user_score 16713 non-null float32 rating 9949 non-null object dtypes: float32(1), float64(5), int16(1), int8(1), object(4) memory usage: 2.0+ MB
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
Ratings
check_rating = games_data.query('rating.isnull()') check_against = games_data.query('rating.notnull()') import sys import warnings if not sys.warnoptions: warnings.simplefilter("ignore") check_against['keys'] = check_against.platform+"."+check_against.genre keys = list(check_against['keys'].unique()) values = list(check_against.groupby(['platform', 'genre'])['rating'].agg(pd.Series.mode)) print(check_against.groupby(['platform', 'genre'])['rating'].agg(pd.Series.mode)) reference = {keys[i]: values[i] for i in range(len(values))} for i,row in check_rating.iterrows(): check = row.platform + "." + row.genre try: replace = reference[check] games_data.loc[i,'rating'] = replace except: continue check_rating = games_data.query('rating.isnull()') check_against = games_data.query('rating.notnull()') check_rating_null = games_data.query('rating.isnull()') for i, row in check_critic_null.iterrows(): up, down, new_val = 1, 1, np.nan try: while pd.isna(games_data.loc[i-up, 'rating']): up += 1 except: up=-1 try: while pd.isna(games_data.loc[i+down, 'rating']): down += 1 except: down=-1 if up != -1 and down != -1: if up < down: new_val = games_data.loc[i-up, 'rating'] else: new_val = games_data.loc[i+down, 'rating'] elif up != -1: new_val = games_data.loc[i-up, 'rating'] elif down != -1: new_val = games_data.loc[i+down, 'rating'] else: genre = row['genre'] new_val = games_data.groupby(['genre'])['rating'].agg(pd.Series.mode).loc[genre] games_data.loc[i, 'rating'] = new_val games_data.info() keys = check_against.genre.unique() values = list(check_against.groupby(['genre'])['rating'].agg(pd.Series.mode)) reference = {keys[i]: values[i] for i in range(len(values))} for i,row in check_rating.iterrows(): check = row.genre try: replace = reference[check] games_data.loc[i,'rating'] = replace except: continue games_data.info()
<class 'pandas.core.frame.DataFrame'> Int64Index: 16713 entries, 0 to 16714 Data columns (total 12 columns): name 16713 non-null object platform 16713 non-null object year_of_release 16713 non-null int16 genre 16713 non-null object na_sales 16713 non-null float64 eu_sales 16713 non-null float64 jp_sales 16713 non-null float64 other_sales 16713 non-null float64 total_sales 16713 non-null float64 critic_score 16713 non-null int8 user_score 16713 non-null float32 rating 16713 non-null object dtypes: float32(1), float64(5), int16(1), int8(1), object(4) memory usage: 2.0+ MB
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
Lastly, it turns out that K-A was a rating that is the same as E, as K-A is kids through adults, and was later changed to mean E. We should change that in this data as well.
games_data.loc[games_data['rating'] == "K-A", "rating"] = "E" games_data.info()
<class 'pandas.core.frame.DataFrame'> Int64Index: 16713 entries, 0 to 16714 Data columns (total 12 columns): name 16713 non-null object platform 16713 non-null object year_of_release 16713 non-null int16 genre 16713 non-null object na_sales 16713 non-null float64 eu_sales 16713 non-null float64 jp_sales 16713 non-null float64 other_sales 16713 non-null float64 total_sales 16713 non-null float64 critic_score 16713 non-null int8 user_score 16713 non-null float32 rating 16713 non-null object dtypes: float32(1), float64(5), int16(1), int8(1), object(4) memory usage: 2.0+ MB
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
All of the ratings are now filled in. Step 2 Conclusion All of the data has been cleaned and filled in. There are no longer any missing values, and there are no more obtuse values such as TBD. All of the characteristics are their correct types, and are adequately downsized to optimized types. Step 3. Analyze the data - Look at how many games were released in different years. Is the data for every period significant?- Look at how sales varied from platform to platform. Choose the platforms with the greatest total sales and build a distribution based on data for each year. Find platforms that used to be popular but now have zero sales. How long does it generally take for new platforms to appear and old ones to fade?- Determine what period you should take data for. To do so, look at your answers to the previous questions. The data should allow you to build a prognosis for 2017.- Work only with the data that you've decided is relevant. Disregard the data for previous years.- Which platforms are leading in sales? Which ones are growing or shrinking? Select several potentially profitable platforms.- Build a box plot for the global sales of all games, broken down by platform. Are the differences in sales significant? What about average sales on various platforms? Describe your findings.- Take a look at how user and professional reviews affect sales for one popular platform (you choose). Build a scatter plot and calculate the correlation between reviews and sales. Draw conclusions.- Keeping your conclusions in mind, compare the sales of the same games on other platforms.- Take a look at the general distribution of games by genre. What can we say about the most profitable genres? Can you generalize about genres with high and low sales? First lets look at the total sales by release year.
total_years = games_data.year_of_release.max()-games_data.year_of_release.min() games_data.year_of_release.hist(bins=total_years) plt.ylabel('Total Sales') plt.xlabel('Year') plt.title('Distribution of Sales by Year') plt.show()
_____no_output_____
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
There appears to be an early tail, most likely when gaming had not yet fully joined the ranks of pop culture that we know it has today. This delay is likely due to consumer access and early technology. It can be compared to the cell phone we know today. It used to be a large brick that had a large price tag of nearly //$4,000 and was extremely limited battery life of about 30 minutes, as mentioned by [this NBC article](https://www.nbcnews.com/id/wbna7432915).This was not seen as something really necessary for anyone but wealthy business leaders. Soon, technology became cheaper and now most citizens of developed countries have a cell phone.That being said, lets remove this time period needed for gaming to take off.
q1 = games_data.year_of_release.quantile(q=.25) q3 = games_data.year_of_release.quantile(q=.75) IQR = q3-q1 games_data = games_data.query('year_of_release > @q1 - @IQR*1.5') total_years = games_data.year_of_release.max()-games_data.year_of_release.min() games_data.year_of_release.hist(bins=total_years) plt.ylabel('Total Sales') plt.xlabel('Year') plt.title('Distribution of Sales by Year') plt.show()
_____no_output_____
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
Now lets try to filter out the less popular platforms. Also, as we are trying to predict near future results, we need to make sure that the consoles are still selling games in the most recent year. Otherwise, they will not be selling games in 2017 either.
grouped_platform_sales = games_data.groupby(['platform', 'year_of_release'])['total_sales'].agg(['sum', 'count']) plats = [] for platform, df in grouped_platform_sales.groupby(level=0): #print(df.index) keep = df.index.isin(['2016'], level='year_of_release') #print(df) if 1 in keep: plats.append(platform) print(plats)
['3DS', 'PC', 'PS3', 'PS4', 'PSV', 'Wii', 'WiiU', 'X360', 'XOne']
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
To understand each platform's performance, we need to calculate the total number of sales per year, per platform.
usable_platforms = grouped_platform_sales[grouped_platform_sales.index.get_level_values('platform').isin(plats)] print(usable_platforms) clean_games_data = games_data.query('platform.isin(@plats)')
sum count platform year_of_release 3DS 1993 0.40 1 1999 0.47 5 2000 0.02 1 2010 0.30 1 2011 63.20 116 ... ... ... X360 2016 1.52 13 XOne 2013 18.96 19 2014 54.07 61 2015 60.14 80 2016 26.15 87 [101 rows x 2 columns]
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
There are a few games that are highly skewing the results, such as Wii Sports, that may be diamonds in the rough, and can not be used to predict future sales.
q1 = clean_games_data.total_sales.quantile(q=.25) q3 = clean_games_data.total_sales.quantile(q=.75) IQR = q3-q1 filtered_clean_games_data = clean_games_data.query('total_sales < @q3 + @IQR*1.5') total_years = clean_games_data.year_of_release.max()-clean_games_data.year_of_release.min() plat_count = clean_games_data.pivot_table(values= 'total_sales', index='year_of_release', columns='platform', aggfunc='sum', fill_value=0) filtered_plat_count = filtered_clean_games_data.pivot_table(values= 'total_sales', index='year_of_release', columns='platform', aggfunc='sum', fill_value=0) # This is to make sure that colors are different with a large number of different colored bars in our graphs def floatRgb(mag, cmin, cmax): """ Return a tuple of floats between 0 and 1 for R, G, and B. """ # Normalize to 0-1 try: x = float(mag-cmin)/(cmax-cmin) except ZeroDivisionError: x = 0.5 # cmax == cmin blue = min((max((4*(0.75-x), 0.)), 1.)) red = min((max((4*(x-0.25), 0.)), 1.)) green = min((max((4*math.fabs(x-0.5)-1., 0.)), 1.)) return red, green, blue def rgb(mag, cmin, cmax): """ Return a tuple of integers, as used in AWT/Java plots. """ red, green, blue = floatRgb(mag, cmin, cmax) return int(red*255), int(green*255), int(blue*255) def strRgb(mag, cmin, cmax): """ Return a hex string, as used in Tk plots. """ return "#%02x%02x%02x" % rgb(mag, cmin, cmax) # Plotting plots = [clean_games_data, filtered_clean_games_data] plot_totals = [plat_count, filtered_plat_count] for plot in range(len(plots)): plt.figure(figsize=(16,8)) print(plots[plot].platform.unique()) color_vals = [] #rotates through the platforms for i in range(len(plots[plot].platform.unique())): num = i*1/len(plots[plot].platform.unique()) color = strRgb(num,0,1) color_vals.append(color) # Creating dictionaries with colors colors = {i: color_vals[i] for i in range(len(color_vals))} vals = list(plots[plot].platform.unique()) platforms = {i: vals[i] for i in range(len(vals))} # Plotting in a loop for i in range(len(plot_totals[plot].index)): year = plot_totals[plot].index[i] year_data = plot_totals[plot].loc[year] baseline = 0 color_index = 0 for j in year_data: plt.bar(x = i, height = j, bottom = baseline, color=colors[color_index]) baseline += j color_index += 1 plt.xticks(np.arange(len(plot_totals[plot].index)), plot_totals[plot].index, rotation = 270); # Creating legend patches = list() for i in reversed(range(len(plots[plot].platform.unique()))): patch = mpatches.Patch(color = colors[i], label = plot_totals[plot].columns[i]) patches.append(patch) plt.legend(handles=patches, fontsize=12, framealpha=1) # Some additioanl plot prep plt.rcParams['axes.axisbelow'] = True plt.grid(color='gray', linestyle='dashed') plt.ylabel('Amount of Sales') plt.xlabel('Year') plt.title('Number of Games by Year and Platform');
['Wii' 'X360' 'PS3' 'PS4' '3DS' 'PC' 'XOne' 'WiiU' 'PSV'] ['PC' 'Wii' 'PS3' 'XOne' 'X360' 'WiiU' '3DS' 'PS4' 'PSV']
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
Reviewer's comment v. 1: AN excellent graphs, but Ridgeplots can be useful here: https://matplotlib.org/matplotblog/posts/create-ridgeplots-in-matplotlib/ We can see a large boost of games sold around 2009 through 2011, primarily for the success of the Wii, PS3, and Xbox 360 consoles. After that burst, the sales drop, and then next gen consoles become popular, but not at the same level and are already falling well below previous years by 2016.To make a prediction for the next year, we need to attempt a parabolic trend, as it will be based on the growth or decay of the popularity of the platforms, and it should also represent how quickly the platforms are coming in and out of popularity. We can see in the above plots on a single platform basis that there are parabolic trends where there is not enough time yet for game developers to create games for a brand new platform, they get that time to make it, and over time the platform becomes outdated, and developers and consumers both prepare for the new consoles. In particular, consumers may want to save money on video games if they believe a platform is nearing the end of its stride, and would want to be financially ready for the next platform. This parabolic trend tends to line up for platforms, as major competing consoles launch at the same time. For example, the playstation series from Sony typically launches around the same time as Microsoft's Xbox line to drive sales with competition.
predicting_2017 = filtered_clean_games_data.query('year_of_release.isin([2014, 2015, 2016])') temp = pd.pivot_table(predicting_2017, values='total_sales', index='platform', columns='year_of_release', aggfunc='sum') def calc_parabola_vertex(x1, y1, x2, y2, x3, y3): denom = (x1-x2) * (x1-x3) * (x2-x3); A = (x3 * (y2-y1) + x2 * (y1-y3) + x1 * (y3-y2)) / denom; B = (x3*x3 * (y1-y2) + x2*x2 * (y3-y1) + x1*x1 * (y2-y3)) / denom; C = (x2 * x3 * (x2-x3) * y1+x3 * x1 * (x3-x1) * y2+x1 * x2 * (x1-x2) * y3) / denom; return A,B,C for i, row in temp.iterrows(): x1, y1 = [2014, row[2014]] x2, y2 = [2015, row[2015]] x3, y3 = [2016, row[2016]] a, b, c = calc_parabola_vertex(x1, y1, x2, y2, x3, y3) new_val=(a*(2017**2))+(b*2017)+c if new_val > 0: temp.loc[i, 2017] = new_val else: temp.loc[i, 2017] = 0 temp
_____no_output_____
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
Now that we have the estimated amounts of sales per platform, we need to integrate it into our sales graph.
filtered_plat_count = filtered_plat_count.append(temp[2017]) print(temp[2017].sum()) # Plotting plots = [filtered_clean_games_data] plot_totals = [filtered_plat_count] for plot in range(len(plots)): plt.figure(figsize=(16,8)) print(plots[plot].platform.unique()) color_vals = [] for i in range(len(plots[plot].platform.unique())): num = i*1/len(plots[plot].platform.unique()) color = strRgb(num,0,1) color_vals.append(color) # Creating dictionaries with colors and cancelaltion causes colors = {i: color_vals[i] for i in range(len(color_vals))} vals = list(plots[plot].platform.unique()) platforms = {i: vals[i] for i in range(len(vals))} # Plotting in a loop for i in range(len(plot_totals[plot].index)): year = plot_totals[plot].index[i] year_data = plot_totals[plot].loc[year] baseline = 0 color_index = 0 for j in year_data: plt.bar(x = i, height = j, bottom = baseline, color=colors[color_index]) baseline += j color_index += 1 #plt.text(x = i, y = plat_count[i] + 0.05, s = round(plat_count[i], 1), \ #ha = 'center', fontsize=13) # for j in year_data: # plt.bar(x = 2017, height = j, bottom = baseline, color=colors[color_index]) # baseline += j # color_index += 1 plt.xticks(np.arange(len(plot_totals[plot].index)), plot_totals[plot].index, rotation = 270); # Creating legend patches = list() for i in reversed(range(len(plots[plot].platform.unique()))): patch = mpatches.Patch(color = colors[i], label = plot_totals[plot].columns[i]) patches.append(patch) plt.legend(handles=patches, fontsize=12, framealpha=1) # Some additioanl plot prep plt.rcParams['axes.axisbelow'] = True plt.grid(color='gray', linestyle='dashed') plt.ylabel('Amount of Sales') plt.xlabel('Year') plt.title('Number of Games by Year and Platform');
['PC' 'Wii' 'PS3' 'XOne' 'X360' 'WiiU' '3DS' 'PS4' 'PSV']
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
We can see that from about 2013 to 2016, it has risen, and began dropping at a faster rate. Our prediction of 2017 at this level of modelling visibly follows that trend. One thing to note is that this indicates, from what we know of the gaming industry, that it would likely be time for a new generation of consoles to come out, restarting the wave of consumer sales. Next, lets look at the distribution of these games by platform.
filtered_clean_games_data.boxplot(column='total_sales', by='platform', figsize=(16,8)) plt.ylabel('Total Sales') plt.xlabel('Platform') plt.title('Distribution of Sales by Platform') plt.show()
_____no_output_____
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
It appears that there are a significant number of outliers accross the board. This shows, that a large portion of each platforms market performance is largely based on triple A titles, but there are still a significant number of games that are indie games, less advertised games, or games that just generally did not get the same amount of traction among consumers. It looks like overall, the PS3 and Xbox 360 generally had better selling games, as the distribution is spread out to higher sales. The PSV was not know for its popularity, so this explains is low distribution. As for the PC, it is known for having a lot of indie games, as it is more accessible for game makers to distribute games. This accessibility also explains the large number of outliers as well. Now lets take a look at how critic and user reviews affect sales of a single platform. For this example, we will look at the Wii.
wii_data = filtered_clean_games_data[clean_games_data['platform'] == 'Wii'] fig, axes = plt.subplots(ncols=3, figsize=(16,8)) axes[0].scatter(wii_data.critic_score, wii_data.total_sales, color='orange', alpha=.5) axes[1].scatter(wii_data.user_score, wii_data.total_sales, color='blue', alpha=.5) axes[2].scatter(wii_data.user_score*10, wii_data.total_sales, color='blue', alpha=.3) axes[2].scatter(wii_data.critic_score, wii_data.total_sales, color='orange', alpha=.3) pop_a = mpatches.Patch(color='blue', label='user') pop_b = mpatches.Patch(color='orange', label='critic') axes[2].legend(handles=[pop_a,pop_b], loc='upper left') axes[0].set(title='Critic Score vs. Total Sales', xlabel='Critic Score', ylabel='Total Sales') axes[1].set(title='User Score vs. Total Sales', xlabel='User Score') axes[2].set(title='Overlapped Critic and User Score vs. Total Sales', xlabel='Critic Score and Equivalent Scale of User Score') plt.show()
_____no_output_____
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
Although critic and user reviews look similar, we can see that barring a few outliers, users tend to be more willing to rate games higher than critics. It also seems that the shape of the critics scoring appears to be more rectangular than the users score. This implies that the amount of sales has less of an impact on the scoring than users do. Users may be more inclined to be influenced by word of mouth and riding the wave of a game's popularity. A lot of games are multiplatform, so lets see if there is much of a difference between platforms.
wii_data = wii_data[['name', 'na_sales', 'eu_sales', 'jp_sales', 'other_sales', 'total_sales']] x360_data = filtered_clean_games_data[clean_games_data['platform'] == 'X360'] x360_data = x360_data[['name', 'na_sales', 'eu_sales', 'jp_sales', 'other_sales', 'total_sales']] wii_x360_cross = pd.merge(wii_data, x360_data, on="name", suffixes=("Wii", "X360")) fig = plt.figure() ax1 = fig.add_subplot(111) ax1.hist(wii_x360_cross['total_salesWii'], bins=30, alpha= 0.5, label='Wii Sales') ax1.hist(wii_x360_cross['total_salesX360'], bins=30, alpha= 0.5, label='XBox 360 Sales') plt.legend(loc='upper right'); plt.ylabel('Frequency') plt.xlabel('Total Sales') plt.title('Distribution of Sales by Platform') plt.show()
_____no_output_____
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
It does appear that there may be a slight bias towards Xbox 360. This does make some sense, as the consoles are very different. The Xbox is primarily a button input, while the wii does have button inputs, but the console was largely popular to it's motion control. Because the Xbox does not have motion controls, motion control games would not be multi platform, and so it does not have that advantage of what area of expertise gave it its popularity. Now lets take a look into the same level of detail for the game genres.
top_plats = filtered_clean_games_data.groupby('genre')['total_sales'].sum() filtered_clean_games_data.boxplot(column='total_sales', by='genre', figsize=(16,8)) plt.ylabel('Total Sales') plt.xlabel('Genre') plt.title('Distribution of Sales by Genre') plt.show()
_____no_output_____
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
The largest genres are Action, Fighting, Platform, Shooter, and Sports. This makes sense as they make up a large part of the triple A title games, including well established franchises such as Zelda, Mortal Combat, Mario, Call of Duty, and Fifa. The lowest are Adventure, Puzzle, and Strategy, games that are typical as indie titles and represent lower volume and pricing.
top_plats.plot('bar', figsize=(16,8)) plt.ylabel('Total Sales') plt.xlabel('Platform') plt.title('Total Sales by Genre') plt.show()
_____no_output_____
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
Similarly to the distribution, the largest amount of sales are in Action and Sports, while the lower sales are in puzzle and strategy. The differences between these total amounts and the distribution is largely in the volume of games in the market place. Step 3 Conclusion After viewing the preliminary data, we saw that the earlier years are not very representative, so all lower outlying years were filtered out. We then filtered for the popular and relevant consoles, based on being more recently selling platforms. We saw a large boost of games sold around 2009 through 2011, primarily for the success of the Wii, PS3, and Xbox 360 consoles - at those years, they were relatively new. After that burst, the success fell, and then next gen consoles came out, but the wave was not as successful and are already falling well below by 2016. Because of this trend, and without the knowledge of new consoles, the trend naturally falls, and we expect sales around 32.4 million USD.As expected with the waves of success, consoles such as the PS3 and Xbox 360 had higher distributions of sales, while handhelds and PC games sold typically lower. We also found that users and critics scored games very similar, but users may be slightly more biased by the traction in sales and popularity by word of mouth. Consoles were also relatively similar, but small discrepancies can be found between multiplatform games, and this may be due to the strengths and weaknesses of the consoles in relation to the game types. We also looked at the distribution of sales based on genre and noticed that more total sales by genre correlated with higher distribution of better selling games. They also are typically the genres of triple A games, so these distributions make sense. Step 4. Create a user profile for each region
categories = ['platform', 'genre', 'rating'] fig, axes = plt.subplots(nrows=3, ncols=3, figsize=(16,16)) color_vals = ['orange', 'cyan', 'lime'] colors = {i: color_vals[i] for i in range(len(color_vals))} vals = ['na_sales', 'eu_sales', 'jp_sales'] locations = {i: vals[i] for i in range(len(vals))} for i in range(len(categories)): top_order = filtered_clean_games_data.groupby(categories[i])['na_sales', 'eu_sales', 'jp_sales'].sum() na_top_order = top_order.sort_values(by='na_sales', ascending=False) eu_top_order = top_order.sort_values(by='eu_sales', ascending=False) jp_top_order = top_order.sort_values(by='jp_sales', ascending=False) top = [na_top_order, eu_top_order, jp_top_order] for j in range(len(top)): # Plotting in a loop for k in range(5): platforms = top[j].index[k] platforms_data = top[j].loc[platforms] baseline = 0 color_index = 0 for m in platforms_data: axes[i,j].bar(x = k, height = m, bottom = baseline, color=colors[color_index]) baseline += m color_index += 1 title_label = 'Top 5 ' + top_order.index.name.title() + 's for ' + top_order.columns[j][:2].upper() axes[i,j].set_title(label=title_label) axes[i,j].xaxis.set(ticks=np.arange(5), ticklabels=top[j].index) axes[i,0].set_ylabel(ylabel='Sales') #Creating legend patches = list() for i in range(3): #patch = mpatches.Patch(color = colors[i], label = cancellation_cause[cancellation_code_per_carrier_pct.columns[i]]) patch = mpatches.Patch(color = colors[i], label = top_order.columns[i]) patches.append(patch) fig.legend(handles=patches, fontsize=12, framealpha=1, loc='upper left') fig.show()
_____no_output_____
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
Step 4 Conclusion For the top 5 platforms by location, the Xbox 360, Wii, and PS3 were very popular in North America, but nothing outstanding byond those three. The EU is similar, but PC was preferenced over the Wii, keeping course with tactile, button based platforms. In Japan, PS3 was the largest platform, but handhelds were highly prefered over what was popular for both the EU and NA groups. This deiscrepancy may be largely due to [Japan's significantly higher use of public transport](https://en.wikipedia.org/wiki/List_of_countries_by_rail_usage). This means they may be more inclined to use that time on a train to use a handheld console for convenience. For the top 5 genres by location, Action and Sports were very the most popular in North America, and the EU. In Japan, Role-Playing was a close second, which was at the 5th spot in NA and was not even present in the EU's top 5. This may be due to the popularity with sports in the respective countries. For example, some of the two most successful sports games are the Madden NFL american football series and FIFA Soccer (european football) series. Both of these may correlate with the popularity of the sports in the United States and Europe respectively.For the top 5 ratings by location, E and T were every groups first and second, respectively. In Japan and the EU, M took precedent over E10+, but the opposite was true in NA. The differences between M and E10+ however, are quite small in all regions, and may be considered negligible. Step 5. Test the following hypotheses:
# the level of significance alpha = .05
_____no_output_____
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
Average user ratings of the Xbox One and PC platforms are the same. A dual sample t-test will be used to determine if the _surf_ plan and _ultimate_ plan generate different monthly revenues per person. We will create the following hypotheses: The null hypothesis, $H_0$: The average score from users of the Xbox One games and PC games are equal. The alternative hypothesis, $H_A$: The average score from users of the Xbox One games and PC games are not equal.
set1 = filtered_clean_games_data[filtered_clean_games_data.platform == 'XOne']['user_score'] set2 = filtered_clean_games_data[filtered_clean_games_data.platform == 'PC']['user_score'] results = st.ttest_ind( filtered_clean_games_data[filtered_clean_games_data.platform == 'XOne']['user_score'], filtered_clean_games_data[filtered_clean_games_data.platform == 'PC']['user_score'], equal_var=False) print('p-value: ', results.pvalue) if results.pvalue > alpha: print('We cannot reject the null hypothesis') else: print('We can reject the null hypothesis') fig, axes = plt.subplots(ncols=2, figsize=(16,4)) xbox = filtered_clean_games_data[filtered_clean_games_data.platform == 'XOne'] pc = filtered_clean_games_data[filtered_clean_games_data.platform == 'PC'] axes[0].hist(xbox.user_score, bins=len(xbox.user_score.unique()), color='orange') axes[1].hist(pc.user_score, bins=len(pc.user_score.unique()), color='blue') axes[0].set(title='Distribution of Xbox User Scores', xlabel='User Score', ylabel='Frequency') axes[1].set(title='Distribution of PC User Scores', xlabel='User Score', ylabel='Frequency') plt.show() pop_a = mpatches.Patch(color='blue', label='PC') pop_b = mpatches.Patch(color='orange', label='Xbox') fig, axes = plt.subplots(ncols=1, figsize=(16,8)) axes.hist([xbox.user_score, pc.user_score], bins=len(xbox.user_score.unique()), color=['orange', 'blue']) axes.set(title='Distribution of Xbox and PC User Scores', xlabel='User Score', ylabel='Frequency') axes.legend(handles=[pop_a,pop_b], loc='upper left') plt.show()
_____no_output_____
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
To confirm, it does appear that the distribution of the PC user score is more left skewed than the Xbox user score. the PC scores peak around 6.7, and tail more evenly in both directions, while there seems to be a larger dostribution of high ranked PC games. The variances of the two subsamples are not equal, and therefore the parameter, `equal_var` must be set to False to compare sets with different variances and/or sets of different sizes. The null hypothesis of a dual sample t-test is that the two groups are similar, and the alternative hypothesis is that they are dissimilar. In this case, the null hypothesis is that the average score from users of the Xbox One games are similar to the average scores of the PC games. In the results of the t-test, the p-value was below our level of significance and we could reject the null variable and say that the average scores differ between the two groups. From the correlation of user score to sales, as well as the distribution of Xbox One games' higher total sales vs the PC games' lower total sales, this makes sense that they would not be equal. Average user ratings for the Action and Sports genres are different. The null hypothesis, $H_0$: The average score from users of the Action games and Sports games are equal. The alternative hypothesis, $H_A$: The average score from users of the Action games and Sports games are not equal.
results = st.ttest_ind( filtered_clean_games_data[filtered_clean_games_data.genre == 'Action']['user_score'], filtered_clean_games_data[filtered_clean_games_data.genre == 'Sports']['user_score'], equal_var=False) print('p-value: ', results.pvalue) if results.pvalue > alpha: print('We cannot reject the null hypothesis') else: print('We can reject the null hypothesis')
p-value: 5.279399270185236e-10 We can reject the null hypothesis
MIT
video-game-exploration.ipynb
Chandler-Stewart/video-game-exploration
📝 Exercise M6.03The aim of this exercise is to:* verifying if a random forest or a gradient-boosting decision tree overfit if the number of estimators is not properly chosen;* use the early-stopping strategy to avoid adding unnecessary trees, to get the best generalization performances.We will use the California housing dataset to conduct our experiments.
from sklearn.datasets import fetch_california_housing from sklearn.model_selection import train_test_split data, target = fetch_california_housing(return_X_y=True, as_frame=True) target *= 100 # rescale the target in k$ data_train, data_test, target_train, target_test = train_test_split( data, target, random_state=0, test_size=0.5)
_____no_output_____
CC-BY-4.0
notebooks/ensemble_ex_03.ipynb
Imarcos/scikit-learn-mooc
NoteIf you want a deeper overview regarding this dataset, you can refer to theAppendix - Datasets description section at the end of this MOOC. Create a gradient boosting decision tree with `max_depth=5` and`learning_rate=0.5`.
# Write your code here.
_____no_output_____
CC-BY-4.0
notebooks/ensemble_ex_03.ipynb
Imarcos/scikit-learn-mooc
Also create a random forest with fully grown trees by setting `max_depth=None`.
# Write your code here.
_____no_output_____
CC-BY-4.0
notebooks/ensemble_ex_03.ipynb
Imarcos/scikit-learn-mooc
For both the gradient-boosting and random forest models, create a validationcurve using the training set to assess the impact of the number of trees onthe performance of each model. Evaluate the list of parameters `param_range =[1, 2, 5, 10, 20, 50, 100]` and use the mean absolute error.
# Write your code here.
_____no_output_____
CC-BY-4.0
notebooks/ensemble_ex_03.ipynb
Imarcos/scikit-learn-mooc
Both gradient boosting and random forest models will always improve whenincreasing the number of trees in the ensemble. However, it will reach aplateau where adding new trees will just make fitting and scoring slower.To avoid adding new unnecessary tree, unlike random-forest gradient-boostingoffers an early-stopping option. Internally, the algorithm will use anout-of-sample set to compute the generalization performance of the model ateach addition of a tree. Thus, if the generalization performance is notimproving for several iterations, it will stop adding trees.Now, create a gradient-boosting model with `n_estimators=1_000`. This numberof trees will be too large. Change the parameter `n_iter_no_change` suchthat the gradient boosting fitting will stop after adding 5 trees that do notimprove the overall generalization performance.
# Write your code here.
_____no_output_____
CC-BY-4.0
notebooks/ensemble_ex_03.ipynb
Imarcos/scikit-learn-mooc
Estimate the generalization performance of this model again usingthe `sklearn.metrics.mean_absolute_error` metric but this time usingthe test set that we held out at the beginning of the notebook.Compare the resulting value with the values observed in the validationcurve.
# Write your code here.
_____no_output_____
CC-BY-4.0
notebooks/ensemble_ex_03.ipynb
Imarcos/scikit-learn-mooc
Convolutional LayerIn this notebook, we visualize four filtered outputs (a.k.a. activation maps) of a convolutional layer. In this example, *we* are defining four filters that are applied to an input image by initializing the **weights** of a convolutional layer, but a trained CNN will learn the values of these weights. Import the image
import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'data/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show()
_____no_output_____
MIT
convolutional-neural-networks/conv-visualization/conv_visualization.ipynb
marielen/deep-learning-v2-pytorch
Define and visualize the filters
import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[1, 1, 1, -1], [1, 1, -1, 1], [1, -1, 1, 1], [-1, 1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) # visualize all four filters fig = plt.figure(figsize=(10, 5)) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) width, height = filters[i].shape for x in range(width): for y in range(height): ax.annotate(str(filters[i][x][y]), xy=(y,x), horizontalalignment='center', verticalalignment='center', color='white' if filters[i][x][y]<0 else 'black')
_____no_output_____
MIT
convolutional-neural-networks/conv-visualization/conv_visualization.ipynb
marielen/deep-learning-v2-pytorch
Define a convolutional layer The various layers that make up any neural network are documented, [here](http://pytorch.org/docs/stable/nn.html). For a convolutional neural network, we'll start by defining a:* Convolutional layerInitialize a single convolutional layer so that it contains all your created filters. Note that you are not training this network; you are initializing the weights in a convolutional layer so that you can visualize what happens after a forward pass through this network! `__init__` and `forward`To define a neural network in PyTorch, you define the layers of a model in the function `__init__` and define the forward behavior of a network that applyies those initialized layers to an input (`x`) in the function `forward`. In PyTorch we convert all inputs into the Tensor datatype, which is similar to a list data type in Python. Below, I define the structure of a class called `Net` that has a convolutional layer that can contain four 3x3 grayscale filters.
import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a single convolutional layer with four filters class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # returns both layers return conv_x, activated_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model)
Net( (conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False) )
MIT
convolutional-neural-networks/conv-visualization/conv_visualization.ipynb
marielen/deep-learning-v2-pytorch
Visualize the output of each filterFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through.
# helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1))
_____no_output_____
MIT
convolutional-neural-networks/conv-visualization/conv_visualization.ipynb
marielen/deep-learning-v2-pytorch
Let's look at the output of a convolutional layer, before and after a ReLu activation function is applied.
# plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get the convolutional layer (pre and post activation) conv_layer, activated_layer = model(gray_img_tensor) # visualize the output of a conv layer viz_layer(conv_layer)
_____no_output_____
MIT
convolutional-neural-networks/conv-visualization/conv_visualization.ipynb
marielen/deep-learning-v2-pytorch
ReLu activationIn this model, we've used an activation function that scales the output of the convolutional layer. We've chose a ReLu function to do this, and this function simply turns all negative pixel values in 0's (black). See the equation pictured below for input pixel values, `x`.
# after a ReLu is applied # visualize the output of an activated conv layer viz_layer(activated_layer)
_____no_output_____
MIT
convolutional-neural-networks/conv-visualization/conv_visualization.ipynb
marielen/deep-learning-v2-pytorch
Ricos pelo Acaso * Link para o vídeo: https://youtu.be/NHCUUZOvk7k---* Base de Dados: http://dados.cvm.gov.br/ Coletando os dados da CVM
import pandas as pd pd.set_option("display.max_colwidth", 150) #pd.options.display.float_format = '{:.2f}'.format
_____no_output_____
MIT
16_CVM_Os_Melhores_e_os_Piores_Fundos_de_Investimento_do_mes_Python_para_Investimentos.ipynb
alcebytes/python_para_investimentos
>Funções que buscam dados no site da CVM e retornam um DataFrame Pandas:
def busca_informes_cvm(ano, mes): url = 'http://dados.cvm.gov.br/dados/FI/DOC/INF_DIARIO/DADOS/inf_diario_fi_{:02d}{:02d}.csv'.format(ano,mes) return pd.read_csv(url, sep=';') def busca_cadastro_cvm(ano, mes, dia): url = 'http://dados.cvm.gov.br/dados/FI/CAD/DADOS/inf_cadastral_fi_{}{:02d}{:02d}.csv'.format(ano, mes, dia) return pd.read_csv(url, sep=';', encoding='ISO-8859-1')
_____no_output_____
MIT
16_CVM_Os_Melhores_e_os_Piores_Fundos_de_Investimento_do_mes_Python_para_Investimentos.ipynb
alcebytes/python_para_investimentos
>Buscando dados no site da CVM
informes_diarios = busca_informes_cvm(2020,4) informes_diarios cadastro_cvm = busca_cadastro_cvm(2020,5,1) cadastro_cvm
_____no_output_____
MIT
16_CVM_Os_Melhores_e_os_Piores_Fundos_de_Investimento_do_mes_Python_para_Investimentos.ipynb
alcebytes/python_para_investimentos
Manipulando os dados da CVM >Definindo filtros para os Fundos de Investimento
minimo_cotistas = 100
_____no_output_____
MIT
16_CVM_Os_Melhores_e_os_Piores_Fundos_de_Investimento_do_mes_Python_para_Investimentos.ipynb
alcebytes/python_para_investimentos
>Manipulando os dados e aplicando filtros
fundos = informes_diarios[informes_diarios['NR_COTST'] >= minimo_cotistas].pivot(index='DT_COMPTC', columns='CNPJ_FUNDO', values=['VL_TOTAL', 'VL_QUOTA', 'VL_PATRIM_LIQ', 'CAPTC_DIA', 'RESG_DIA']) fundos
_____no_output_____
MIT
16_CVM_Os_Melhores_e_os_Piores_Fundos_de_Investimento_do_mes_Python_para_Investimentos.ipynb
alcebytes/python_para_investimentos
>Normalizando os dados de cotas para efeitos comparativos
cotas_normalizadas = fundos['VL_QUOTA'] / fundos['VL_QUOTA'].iloc[0] cotas_normalizadas
_____no_output_____
MIT
16_CVM_Os_Melhores_e_os_Piores_Fundos_de_Investimento_do_mes_Python_para_Investimentos.ipynb
alcebytes/python_para_investimentos
Fundos de Investimento com os melhores desempenhos em Abril de 2020
melhores = pd.DataFrame() melhores['retorno(%)'] = (cotas_normalizadas.iloc[-1].sort_values(ascending=False)[:5] - 1) * 100 melhores
_____no_output_____
MIT
16_CVM_Os_Melhores_e_os_Piores_Fundos_de_Investimento_do_mes_Python_para_Investimentos.ipynb
alcebytes/python_para_investimentos
>Buscando dados dos Fundos de Investimento pelo CNPJ
for cnpj in melhores.index: fundo = cadastro_cvm[cadastro_cvm['CNPJ_FUNDO'] == cnpj] melhores.at[cnpj, 'Fundo de Investimento'] = fundo['DENOM_SOCIAL'].values[0] melhores.at[cnpj, 'Classe'] = fundo['CLASSE'].values[0] melhores.at[cnpj, 'PL'] = fundo['VL_PATRIM_LIQ'].values[0] melhores
_____no_output_____
MIT
16_CVM_Os_Melhores_e_os_Piores_Fundos_de_Investimento_do_mes_Python_para_Investimentos.ipynb
alcebytes/python_para_investimentos
Fundos de Investimento com os piores desempenhos em Abril de 2020
piores = pd.DataFrame() piores['retorno(%)'] = (cotas_normalizadas.iloc[-1].sort_values(ascending=True)[:5] - 1) * 100 piores
_____no_output_____
MIT
16_CVM_Os_Melhores_e_os_Piores_Fundos_de_Investimento_do_mes_Python_para_Investimentos.ipynb
alcebytes/python_para_investimentos
>Buscando dados dos Fundos de Investimento pelo CNPJ
for cnpj in piores.index: fundo = cadastro_cvm[cadastro_cvm['CNPJ_FUNDO'] == cnpj] piores.at[cnpj, 'Fundo de Investimento'] = fundo['DENOM_SOCIAL'].values[0] piores.at[cnpj, 'Classe'] = fundo['CLASSE'].values[0] piores.at[cnpj, 'PL'] = fundo['VL_PATRIM_LIQ'].values[0] piores
_____no_output_____
MIT
16_CVM_Os_Melhores_e_os_Piores_Fundos_de_Investimento_do_mes_Python_para_Investimentos.ipynb
alcebytes/python_para_investimentos
HSV Color Space, Balloons Import resources and display image
import numpy as np import matplotlib.pyplot as plt import cv2 %matplotlib inline # Read in the image image = cv2.imread('images/water_balloons.jpg') # Make a copy of the image image_copy = np.copy(image) # Change color to RGB (from BGR) image = cv2.cvtColor(image_copy, cv2.COLOR_BGR2RGB) plt.imshow(image)
_____no_output_____
MIT
1_1_Image_Representation/5_1. HSV Color Space, Balloons.ipynb
Abdulrahman-Adel/CVND-Exercises
Plot color channels
# RGB channels r = image[:,:,0] g = image[:,:,1] b = image[:,:,2] f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20,10)) ax1.set_title('Red') ax1.imshow(r, cmap='gray') ax2.set_title('Green') ax2.imshow(g, cmap='gray') ax3.set_title('Blue') ax3.imshow(b, cmap='gray') # Convert from RGB to HSV hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) # HSV channels h = hsv[:,:,0] s = hsv[:,:,1] v = hsv[:,:,2] f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20,10)) ax1.set_title('Hue') ax1.imshow(h, cmap='gray') ax2.set_title('Saturation') ax2.imshow(s, cmap='gray') ax3.set_title('Value') ax3.imshow(v, cmap='gray')
_____no_output_____
MIT
1_1_Image_Representation/5_1. HSV Color Space, Balloons.ipynb
Abdulrahman-Adel/CVND-Exercises
Define pink and hue selection thresholds
# Define our color selection criteria in HSV values lower_hue = np.array([160,0,0]) upper_hue = np.array([180,255,255]) # Define our color selection criteria in RGB values lower_pink = np.array([180,0,100]) upper_pink = np.array([255,255,230])
_____no_output_____
MIT
1_1_Image_Representation/5_1. HSV Color Space, Balloons.ipynb
Abdulrahman-Adel/CVND-Exercises
Mask the image
# Define the masked area in RGB space mask_rgb = cv2.inRange(image, lower_pink, upper_pink) # mask the image masked_image = np.copy(image) masked_image[mask_rgb==0] = [0,0,0] # Vizualize the mask plt.imshow(masked_image) # Now try HSV! # Define the masked area in HSV space mask_hsv = cv2.inRange(hsv, lower_hue, upper_hue) # mask the image masked_image = np.copy(image) masked_image[mask_hsv==0] = [0,0,0] # Vizualize the mask plt.imshow(masked_image)
_____no_output_____
MIT
1_1_Image_Representation/5_1. HSV Color Space, Balloons.ipynb
Abdulrahman-Adel/CVND-Exercises
Python Final Project - Team Python Charmers
# Loading Packages import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.preprocessing import StandardScaler from sklearn.pipeline import make_pipeline # Loading Data From Source. def load_data(): url = r'https://raw.githubusercontent.com/Python-Charmer/Final-Project-Team-Python-Charmer/master/Phase1/Data/BreastCancerWisconsin.csv' df = pd.read_csv(url) names = ['Scn','A2','A3','A4','A5','A6','A7', 'A8','A9','A10','Class'] df.columns = names return df # Understanding Missing Values def clean_missing(df): df['A7'] = df['A7'].replace('?',np.NaN) df['A7'] = pd.to_numeric(df['A7']) print("Below are how many missing values for each column\n") print(df.isnull().sum()) print("\nCleaning missing values with column means\n") df = df.fillna(round(df.mean(skipna = True),2)) print(df.isnull().sum()) return df # Calculating Summary Metrics def sum_metrics(df): print("\n Below are the summary metrics of the data \n" + str(df.describe())) print ("\n\nThere are " + str(df.shape[0]) + " rows and " + str(df.shape[1]) + " Columns in this data frame") print("\nThere are " + str(len(df['Scn'].unique())) + " unique scn values in the dataset.\n") print("Below are the duplicate rows in the dataset.\n") print(str(df.loc[df.duplicated(), :]) + "\n") # Plotting graphs def plot_graphs(df): print("\nBelow are the histograms of A2:A10 \n") df.iloc[:,1:10].hist(bins = 8, color="blue", grid="False",alpha = .5, figsize=(12,6)) plt.tight_layout(rect=(0,0,1.2,1.2)) plt.show() df['Class'].value_counts().plot.bar().set_title("Class Variable: 2 = Benign 4 = Malignant") df.plot.scatter(x='A3', y='A4').set_title("Scatter of A3 & A4 90% corr") # We are getting centers for K = 4 clusters def get_mids(X): clss = KMeans(n_clusters = 4) clss.fit(X) cent = clss.cluster_centers_ print("\n Below are the centers of K = 4 clusters \n") print(pd.DataFrame(cent ,columns = X.columns)) # We are plotting intertia plot to find optimal K def find_optimal_K(X): print("\n Below is the intertia chart \n") inertia = [] k = [] for i in range(1,15): clss = KMeans(n_clusters = i) clss.fit(X) iner = clss.inertia_ k.append(i) inertia.append(iner) res = pd.concat([pd.DataFrame(k), pd.DataFrame(inertia)],axis = 1) res.columns = ['K','Inertia'] ax = res.plot("K",marker='o', linestyle='dashed', title = "Optimal K = 2" ) ax.set_xlabel("Number of Clusters") ax.set_ylabel("Inertia") # Plotting SD plot to understand the data variance def sd_plot(X): dt = pd.DataFrame(X.std()).sort_values(by = 0, ascending = False) dt.reset_index() fig, ay = plt.subplots() x_val = dt.index y_val = dt[0].values ay.bar(x = x_val, height = y_val) ay.set_xlabel("Features") ay.set_ylabel("Standard Deviation") ay.set_title("Standard Deviation Plot") # Plotting Box plot to understand the data variance def var_plot(df): # Box plot showing variation of the columns A2:A10 data = [] for i in range(1, 10): data.append(df.iloc[:, i]) # Multiple box plots on one Axes fig, ax = plt.subplots() plt.title("Boxplot showing Variation of Features") plt.xlabel("Columns A2 thru A10") plt.ylabel("Values") ax.boxplot(data, 0,showbox=True,showmeans=True) top = 12 bottom = -2 ax.set_ylim(bottom, top) ax.set_xticklabels(df.iloc[:,1:-1].columns, rotation=45, fontsize=8) plt.show() #Getting centers of optimal K = 2 def get_centers(X): print("\n Below are the centers of K = 2 clusters \n \n") mdl = make_pipeline(StandardScaler(), KMeans(n_clusters = 2, n_init=20)) mdl.fit(X) centers = pd.DataFrame(mdl.named_steps['kmeans'].cluster_centers_) centers.columns = X.columns print(centers) # Cross tabulating the cluster labels with "Class" def lables(i,df): print("\nBelow are the predicted labels with k = " + str(i) + "\n") if i == 4: mdl = KMeans(n_clusters = i) else: mdl = make_pipeline(StandardScaler(), KMeans(n_clusters = i, n_init=20)) labels = mdl.fit_predict(df.iloc[:,1:-1]) ctf = pd.DataFrame({'labels': labels, 'Class': df["Class"]}) print(pd.crosstab(ctf['labels'], ctf['Class'])) # Main Function Phase 1 df = load_data() df = clean_missing(df) sum_metrics(df) plot_graphs(df) print("The columns that need standardization are: A7,A3,& A9 because they have the highest amount of variance compared to other factors.") #Main Functions Phase 2 X = df.drop(['Scn','Class'], axis = 1) y = df['Class'] get_mids(X) lables(4,df) find_optimal_K(X) sd_plot(X) var_plot(df) print('\n Based on the Box and SD plot above we can see features A7,A9 has the most variations.\n') get_centers(X) lables(2,df) #Main Phase 3 mdl = make_pipeline(StandardScaler(), KMeans(n_clusters = 2, n_init=20, max_iter = 500)) labels = mdl.fit_predict(X) df['Predicted'] = labels for x in range(df.shape[0]): if df.iloc[x,11] == 0: df.iloc[x,11] = 2 else: df.iloc[x,11] = 4 print("\nBelow are the first 15 rows of the dataframe \n") print(df.head(15)) print("\nBelow are the observtions where the predicted did not match the class \n") print(df[df['Class'] != df['Predicted']]) def error_rate(predicted,actual): tab = pd.crosstab(actual,predicted) error2 = tab.iloc[0,1] total2 = tab.iloc[0,0] + tab.iloc[1,0] error4 = tab.iloc[1,0] total4 = tab.iloc[0,1] + tab.iloc[1,1] B = str(round(error2/total2,4)*100) + "%" M = str(round(error4/total4,4)*100) + "%" tot_error = str(round((error2 + error4)/(total2 + total4),4)*100) + "%" print("\nThe error rate for beningn cells is " + str(B) + "\n") print("The error rate for malignent cells is " +str(M) + "\n") print("The total error rate is " +str(tot_error) + "\n") error_rate(df['Predicted'], df['Class'])
_____no_output_____
MIT
Phase 3/Code/FinalProject.ipynb
Python-Charmer/Final-Project-Team-Python-Charmer
Putting it All TogetherThis notebook is a case study in working with python and several modules. It's a real problem I had to solve with real data. There are *many* ways to attack a problem such as this; this is simply one way. The point is to illustrate how you can get existing modules to do the heavy-lifting for you and that visualization is a powerful diagnostic tool. Try not to get caught up in the details of the model; it's quite complex and the point is not to understand all the equations, but the *procedure* of exploring data and fitting it to a model (read the citation if you're really interested all the gory details).This notebook requires the following modules:* `numpy`: dealing with arrays of numbers and mathematics* `scipy`: collection of scientific algorithms* `matplotlib`: de-facto plotting module* `pandas`: module for organizing arrays of number into tables* `bokeh`: another module for plotting, with emphasis on interactive visualizationThe problem I needed to solve: predict the background sky brightness caused by the moon at a given location in the sky on a given date. This is to help plan observations at the telescope. As with all problems of this type, we need to do several things:* Download/import/munge training data* Model the training data* Extract model parameters* Graph the result(s) to see how well we do, maybe modify the model* Use final model and parameters to make future predictions 1) The DataIn this case, the data to model is roughly 10 years of photometry from the Carnegie Supernova Project (CSP). Each and every measurement of the flux from a standard star has an associated estimate of the sky background (which must be subtracted from the raw counts of the star). These data were taken over many different times of the month and a many different sky altitudes, so are ideal for this problem.Let's start by getting the data. For convenience, this has been included in the `data` folder and so we can load it up immediately into a `pandas` dataframe.
import pandas as pd data = pd.read_csv('data/skyfit.dat')
_____no_output_____
MIT
MoreNotebooks/Skyfit.ipynb
mahdiqezlou/FlyingCircus
We can take a quick look at what's in this `DataFrame` by printing out the first few rows.
print(data[0:10])
_____no_output_____
MIT
MoreNotebooks/Skyfit.ipynb
mahdiqezlou/FlyingCircus
The column `jd` is the [Julian Day](https://en.wikipedia.org/wiki/Julian_day), a common numerical representation of the date, `RA` and `Decl` are the sky coordiates of the field, and `magsky` is the sky brighness. Let's have a look at the distribution of sky brightnesses to make sure they "make sense". The units should be magnitudes per square-arc-second and be on order of 22 or so, but should be smaller for bright time (full moon). Since we're just doing a quick-look, we can use `pandas`' built-in histogram plotter.
%matplotlib inline data.hist('magsky', bins=50)
_____no_output_____
MIT
MoreNotebooks/Skyfit.ipynb
mahdiqezlou/FlyingCircus
As you can see, there is peak near 22 mag/square-arc-sec, as expected, but a broader peak at brighter backgrounds. We expect this is due to moonlight. Something to think about: why would this be bi-modal?We expect that the fuller the moon, the brighter it will be and the closer the observation is to the moon on the sky, the higher the background. So whatever model we use is going to require knowledge of the moon's position and phase. There are mathematical formulae for calculating these, but we'll use the handy `astropy.coordinates` module to do all the work for us. First, let's compute the lunar phase for each date in our table. To do this, we need the position of the moon and the sun at these times.
from astropy.coordinates import get_moon, get_sun from astropy.time import Time times = Time(data['jd'], format='jd') # makes an array of astropy.Time objects moon = get_moon(times) # makes an array of moon positions sun = get_sun(times) # makes an array of sun positions
_____no_output_____
MIT
MoreNotebooks/Skyfit.ipynb
mahdiqezlou/FlyingCircus
Currently, `astropy.coordinates` does not have a lunar phase function, so we'll just use the angular separation between the sun and moon as a proxy. If the angular separation is 0 degrees, that's new moon, whereas an angular separation of 180 degrees is full moon. Other phases lie in between. `moon` and `sun` are arrays of `SkyCoord` objects that have many useful tools for computing sky posisitions. Here we'll use the `separation()` function, which computes the angular separation on the sky between two objects:
seps = moon.separation(sun) # angular separation from moon to sun data['phase'] = pd.Series(seps, index=data.index) # Add this new parameter to the data frame
_____no_output_____
MIT
MoreNotebooks/Skyfit.ipynb
mahdiqezlou/FlyingCircus
Now that we have the phase information, let's see if our earlier hypothesis about the moon being a source of background light is valid. We'll plot one versus the other, again using the `pandas` built-in plotting functionality.
data.plot.scatter('phase','magsky')
_____no_output_____
MIT
MoreNotebooks/Skyfit.ipynb
mahdiqezlou/FlyingCircus
Great! There's a definite trend there, but also some interesting patterns. Remember these are magnitudes per square arc-second, so brighter sky is down, not up. We can also split up the data based on the phase and plot the resulting histograms together. You can run this next snippet of code with different `phasecut` values to see how they separate out. We use `matplotlib`'s `gca` function to "get the current axis", allowing us to over-plot two histograms.
import matplotlib.pyplot as plt phasecut = 90. res = data[data.phase>phasecut].hist('magsky', bins=50, label='> {:.2f} degrees'.format(phasecut), alpha=0.7) ax = plt.gca() res = data[data.phase<phasecut].hist('magsky', ax=ax, bins=50, label='< {:.2f} degrees'.format(phasecut), alpha=0.7) plt.legend(loc='upper left')
_____no_output_____
MIT
MoreNotebooks/Skyfit.ipynb
mahdiqezlou/FlyingCircus