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 na... | 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. Assignin... | 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... | _____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... | # A dependency of the preprocessing for BERT inputs
!pip install -q -U tensorflow-text | [K |████████████████████████████████| 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 repos... | _____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 Da... | 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(data... | 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 th... | 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.cac... | 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. "Pandemon... | 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... | #@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... | 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 i... | 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_... | 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... | 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_... | 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)
S... | 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 ... | 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_... | _____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 informati... | 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 (... | 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,
... | _____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 ... | 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... | 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... | 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 ea... | _____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%[=============... | 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(... | 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(pro... | _____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... | _____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 ... | 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_s... | 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/u... | 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,... | _____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'])[... | _____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 i... | _____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 ... | 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 (Presum... | 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 ... | 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']):
... | <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_sal... | 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
... | <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_sal... | 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 t... | 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:
... | _____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_sal... | 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 = li... | <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_sal... | 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_sal... | 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 dat... | 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 /... | 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('Tot... | _____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... | ['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 ... | 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.piv... | ['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 dr... | 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 = (... | _____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... | ['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 c... | 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... | 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_dat... | _____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 ... | 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, o... | _____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 ... | 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 ... | 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 tha... | 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... | _____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 handh... | # 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 gam... | 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_g... | _____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 theref... | 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... | 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 ho... | 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_stat... | _____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 op... | # 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 weight... | 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(b... | _____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` ... | _____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 t... | 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 weig... | 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.imsh... | _____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')
a... | _____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,... | _____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(... | _____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, uppe... | _____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... | _____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... | 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... | %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 sk... | 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 array... | 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` va... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.