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 |
|---|---|---|---|---|---|
52 lines of code is impresive! | UNET() | _____no_output_____ | MIT | notebooks/Original_U-Net_PyTorch.ipynb | jimmiemunyi/fastai-experiments |
Testing the U-Net with the original sizes of the input in the paper: | x = torch.randn(1, 1, 572, 572)
m = UNET(in_channels=1, out_channels=2)
m(x).shape | _____no_output_____ | MIT | notebooks/Original_U-Net_PyTorch.ipynb | jimmiemunyi/fastai-experiments |
Does our U-Net also work for odd numbers? | x = torch.randn(1, 1, 571, 571)
m = UNET(in_channels=1, out_channels=2)
m(x).shape | _____no_output_____ | MIT | notebooks/Original_U-Net_PyTorch.ipynb | jimmiemunyi/fastai-experiments |
Normalizing Flows Tutorial Part 12D invertible MLP on a toy dataset.Copyright 2018 Eric Jang | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions
tfb = tfp.bijectors
tf.set_random_seed(0)
sess = tf.InteractiveSession()
batch_size=512
DTYPE=tf.float32
NP_DTYPE=np.float32 | _____no_output_____ | MIT | nf_part1_intro.ipynb | pawelc/normalizing-flows-tutorial |
Target Density | DATASET = 1
if DATASET == 0:
mean = [0.4, 1]
A = np.array([[2, .3], [-1., 4]])
cov = A.T.dot(A)
print(mean)
print(cov)
X = np.random.multivariate_normal(mean, cov, 2000)
plt.scatter(X[:, 0], X[:, 1], s=10, color='red')
dataset = tf.data.Dataset.from_tensor_slices(X.astype(NP_DTYPE))
... | _____no_output_____ | MIT | nf_part1_intro.ipynb | pawelc/normalizing-flows-tutorial |
Construct Flow | base_dist = tfd.MultivariateNormalDiag(loc=tf.zeros([2], DTYPE))
# quite easy to interpret - multiplying by alpha causes a contraction in volume.
class LeakyReLU(tfb.Bijector):
def __init__(self, alpha=0.5, validate_args=False, name="leaky_relu"):
super(LeakyReLU, self).__init__(
forward_min_eve... | _____no_output_____ | MIT | nf_part1_intro.ipynb | pawelc/normalizing-flows-tutorial |
Visualization (before training) | # visualization
x = base_dist.sample(512)
samples = [x]
names = [base_dist.name]
for bijector in reversed(dist.bijector.bijectors):
x = bijector.forward(x)
samples.append(x)
names.append(bijector.name)
sess.run(tf.global_variables_initializer())
results = sess.run(samples)
f, arr = plt.subplots(1, len(resul... | _____no_output_____ | MIT | nf_part1_intro.ipynb | pawelc/normalizing-flows-tutorial |
Optimize Flow | loss = -tf.reduce_mean(dist.log_prob(x_samples))
train_op = tf.train.AdamOptimizer(1e-3).minimize(loss)
sess.run(tf.global_variables_initializer())
NUM_STEPS = int(1e5)
global_step = []
np_losses = []
for i in range(NUM_STEPS):
_, np_loss = sess.run([train_op, loss])
if i % 1000 == 0:
global_step.append... | _____no_output_____ | MIT | nf_part1_intro.ipynb | pawelc/normalizing-flows-tutorial |
UpSampling2D **[convolutional.UpSampling2D.0] size 2x2 upsampling on 3x3x3 input, dim_ordering='tf'** | data_in_shape = (3, 3, 3)
L = UpSampling2D(size=(2, 2), dim_ordering='tf')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(input=layer_0, output=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(250)
data_in = 2 * np.random.random(data_in_shape) - 1
print('')
print... |
in shape: (3, 3, 3)
in: [-0.570441, -0.454673, -0.285321, 0.237249, 0.282682, 0.428035, 0.160547, -0.332203, 0.546391, 0.272735, 0.010827, -0.763164, -0.442696, 0.381948, -0.676994, 0.753553, -0.031788, 0.915329, -0.738844, 0.269075, 0.434091, 0.991585, -0.944288, 0.258834, 0.162138, 0.565201, -0.492094]
out shape: (6... | MIT | notebooks/layers/convolutional/UpSampling2D.ipynb | jefffriesen/keras-js |
**[convolutional.UpSampling2D.0] size 2x2 upsampling on 3x3x3 input, dim_ordering='th'** | data_in_shape = (3, 3, 3)
L = UpSampling2D(size=(2, 2), dim_ordering='th')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(input=layer_0, output=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(250)
data_in = 2 * np.random.random(data_in_shape) - 1
print('')
print... |
in shape: (3, 3, 3)
in: [-0.570441, -0.454673, -0.285321, 0.237249, 0.282682, 0.428035, 0.160547, -0.332203, 0.546391, 0.272735, 0.010827, -0.763164, -0.442696, 0.381948, -0.676994, 0.753553, -0.031788, 0.915329, -0.738844, 0.269075, 0.434091, 0.991585, -0.944288, 0.258834, 0.162138, 0.565201, -0.492094]
out shape: (3... | MIT | notebooks/layers/convolutional/UpSampling2D.ipynb | jefffriesen/keras-js |
**[convolutional.UpSampling2D.2] size 3x2 upsampling on 4x2x2 input, dim_ordering='tf'** | data_in_shape = (4, 2, 2)
L = UpSampling2D(size=(3, 2), dim_ordering='tf')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(input=layer_0, output=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(251)
data_in = 2 * np.random.random(data_in_shape) - 1
print('')
print... |
in shape: (4, 2, 2)
in: [0.275222, -0.793967, -0.468107, -0.841484, -0.295362, 0.78175, 0.068787, -0.261747, -0.625733, -0.042907, 0.861141, 0.85267, 0.956439, 0.717838, -0.99869, -0.963008]
out shape: (12, 4, 2)
out: [0.275222, -0.793967, 0.275222, -0.793967, -0.468107, -0.841484, -0.468107, -0.841484, 0.275222, -0.7... | MIT | notebooks/layers/convolutional/UpSampling2D.ipynb | jefffriesen/keras-js |
**[convolutional.UpSampling2D.3] size 1x3 upsampling on 4x3x2 input, dim_ordering='th'** | data_in_shape = (4, 3, 2)
L = UpSampling2D(size=(1, 3), dim_ordering='th')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(input=layer_0, output=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(252)
data_in = 2 * np.random.random(data_in_shape) - 1
print('')
print... |
in shape: (4, 3, 2)
in: [-0.989173, -0.133618, -0.505338, 0.023259, 0.503982, -0.303769, -0.436321, 0.793911, 0.416102, 0.806405, -0.098342, -0.738022, -0.982676, 0.805073, 0.741244, -0.941634, -0.253526, -0.136544, -0.295772, 0.207565, -0.517246, -0.686963, -0.176235, -0.354111]
out shape: (4, 3, 6)
out: [-0.989173, ... | MIT | notebooks/layers/convolutional/UpSampling2D.ipynb | jefffriesen/keras-js |
Train summary on Train mosaic made from Trainset of 50k CIFAR | fg = [fg1,fg2,fg3]
bg = list(set([0,1,2,3,4,5,6,7,8,9])-set(fg))
from tabulate import tabulate
correct = 0
total = 0
count = 0
flag = 1
focus_true_pred_true =0
focus_false_pred_true =0
focus_true_pred_false =0
focus_false_pred_false =0
argmax_more_than_half = 0
argmax_less_than_half =0
with torch.no_grad():
for dat... | _____no_output_____ | MIT | 1_mosaic_data_attention_experiments/11_mosaic_from_CIFAR_involving_direction/using_least_variance_direction/extra/gamma 0.02/fg_123_run1.ipynb | lnpandey/DL_explore_synth_data |
Test summary on Test mosaic made from Trainset of 50k CIFAR | fg = [fg1,fg2,fg3]
bg = list(set([0,1,2,3,4,5,6,7,8,9])-set(fg))
correct = 0
total = 0
count = 0
flag = 1
focus_true_pred_true =0
focus_false_pred_true =0
focus_true_pred_false =0
focus_false_pred_false =0
argmax_more_than_half = 0
argmax_less_than_half =0
with torch.no_grad():
for data in test_loader:
inputs, ... | _____no_output_____ | MIT | 1_mosaic_data_attention_experiments/11_mosaic_from_CIFAR_involving_direction/using_least_variance_direction/extra/gamma 0.02/fg_123_run1.ipynb | lnpandey/DL_explore_synth_data |
Test summary on Test mosaic made from Testset of 10k CIFAR | fg = [fg1,fg2,fg3]
bg = list(set([0,1,2,3,4,5,6,7,8,9])-set(fg))
correct = 0
total = 0
count = 0
flag = 1
focus_true_pred_true =0
focus_false_pred_true =0
focus_true_pred_false =0
focus_false_pred_false =0
argmax_more_than_half = 0
argmax_less_than_half =0
with torch.no_grad():
for data in unseen_test_loader:
i... | _____no_output_____ | MIT | 1_mosaic_data_attention_experiments/11_mosaic_from_CIFAR_involving_direction/using_least_variance_direction/extra/gamma 0.02/fg_123_run1.ipynb | lnpandey/DL_explore_synth_data |
Example to use the custom Container for mono reconstruction | from lstchain.io.containers import DL1ParametersContainer
from lstchain.reco.utils import guess_type
from ctapipe.utils import get_dataset_path
from ctapipe.io import HDF5TableWriter, HDF5TableReader
from ctapipe.calib import CameraCalibrator
from ctapipe.image import tailcuts_clean
from ctapipe.io import event_source... | _____no_output_____ | BSD-3-Clause | notebooks/example_container.ipynb | Mike7477/cta-lstchain |
Options | infile = get_dataset_path('gamma_test_large.simtel.gz')
dl1_parameters_filename = 'dl1.h5'
allowed_tels = {1} # select LST1 only
max_events = 300 # limit the number of events to analyse in files - None if no limit
cal = CameraCalibrator(r1_product='HESSIOR1Calibrator', extractor_product='NeighbourPeakIntegrator')... | _____no_output_____ | BSD-3-Clause | notebooks/example_container.ipynb | Mike7477/cta-lstchain |
R0 to DL1 | dl1_container = DL1ParametersContainer()
with HDF5TableWriter(filename=dl1_parameters_filename, group_name='events', overwrite=True) as writer:
source = event_source(infile)
source.allowed_tels = allowed_tels
source.max_events = max_events
for i, event in enumerate(source):
if i%100==0:
... | 152 -rw-r--r-- 1 thomasvuillaume staff 75K Nov 19 14:31 dl1.h5
| BSD-3-Clause | notebooks/example_container.ipynb | Mike7477/cta-lstchain |
Transparent data reading into the container | from ctapipe.io import HDF5TableReader
with HDF5TableReader(dl1_parameters_filename, mode='r+') as table:
for c in table.read('/events/LSTCam', DL1ParametersContainer()):
print(c.disp) | WARNING:ctapipe.io.hdf5tableio.HDF5TableReader:Table '/events/LSTCam' is missing column 'mc_type' that is in container DL1ParametersContainer. It will be skipped.
WARNING:ctapipe.io.hdf5tableio.HDF5TableReader:Table '/events/LSTCam' is missing column 'impact' that is in container DL1ParametersContainer. It will be skip... | BSD-3-Clause | notebooks/example_container.ipynb | Mike7477/cta-lstchain |
The hdf5 file is also very easy to read with pandas | import pandas as pd
pd.read_hdf(dl1_parameters_filename, key='events/LSTCam') | _____no_output_____ | BSD-3-Clause | notebooks/example_container.ipynb | Mike7477/cta-lstchain |
Transfer LearningIn this notebook, you'll learn how to use pre-trained networks to solved challenging problems in computer vision. Specifically, you'll use networks trained on [ImageNet](http://www.image-net.org/) [available from torchvision](http://pytorch.org/docs/0.3.0/torchvision/models.html). ImageNet is a massiv... | %matplotlib inline
%config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models | _____no_output_____ | MIT | Part 8 - Transfer Learning.ipynb | Hamez/DL_PyTorch |
Most of the pretrained models require the input to be 224x224 images. Also, we'll need to match the normalization used when the models were trained. Each color channel was normalized separately, the means are `[0.485, 0.456, 0.406]` and the standard deviations are `[0.229, 0.224, 0.225]`. | data_dir = 'Cat_Dog_data'
# TODO: Define transforms for the training data and testing data
train_transforms = transforms.Compose([transforms.RandomRotation(30),
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
... | _____no_output_____ | MIT | Part 8 - Transfer Learning.ipynb | Hamez/DL_PyTorch |
We can load in a model such as [DenseNet](http://pytorch.org/docs/0.3.0/torchvision/models.htmlid5). Let's print out the model architecture so we can see what's going on. | model = models.densenet121(pretrained=True)
model | C:\Users\jdmcd\Anaconda3\lib\site-packages\torchvision\models\densenet.py:212: UserWarning: nn.init.kaiming_normal is now deprecated in favor of nn.init.kaiming_normal_.
nn.init.kaiming_normal(m.weight.data)
| MIT | Part 8 - Transfer Learning.ipynb | Hamez/DL_PyTorch |
This model is built out of two main parts, the features and the classifier. The features part is a stack of convolutional layers and overall works as a feature detector that can be fed into a classifier. The classifier part is a single fully-connected layer `(classifier): Linear(in_features=1024, out_features=1000)`. T... | # Freeze parameters so we don't backprop through them
for param in model.parameters():
param.requires_grad = False
from collections import OrderedDict
classifier = nn.Sequential(OrderedDict([
('fc1', nn.Linear(1024, 500)),
('relu', nn.ReLU()),
... | _____no_output_____ | MIT | Part 8 - Transfer Learning.ipynb | Hamez/DL_PyTorch |
With our model built, we need to train the classifier. However, now we're using a **really deep** neural network. If you try to train this on a CPU like normal, it will take a long, long time. Instead, we're going to use the GPU to do the calculations. The linear algebra computations are done in parallel on the GPU lea... | import time
#for device in ['cpu', 'cuda']:
device = 'cpu'
criterion = nn.NLLLoss()
# Only train the classifier parameters, feature parameters are frozen
optimizer = optim.Adam(model.classifier.parameters(), lr=0.001)
model.to(device)
for ii, (inputs, labels) in enumerate(trainloader):
# Move input and label ten... | Device = cpu; Time per batch: 6.865 seconds
| MIT | Part 8 - Transfer Learning.ipynb | Hamez/DL_PyTorch |
You can write device agnostic code which will automatically use CUDA if it's enabled like so:```python at beginning of the scriptdevice = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")... then whenever you get a new Tensor or Module this won't copy if they are already on the desired deviceinput = data.t... | # TODO: Train a model with a pre-trained network
device = 'cpu'
criterion = nn.NLLLoss()
# Only train the classifier parameters, feature parameters are frozen
optimizer = optim.Adam(model.classifier.parameters(), lr=0.001)
model.classifier.fc1.weight
model.to(device)
for ii, (inputs, labels) in enumerate(trainloader):... | _____no_output_____ | MIT | Part 8 - Transfer Learning.ipynb | Hamez/DL_PyTorch |
Note* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. | # Dependencies and Setup
import pandas as pd
# File to Load (Remember to Change These)
school_data_to_load = "Resources/schools_complete.csv"
student_data_to_load = "Resources/students_complete.csv"
# Read School and Student Data File and store into Pandas DataFrames
school_data = pd.read_csv(school_data_to_load)
stu... | _____no_output_____ | Apache-2.0 | PyCitySchools/.ipynb_checkpoints/PyCitySchools_starter-checkpoint.ipynb | seidyp/pandas-analysis-education |
Visualizations 2 A notebook of exploratory data analysis for energy forecasting **Run Imports** | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime as dt | _____no_output_____ | CC0-1.0 | notebooks/viz_2.ipynb | jf-silverman/energy_forecasting |
**Seaborn plot formatting** | sns.set_context('paper', font_scale= 1.5) # size of text/graph elements
sns.despine() # takes away axes on charts with no grid
sns.set_style('darkgrid') # background of chart color and if grid is present | _____no_output_____ | CC0-1.0 | notebooks/viz_2.ipynb | jf-silverman/energy_forecasting |
**Reading in the data** | nrg = pd.read_csv('../data/all_erco_energy_cst.csv') | _____no_output_____ | CC0-1.0 | notebooks/viz_2.ipynb | jf-silverman/energy_forecasting |
**Converting the date column to datetime type for indexing** | nrg['datetime'] = pd.to_datetime(nrg['datetime'].str[:-3],format='%Y%m%dT%H') | _____no_output_____ | CC0-1.0 | notebooks/viz_2.ipynb | jf-silverman/energy_forecasting |
**Setting the date column as index** | nrg.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 57865 entries, 0 to 57864
Data columns (total 13 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 datetime 57865 non-null datetime64[ns]
1 demand 57660 non-null float6... | CC0-1.0 | notebooks/viz_2.ipynb | jf-silverman/energy_forecasting |
**Dropping records that in the data for forcasting that don't have energy type info** | nrg.dropna(inplace=True) # removes 26,000 records from before July 2018 | _____no_output_____ | CC0-1.0 | notebooks/viz_2.ipynb | jf-silverman/energy_forecasting |
**Making an hour column for plotting (0 to 23 hrs)** | nrg['hour_num'] = pd.to_numeric(nrg['datetime'].dt.strftime('%H'),downcast='integer')
# making a 'day_night' column, where 6am to 6pm is the day value; rest is night.
def calc_col_vals(row):
if row['hour_num']<6 or row['hour_num']>17:
return 'Night'
elif row['hour_num']>5 and row['hour_num']<18:
... | _____no_output_____ | CC0-1.0 | notebooks/viz_2.ipynb | jf-silverman/energy_forecasting |
Table of Contents- [Part 2: Q-Learning for FrozenLake-v0, OpenAI Gym environment](frozen-lake) - [Q-Learning Approach](q-learn) - [OpenAI Gym Stochastic FrozenLake approach](stochastic-field) - [Personal Deterministic FrozenLake approach](deterministic-field) - [Play Against Environment](pve) ... | '''
If following import fails, just install gym from anaconda console, using:
pip install gym
'''
import gym
import numpy as np
import time, pickle, os
# Global constants
epsilon = 0.9
total_epoches = 10000
max_steps = 1000
lr_rate = 0.81
gamma = 0.96 | _____no_output_____ | MIT | Coursework/Part 2 Q-Learning for FrozenLake-v0.ipynb | vieliashevskyi/lembs-datascience-school |
Q-Learning Approach Before moving to DNN implementation, I've decided to use Q-learning algorithm.The goal of Q-learning is to learn a policy, which tells an agent what action to take under what circumstances. OpenAI Gym Stochastic FrozenLake Approach In this context, **stochastic** means that upon action selection... | # Load OpenAI gym environment
env_stochastic = gym.make('FrozenLake-v0')
# Define our Q-Learn matrix
Q_stochastic = np.zeros((env_stochastic.observation_space.n, env_stochastic.action_space.n))
file_Q_stochastic = "frozenLake_stochastic_qTable.pkl"
# Preview board
env_stochastic.render()
# Defines all possible action... | _____no_output_____ | MIT | Coursework/Part 2 Q-Learning for FrozenLake-v0.ipynb | vieliashevskyi/lembs-datascience-school |
Below function does not depend on any additional learning, so it can be freely changed. | # This function will select Move (Action) based on State and all previous Experience saved in model.
def choose_QModel_action(state, verbose, Q):
action = np.argmax(Q[state, :])
if verbose == True:
print (action)
return action
def initPlayByQModel(episodes_count, environment, file_QTable, showOutpu... | *** Starting Episode: 0
Success: Agent passed the Lake!
*** Starting Episode: 1
Success: Agent passed the Lake!
*** Starting Episode: 2
Agent died in vain!
*** Starting Episode: 3
Agent died in vain!
*** Starting Episode: 4
Success: Agent passed the Lake!
*** Starting Episode: 5
Agent died in vain!
*** Starting E... | MIT | Coursework/Part 2 Q-Learning for FrozenLake-v0.ipynb | vieliashevskyi/lembs-datascience-school |
Personal Deterministic FrozenLake Approach So, as you can see stochastic environment ain't that good for Q-Learning (Let's run few more times here, just to show how bad it is). Let's make environment **deterministic**!For any references about arguments or environment we can look directly in OpenAI FrozenLake implemen... | # First, we need to register our new environment we going to work with
from gym.envs.registration import register
register(id='Deterministic-FrozenLake4x4-v0',
entry_point='gym.envs.toy_text.frozen_lake:FrozenLakeEnv',
kwargs={'map_name': '4x4', 'is_slippery': False}
)
# Create new environment instance to work... | *** Starting Episode: 0
Success: Agent passed the Lake!
*** Starting Episode: 1
Success: Agent passed the Lake!
*** Starting Episode: 2
Success: Agent passed the Lake!
*** Starting Episode: 3
Success: Agent passed the Lake!
*** Starting Episode: 4
Success: Agent passed the Lake!
*** Starting Episode: 5
Success: A... | MIT | Coursework/Part 2 Q-Learning for FrozenLake-v0.ipynb | vieliashevskyi/lembs-datascience-school |
Wow. Environment definitely takes huge place in results.Let's check differences in learned Q-Matrices: | print("Stochastic:\n\n", Q_stochastic, "\n\n\nDeterministic:\n\n", Q_deterministic) | Stochastic:
[[0.63155759 0.7260818 0.63098495 0.64096586]
[0.08923413 0.59320009 0.4857933 0.5864178 ]
[0.58253307 0.54801955 0.74002867 0.5670273 ]
[0.09847175 0.43629738 0.52282304 0.5225726 ]
[0.69112814 0.72705092 0.76905186 0.12600166]
[0. 0. 0. 0. ]
[0.59500203 0.00506861 ... | MIT | Coursework/Part 2 Q-Learning for FrozenLake-v0.ipynb | vieliashevskyi/lembs-datascience-school |
Play against environment Let's adapt environment to be human agent friendly | def initPlayVsEnv(environment, showOutput=True):
state = environment.reset()
while True:
if showOutput == True:
environment.render()
action = input('Your action? 0 -> Left, 1 -> Down, 2 -> Right, 3 -> Up')
action = int(action)
if action >= 4:
print ... |
[41mS[0mFFF
FHFH
FFFH
HFFG
| MIT | Coursework/Part 2 Q-Learning for FrozenLake-v0.ipynb | vieliashevskyi/lembs-datascience-school |
Pensamento ComputacionalAluna: Bianca MunizExercício : calculando a densidade demográfica | import csv
arquivo = open("brasil.csv")
leitor = csv.DictReader(arquivo)
for registro in leitor:
registro["densidade"] = int(registro["habitantes"])/float(registro["area"])
print(f"O município {registro['municipio']}/{registro['estado']} possui densidade demográfica de {registro['densidade']} hab/km².") | [1;30;43mA saída de streaming foi truncada nas últimas 5000 linhas.[0m
O município Sapeaçu/BA possui densidade demográfica de 141.4981656855217 hab/km².
O município Sátiro Dias/BA possui densidade demográfica de 18.77530815306173 hab/km².
O município Saubara/BA possui densidade demográfica de 68.50764525993884 hab/km... | MIT | pensamento_computacional/PC_exercicio3_aula3.ipynb | biamuniz/MJDA_Insper |
!pip install yfinance
import pandas as pd
import numpy as np
import math
import pandas_datareader as pdd
from sklearn.preprocessing import MinMaxScaler
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM
import matplotlib.pyplot as plt
from pandas_... | _____no_output_____ | MIT | stock_LSTM.ipynb | purohitn/SNAS-Series | |
Heart Disease UCIFor this blog project, I decided to use the the heart disease UCI dataset taken from https://www.kaggle.com/ronitf/heart-disease-uci which is already a reprocessed data from UCI machine learning repository. This dataset have been taken back from 1988 and consisted of patients with admitted heart disea... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_graphviz
from sklearn.metrics import roc_curve, auc
from sklearn.metrics import classificati... | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
Features: 1. **age**: Patient age in years when admitted2. **sex**: Patient's gender (female=0, male=1) 3. **cp**: Type of chest pain that patient felt (typical angina, atypical angina, non-angina, or asymptomatic angina)4. **trestbps**: Patient's resting blood pressure (mm Hg)5. **chol**: Patient's cholesterol level (... | df.columns = ['age', 'gender', 'chest_pain', 'blood_pressure', 'cholesterol', 'blood_sugar', 'restecg', 'max_heart_rate',
'exang', 'st_depression', 'st_slope', 'major_vessels', 'thallium', 'result']
df.head()
df.describe()
df.isnull().sum()
df.info()
df['gender'].value_counts()
df['chest_pain'].value_counts()
df... | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
There are some impossible values for the major vessels and thallium test results. For the major vessels column, it have value of 4 where it should be Nan in its original datasets. While for the thallium column, it also have a value of 0 which should have been nan in its original dataset. | indexNames = df[ (df['major_vessels'] == 4) | (df['thallium'] == 0) ].index
df= df.drop(indexNames)
df['thallium'].value_counts()
indexNames
df.info() | <class 'pandas.core.frame.DataFrame'>
Int64Index: 296 entries, 0 to 302
Data columns (total 14 columns):
age 296 non-null int64
gender 296 non-null object
chest_pain 296 non-null object
blood_pressure 296 non-null int64
cholesterol 296 non-null int64
blood_sugar 296 non-nu... | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
After dealing with wrong values, we will search for the outlier for the part with continuous value | sb.boxplot(data = df, y = 'blood_pressure')
sb.boxplot(data = df, y = 'cholesterol')
sb.boxplot(data = df, y = 'max_heart_rate')
sb.boxplot(data = df, y = 'st_depression') | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
We can see that there is some outliers especially for blood_pressure, cholesterol and st_depression which we decide to get rid of by knowing the threshold first | q1 = df['blood_pressure'].quantile(0.25)
q3 = df['blood_pressure'].quantile(0.75)
iqr = q3-q1
fence_low = q1-1.5*iqr
fence_high = q3+1.5*iqr
fence_high, fence_low
q1 = df['cholesterol'].quantile(0.25)
q3 = df['cholesterol'].quantile(0.75)
iqr = q3-q1
fence_low = q1-1.5*iqr
fence_high = q3+1.5*iqr
fence_high, fence_... | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
After knowing the outlier threshold, we will drop all of the value that exceed the high fence | indexNames2 = df[ (df['blood_pressure'] >= 170) | (df['cholesterol'] >= 371.625) | (df['st_depression'] >= 4.125) ].index
df2= df.drop(indexNames2)
df2.info()
sb.boxplot(data = df2, y = 'blood_pressure')
sb.boxplot(data = df2, y = 'cholesterol')
sb.boxplot(data = df2, y = 'st_depression') | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
In this section, we will analyze the required features and the methods in answering the questions 1. Does age and gender of the patients have certain trends in determining whether the patient have heart disease or not? The needed features for this question are age, gender and result columns. | age_distribution = df2.groupby(["age", "result"]).size().reset_index()
plt.figure(figsize=(20,10))
my_palette = {0:'#3498db', 1:'#e74c3c'}
ax = sb.barplot(x='age', y=0, hue='result', palette=my_palette, data=age_distribution)
plt.title('Result Distribution for each of age classes', fontsize=22, y=1.015)
plt.xlabel('Age... | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
We can see that as the patient get older, the possibility of having heart disease is higher especially at the age of 60s | plt.figure(figsize=(16,8))
ax = sb.boxplot(x='gender', y='age', hue='result', linewidth=11, data= df2)
plt.title('Heart Test results distribution based on Age and Gender', fontsize=22, y=1.015)
plt.xlabel('Gender', fontsize=16, labelpad=16)
plt.ylabel('Age', fontsize=16, labelpad=16)
plt.xticks(size = 14)
plt.yticks(si... | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
As we can see that the male have wider distribution (30s-80s) among ages for the one that has heart disease compared to the female age distribution (50s-65s) 2. What is the relationship between blood pressure and heart rate in having heart disease? The features in this question will be blood pressure and max heart rat... | df_d = df2[df2['result'] == 0]
df_nd = df2[df2['result'] == 1]
plt.figure(figsize=(16,8))
plt.hist(df_d['max_heart_rate'], alpha=0.5, label='disease')
plt.hist(df_nd['max_heart_rate'], alpha=0.5, label='healthy')
plt.title('Max Heart Rate Distribution based on heart disease', fontsize=22, y=1.015)
plt.xlabel('Max Heart... | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
We can see that the one with healthy hearts have stronger maximum heart rate. | plt.figure(figsize=(16,8))
plt.hist(df_d['blood_pressure'], alpha=0.5, label='disease')
plt.hist(df_nd['blood_pressure'], alpha=0.5, label='healthy')
plt.title('Blood Pressure Distribution based on heart disease', fontsize=22, y=1.015)
plt.xlabel('Blood Pressure', fontsize=16, labelpad=16)
plt.ylabel('Count', fontsize=... | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
there are no special trait that can be distinguished between the healthy and sick patients in their blood pressure section; however, we can see that healthy patient have lower blood pressure compared to patient with heart disease. | plt.figure(figsize=(20,10))
ax = sb.scatterplot(x='blood_pressure', y='max_heart_rate', hue='result', data=df2)
plt.title('The Relationship between Blood Pressure and Max Heart Rate', fontsize=22, y=1.015)
plt.xlabel('Blood Pressure', fontsize=16, labelpad=16)
plt.ylabel('Max Heart Rate', fontsize=16, labelpad=16)
plt.... | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
As the graph indicated, the lower half of the max heart rate is filled with sick patient which have lower max heart rate. we can also see that the blood pressure of healthy patient is also lower compared to sick patient which is indicated by the left side of this graph. 3. Do we know the symptom of the heart attacks s... | chest_distribution = df2.groupby(["chest_pain", "result"]).size().reset_index()
plt.figure(figsize=(20,10))
my_palette = {0:'#3498db', 1:'#e74c3c'}
ax = sb.barplot(x='chest_pain', y=0, hue='result', palette=my_palette, data=chest_distribution)
plt.title('Result Distribution according to Chest Pain types', fontsize=22, ... | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
Angina is a type of chest pain which is usually caused by the reduction of amount of blood that is pumped to heart, thus, making the heart work harder. There are four categories of angina: 1. [asymptomatic](https://www.health.harvard.edu/heart-health/angina-and-its-silent-cousin): The type of angina that has no symptom... | exang_distribution = df2.groupby(["exang", "result"]).size().reset_index()
plt.figure(figsize=(20,10))
my_palette = {0:'#3498db', 1:'#e74c3c'}
ax = sb.barplot(x='exang', y=0, hue='result', palette=my_palette, data=exang_distribution)
plt.title('Result Distribution according to Exercise Induced Angina', fontsize=22, y=1... | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
Exercise induced angina means that when the patient exercise, they have the possibility in triggering angina which of course is in line with the logic that those with heart disease have higher possibility in triggering agina when exercise. | plt.figure(figsize=(16,8))
plt.hist(df_d['cholesterol'], alpha=0.5, label='disease')
plt.hist(df_nd['cholesterol'], alpha=0.5, label='healthy')
plt.title('Cholesterol Distribution based on heart disease', fontsize=22, y=1.015)
plt.xlabel('Cholesterol', fontsize=16, labelpad=16)
plt.ylabel('Count', fontsize=16, labelpad... | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
We can see that there are no significant differences between the one with heart disease and the one with healthy heart as they are both have even distributions | sugar_distribution = df2.groupby(["blood_sugar", "result"]).size().reset_index()
plt.figure(figsize=(20,10))
my_palette = {0:'#3498db', 1:'#e74c3c'}
ax = sb.barplot(x='blood_sugar', y=0, hue='result', palette=my_palette, data=sugar_distribution)
plt.title('Result Distribution according to Blood Sugar', fontsize=22, y=1... | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
Blood sugar plot also indicated that there is no special trend, the same as cholesterol distribution plot 4. What is the trend of the cardiological test such as ECG, Fluoroscopy and Thallium? After knowing the symptoms, we will try to analyze the trend in the cardiological tests results | ecg_distribution = df2.groupby(["restecg", "result"]).size().reset_index()
plt.figure(figsize=(20,10))
my_palette = {0:'#3498db', 1:'#e74c3c'}
ax = sb.barplot(x='restecg', y=0, hue='result', palette=my_palette, data=ecg_distribution)
plt.title('Result Distribution according to Electrocardiogram results', fontsize=22, y... | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
So according to this graph of ecg results, the main findings from this are a lot of the patient with heart disease found out that they are suffering from left venticular hypertrophy (enlargement and thickening of the heart pumping chamber wall). | plt.figure(figsize=(16,8))
plt.hist(df_d['st_depression'], alpha=0.5, label='disease')
plt.hist(df_nd['st_depression'], alpha=0.5, label='healthy')
plt.title('ST Depression Distribution based on heart disease', fontsize=22, y=1.015)
plt.xlabel('ST Depression', fontsize=16, labelpad=16)
plt.ylabel('Count', fontsize=16, ... | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
[ST depression](https://litfl.com/st-segment-ecg-library/) refers to the fluctuation of ST segments in the electrocardiogram where the higher the ST depressions (mV) there is higher chance that the supply of blood to hearts is lesser, thus, higher chance of heart failing. This explanation is in line with the graph wher... | st_distribution = df2.groupby(["st_slope", "result"]).size().reset_index()
plt.figure(figsize=(20,10))
my_palette = {0:'#3498db', 1:'#e74c3c'}
ax = sb.barplot(x='st_slope', y=0, hue='result', palette=my_palette, data=st_distribution)
plt.title('Result Distribution according to Slope of peak exercise ST segment', fontsi... | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
In this graph, we measure the slope of the peak during ST segments. According to this [source](https://litfl.com/st-segment-ecg-library/), the flat or downsloping leads to myocardial ischaemia at certain threshold which is in line with this finding of the graph (upsloping only considered dangerous at certain threshold ... | vessel_distribution = df2.groupby(["major_vessels", "result"]).size().reset_index()
plt.figure(figsize=(20,10))
my_palette = {0:'#3498db', 1:'#e74c3c'}
ax = sb.barplot(x='major_vessels', y=0, hue='result', palette=my_palette, data=vessel_distribution)
plt.title('Result Distribution according to number of major vessels ... | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
[Fluoroscopy](https://www.fda.gov/radiation-emitting-products/medical-x-ray-imaging/fluoroscopy) is a test which used to examine the hearts by using the material itself in order to provide continuous imaging of the examined area. The more vessels are colored by the fluoroscopy, the more troubled major vessels in the he... | thallium_distribution = df2.groupby(["thallium", "result"]).size().reset_index()
plt.figure(figsize=(20,10))
my_palette = {0:'#3498db', 1:'#e74c3c'}
ax = sb.barplot(x='thallium', y=0, hue='result', palette=my_palette, data=thallium_distribution)
plt.title('Result Distribution according to Thallium nuclear test', fontsi... | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
[Thallium nuclear test](https://www.jaocr.org/articles/review-of-spect-myocardial-perfusion-imaging) is the the type of test which patient is injected with thallium radioactive dye and the dye is picked up with the sensor and translated into images. There are three types of result: fixed defect (a type of perfusion def... | df3 = pd.get_dummies(df2, drop_first=True)
df3.head()
# Split the 'features' and 'income' data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(df3.drop('result', 1),
df3['result'],
... | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
5. Evaluation After training our model, we will predict and evaluate the metric in predicting the results | rf_preds = model_a.predict(X_test)
print_metrics(y_test, rf_preds, 'logistic regression')
rf_preds = model_b.predict(X_test)
print_metrics(y_test, rf_preds, 'random forest')
rf_preds = model_c.predict(X_test)
print_metrics(y_test, rf_preds, 'SGD classifier') | Accuracy score for logistic regression : 0.8554216867469879
Precision score logistic regression : 0.8222222222222222
Recall score logistic regression : 0.9024390243902439
F1 score logistic regression : 0.8604651162790697
Accuracy score for random forest : 0.7951807228915663
Precision score random forest : 0.8
Recall... | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
We can see that logistic regresssion is the most suitable in predicting the result since the end result is binary and the random forest as the second most predictive | parameters = {'C':[0.01,0.1,1,10,100,1000], 'solver':['lbfgs', 'liblinear']}
# TODO: Make an fbeta_score scoring object using make_scorer()
scorer = make_scorer(fbeta_score, beta=0.5)
# TODO: Perform grid search on the classifier using 'scorer' as the scoring method using GridSearchCV()
grid_obj = GridSearchCV(clf_a,... | Unoptimized model
------
Accuracy score on testing data: 0.8554
F-score on testing data: 0.8371
Optimized Model
------
Final accuracy score on the testing data: 0.8434
Final F-score on the testing data: 0.8373
| CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
We can see that the unoptimized version is better than optimized in accuracy; however, for the Fscore, the optimized version is better | model = RandomForestClassifier(random_state=56).fit(X_train, y_train)
# TODO: Extract the feature importances using .feature_importances_
importances = model.feature_importances_
# Plot
vs.feature_plot(importances, X_train, y_train) | _____no_output_____ | CNRI-Python | Write a data science blog post.ipynb | audichandra/Heart_Disease_UCI |
Singaporean Food in Indonesia Phrase III : Sumatra, Kalimantan, Sulawesi, and Papua AreaThis is the last phrase of Singaporean food in Indonesia series. In this notebook I'll show you list of Singaporean restaurant in Sumatra (Medan, Padang, Palembang), Kalimantan (Pontianak, Palangkaraya, Balikpapan), Sulawesi (Manad... | from pandasql import sqldf
import pandas as pd
singapore = pd.read_csv("../input/singapore-food/singapore_id.csv", sep = ";") | _____no_output_____ | CC0-1.0 | Singaporean Food in Indonesia/Phrase III (Sumatra, Kalimantan, Sulawesi, Papua).ipynb | miradelimanr/update-code |
OverviewHere is all the list of restaurants sorted by region and city, there are also their unique menu, price, and ratings. Most of prices ranged from 20k until 65k and ratings are quite rave. Medan and Palembang is the most available restaurant. | singapore = sqldf("""SELECT no, restaurant_name, region, city, unique_menu, price,
ltrim(google_rating) as google_rating, ltrim(platform_rating) as platform_rating
FROM singapore
WHERE region LIKE '%Sumatra' OR region LIKE '%Kalimantan' OR region LIKE '%Sulawesi' OR region LIKE '%Papua'""")
singapore.style.hide_inde... | _____no_output_____ | CC0-1.0 | Singaporean Food in Indonesia/Phrase III (Sumatra, Kalimantan, Sulawesi, Papua).ipynb | miradelimanr/update-code |
MenuLike the previous part, I'll divide those menu on three category, which are Rice & Noodle Menu, Poultry Menu, and Toast & Snack Menu.**Rice & Noodle**Here is their Rice and Noodle Menu. For the rice they mostly have hainanse rice and various porridge. For noodle they have noodle (mostly mee goreng) and kway teow. ... | singapore = sqldf("""SELECT restaurant_name, city, rice_menu, noodle, noodle_specific
FROM singapore
WHERE region LIKE '%Sumatra' OR region LIKE '%Kalimantan' OR region LIKE '%Sulawesi' OR region LIKE '%Papua'
GROUP BY city""")
singapore.style.hide_index() | _____no_output_____ | CC0-1.0 | Singaporean Food in Indonesia/Phrase III (Sumatra, Kalimantan, Sulawesi, Papua).ipynb | miradelimanr/update-code |
**Poultry Menu**Based on the list here, the poultry menu are mostly dominated by chicken but only as a topping (signed by 'yes'), but some places have chicken speciality like kungpao and blackpepper. The seafood is quite rare but some places mostly has prawn as majority. Restaurant serving seafood are **New Star Kopiti... | singapore = sqldf("""SELECT restaurant_name, city, chicken, seafood, poultry_other
FROM singapore
WHERE region LIKE '%Sumatra' OR region LIKE '%Kalimantan' OR region LIKE '%Sulawesi' OR region LIKE '%Papua'
GROUP BY city""")
singapore.style.hide_index() | _____no_output_____ | CC0-1.0 | Singaporean Food in Indonesia/Phrase III (Sumatra, Kalimantan, Sulawesi, Papua).ipynb | miradelimanr/update-code |
**Toast & Snack Menu**Similar with the previous part, kaya toast is also popular in this area. Which means kaya toast is the most popular Singaporean toast for entire Indonesia. As for snack the fries are the most popular, but there is a place named **Aman Hainanse Chicken Rice (Medan)** which has unique snack which no... | singapore = sqldf("""SELECT restaurant_name, city, toast
FROM singapore
WHERE (region LIKE '%Sumatra' OR region LIKE '%Kalimantan' OR region LIKE '%Sulawesi' OR region LIKE '%Papua') AND (toast NOT LIKE '%no')""")
singapore.style.hide_index()
singapore = sqldf("""SELECT restaurant_name, city, snack_dish
FROM singapor... | _____no_output_____ | CC0-1.0 | Singaporean Food in Indonesia/Phrase III (Sumatra, Kalimantan, Sulawesi, Papua).ipynb | miradelimanr/update-code |
FacilityAll of them have takeaway options and majority of them has delivery options except some places. None of them has outdoor seat and smoking area, except Bangi Kopitiam, M Kopitiam, New Town Kopitiam, Pace Tan Pu Kopitiam, and Lins Kopitiam for the outdoor, and SING Bakuteh Manado and Rajawali Kopitiam for the sm... | singapore = sqldf("""SELECT restaurant_name, city, takeaway, delivery, outdoor_seat, smoking_area, alcohol_served, wifi
FROM singapore
WHERE region LIKE '%Sumatra' OR region LIKE '%Kalimantan' OR region LIKE '%Sulawesi' OR region LIKE '%Papua'
GROUP BY city""")
singapore.style.hide_index() | _____no_output_____ | CC0-1.0 | Singaporean Food in Indonesia/Phrase III (Sumatra, Kalimantan, Sulawesi, Papua).ipynb | miradelimanr/update-code |
RatingThese ratings are ordered by highest total rating, should they have more than 3.5 then the restaurant is worth to try. All the facility and menu are representated by all both google and platform rating and count, so in the meantime only ratings are counted here. Based on the results, **Liu Kee Hainanse Chicken R... | singapore = sqldf("""SELECT restaurant_name, city,
ltrim(google_rating) as google_rating,
ltrim(platform_rating) as platform_rating,
ltrim((google_rating + platform_rating)/2) as total_rating,
CASE
WHEN (google_rating + platform_rating)/2 >= 3.5 THEN "Recommended"
ELSE "Reconsider"
END AS "Recommendation"
FR... | _____no_output_____ | CC0-1.0 | Singaporean Food in Indonesia/Phrase III (Sumatra, Kalimantan, Sulawesi, Papua).ipynb | miradelimanr/update-code |
Layered Charts A `LayeredChart` allows you to stack multiple individual charts on top of each other as layers. For example, this could be used to create a chart with both lines and points. Imports | import altair as alt
import pandas as pd
import numpy as np
# Uncomment/run this line to enable Altair in the classic notebook (not JupyterLab)
alt.renderers.enable('notebook') | _____no_output_____ | BSD-3-Clause | notebooks/altair_notebooks/07-LayeredCharts.ipynb | WSU-DataScience/ICOTS10_Data_Visualization |
Data | np.random.seed(181)
data = pd.DataFrame({'x': np.arange(10),
'y':np.random.rand(10)})
data.head() | _____no_output_____ | BSD-3-Clause | notebooks/altair_notebooks/07-LayeredCharts.ipynb | WSU-DataScience/ICOTS10_Data_Visualization |
Layered charts Suppose you have defined two charts, and you would like to plot them on the same set of axes.This comes up often when creating a compound chart with points and lines marking the same data.For example: | layer1 = alt.Chart(data).mark_point().encode(
x='x:Q',
y='y:Q'
)
layer2 = alt.Chart(data).mark_line().encode(
x='x:Q',
y='y:Q'
) | _____no_output_____ | BSD-3-Clause | notebooks/altair_notebooks/07-LayeredCharts.ipynb | WSU-DataScience/ICOTS10_Data_Visualization |
The most succinct way to layer two charts is to use the ``+`` operator: | layer1 + layer2 | _____no_output_____ | BSD-3-Clause | notebooks/altair_notebooks/07-LayeredCharts.ipynb | WSU-DataScience/ICOTS10_Data_Visualization |
One problem with this is that you end up specifying the encodings and data multiple times; you can instead build both layers from the same base chart: | base = alt.Chart(data).encode(
x='x:Q',
y='y:Q'
)
base.mark_line() + base.mark_point() | _____no_output_____ | BSD-3-Clause | notebooks/altair_notebooks/07-LayeredCharts.ipynb | WSU-DataScience/ICOTS10_Data_Visualization |
To be a bit more explicit, you can use the ``alt.layer`` function, which produces the same thing: | alt.layer(
base.mark_line(),
base.mark_point()
) | _____no_output_____ | BSD-3-Clause | notebooks/altair_notebooks/07-LayeredCharts.ipynb | WSU-DataScience/ICOTS10_Data_Visualization |
In this notebook, we solve a storage flow relationship, assuming the so-called Muskingum equation. An important law we use (as always) is the continuity equation (i.e. how much flow goes into and out of a given river section, how much does this change the storage?)$$\frac{\partial{A}}{\partial{t}} + \frac{\partial{Q}}{... |
class simple_runoff(object):
"""
A very very simple rainfall runoff response model, computing specific runoff as follows:
q = max(P-I, 0)*rc
where P is precipitation in mm per day, I is interception in mm/day, rc is runoff coefficient [-]
Consequently, it will compute flows at the outlet as follows... | _____no_output_____ | MIT | Muskingum_routing.ipynb | hcwinsemius/hydrology_computing |
Sagemaker Model training workflow with AWS Glue Databrew reciepe and AWS Step Functions.1. [Introduction](Introduction)1. [Setup](Setup)1. [Create Resources](Create-Resources)1. [Build a Machine Learning Workflow](Build-a-Machine-Learning-Workflow)1. [Run the Workflow](Run-the-Workflow)1. [Clean Up](Clean-Up) Introdu... | # verify latest version of stepfunctions.
import sys
# verify step function version
!pip show stepfunctions
# clone the repo and install SDK version > 2.2.0 required for databrew integration
# https://github.com/aws/aws-step-functions-data-science-sdk-python/pull/151
!git clone https://github.com/aws/aws-step-functi... | _____no_output_____ | MIT-0 | notebooks/sagemaker_databrew_ml_workflow_blog.ipynb | aws-samples/aws-databrew-ml-stepfunction-workflow |
Configure Execution Roles | # paste the AmazonSageMaker-StepFunctionsWorkflowExecutionRole ARN (please refer permission setup section)
workflow_execution_role = ''
# SageMaker Execution Role
# You can use sagemaker.get_execution_role() if running inside sagemaker's notebook instance
sagemaker_execution_role = sagemaker.get_execution_role() #Repl... | _____no_output_____ | MIT-0 | notebooks/sagemaker_databrew_ml_workflow_blog.ipynb | aws-samples/aws-databrew-ml-stepfunction-workflow |
Source DataSet LocationCopy the train dataset to S3 location for DataBrew transformation and to train the processed data. | data_source = S3Uploader.upload(local_path='./data/bank-additional.csv',
desired_s3_uri='s3://{}/{}'.format(bucket, project_name),
sagemaker_session=session)
recipe_prefix = 'recipe'
train_prefix = 'train'
val_prefix = 'validation'
recipe_data = 's3://{}/{}... | _____no_output_____ | MIT-0 | notebooks/sagemaker_databrew_ml_workflow_blog.ipynb | aws-samples/aws-databrew-ml-stepfunction-workflow |
Create the AWS Glue Job | glue_script_location = S3Uploader.upload(local_path='./code/glue_etl.py',
desired_s3_uri='s3://{}/{}'.format(bucket, project_name),
sagemaker_session=session)
glue_client = boto3.client('glue')
response = glue_client.create_job(
Name=etl_job_name,
D... | _____no_output_____ | MIT-0 | notebooks/sagemaker_databrew_ml_workflow_blog.ipynb | aws-samples/aws-databrew-ml-stepfunction-workflow |
Create the AWS Lambda Function | import zipfile
zip_name = 'lambda_training_job_status.zip'
lambda_source_code = './code/lambda_training_job_status.py'
zf = zipfile.ZipFile(zip_name, mode='w')
zf.write(lambda_source_code, arcname=lambda_source_code.split('/')[-1])
zf.close()
S3Uploader.upload(local_path=zip_name,
desired_s3_uri='... | _____no_output_____ | MIT-0 | notebooks/sagemaker_databrew_ml_workflow_blog.ipynb | aws-samples/aws-databrew-ml-stepfunction-workflow |
Configure the AWS SageMaker Estimator | container = sagemaker.image_uris.retrieve('xgboost', region, '1.2-1')
xgb = sagemaker.estimator.Estimator(container,
sagemaker_execution_role,
train_instance_count=1,
train_instance_type='ml.m4.xlarge',
... | _____no_output_____ | MIT-0 | notebooks/sagemaker_databrew_ml_workflow_blog.ipynb | aws-samples/aws-databrew-ml-stepfunction-workflow |
Build a Machine Learning Workflow You can use a state machine workflow to create a model training pipeline. The AWS Stepfunctions Data Science SDK provides several AWS SageMaker workflow steps that you can use to construct an ML pipeline. In this tutorial you will create the following steps:* [**ETLStep**](https://aw... | # SageMaker expects unique names for each job, model and endpoint.
# If these names are not unique the execution will fail.
execution_input = ExecutionInput(schema={
'TrainingJobName': str,
'DatabrewJobName': str,
'GlueETLJobName': str,
'ModelName': str,
'EndpointName': str,
'LambdaFunctionName... | _____no_output_____ | MIT-0 | notebooks/sagemaker_databrew_ml_workflow_blog.ipynb | aws-samples/aws-databrew-ml-stepfunction-workflow |
Create a step with AWS GlueDataBrew recipe JobIn the following cell, we create a DataBrew step that runs an AWS Glue DataBrew recipe job. The Glue job extracts the latest data from our source location, removes unnecessary columns, and perform few data cleansing operations. AWS Glue DataBrew is performing this extracti... | recipe_step = steps.GlueDataBrewStartJobRunStep(
'Extract, Transform, Load',
parameters={"Name": execution_input['DatabrewJobName']}
) | _____no_output_____ | MIT-0 | notebooks/sagemaker_databrew_ml_workflow_blog.ipynb | aws-samples/aws-databrew-ml-stepfunction-workflow |
Create an ETL step with AWS Glue JobIn the following cell, we create a Glue step thats runs an AWS Glue job. The Glue job splits the data in to training and validation sets, and saves the data to CSV format in S3. Glue is performing this extraction, transformation, and load (ETL) in a serverless fashion, so there are ... | etl_step = steps.GlueStartJobRunStep('Split Train & Test DataSet',
parameters={"JobName": execution_input['GlueETLJobName'],
"Arguments":{
'--S3_SOURCE': recipe_data,
'--S3_DEST': 's3a://{}/{}/'.format(bucket, project_name),
'--TRAIN_KEY': ... | _____no_output_____ | MIT-0 | notebooks/sagemaker_databrew_ml_workflow_blog.ipynb | aws-samples/aws-databrew-ml-stepfunction-workflow |
Create a SageMaker Training Step In the following cell, we create the training step and pass the estimator we defined above. See [TrainingStep](https://aws-step-functions-data-science-sdk.readthedocs.io/en/latest/sagemaker.htmlstepfunctions.steps.sagemaker.TrainingStep) in the AWS Step Functions Data Science SDK docu... | training_step = steps.TrainingStep(
'Model Training',
estimator=xgb,
data={
'train': TrainingInput(train_data, content_type='text/csv'),
'validation': TrainingInput(validation_data, content_type='text/csv')
},
job_name=execution_input['TrainingJobName'],
wait_for_completion=True... | _____no_output_____ | MIT-0 | notebooks/sagemaker_databrew_ml_workflow_blog.ipynb | aws-samples/aws-databrew-ml-stepfunction-workflow |
Create a Model Step In the following cell, we define a model step that will create a model in Amazon SageMaker using the artifacts created during the TrainingStep. See [ModelStep](https://aws-step-functions-data-science-sdk.readthedocs.io/en/latest/sagemaker.htmlstepfunctions.steps.sagemaker.ModelStep) in the AWS Ste... | model_step = steps.ModelStep(
'Save Model',
model=training_step.get_expected_model(),
model_name=execution_input['ModelName'],
result_path='$.ModelStepResults'
) | _____no_output_____ | MIT-0 | notebooks/sagemaker_databrew_ml_workflow_blog.ipynb | aws-samples/aws-databrew-ml-stepfunction-workflow |
Create a Lambda StepIn the following cell, we define a lambda step that will invoke the previously created lambda function as part of our Step Function workflow. See [LambdaStep](https://aws-step-functions-data-science-sdk.readthedocs.io/en/latest/compute.htmlstepfunctions.steps.compute.LambdaStep) in the AWS Step Fun... | lambda_step = steps.compute.LambdaStep(
'Query Training Results',
parameters={
"FunctionName": execution_input['LambdaFunctionName'],
'Payload':{
"TrainingJobName.$": '$.TrainingJobName'
}
}
) | _____no_output_____ | MIT-0 | notebooks/sagemaker_databrew_ml_workflow_blog.ipynb | aws-samples/aws-databrew-ml-stepfunction-workflow |
Create a Choice State Step In the following cell, we create a choice step in order to build a dynamic workflow. This choice step branches based off of the results of our SageMaker training step: did the training job fail or should the model be saved and the endpoint be updated? We will add specific rules to this choic... | check_accuracy_step = steps.states.Choice(
'Accuracy > 90%'
) | _____no_output_____ | MIT-0 | notebooks/sagemaker_databrew_ml_workflow_blog.ipynb | aws-samples/aws-databrew-ml-stepfunction-workflow |
Create an Endpoint Configuration StepIn the following cell we create an endpoint configuration step. See [EndpointConfigStep](https://aws-step-functions-data-science-sdk.readthedocs.io/en/latest/sagemaker.htmlstepfunctions.steps.sagemaker.EndpointConfigStep) in the AWS Step Functions Data Science SDK documentation to ... | endpoint_config_step = steps.EndpointConfigStep(
"Create Model Endpoint Config",
endpoint_config_name=execution_input['ModelName'],
model_name=execution_input['ModelName'],
initial_instance_count=1,
instance_type='ml.m4.xlarge'
) | _____no_output_____ | MIT-0 | notebooks/sagemaker_databrew_ml_workflow_blog.ipynb | aws-samples/aws-databrew-ml-stepfunction-workflow |
Update the Model Endpoint StepIn the following cell, we create the Endpoint step to deploy the new model as a managed API endpoint, updating an existing SageMaker endpoint if our choice state is successful. | endpoint_step = steps.EndpointStep(
'Update Model Endpoint',
endpoint_name=execution_input['EndpointName'],
endpoint_config_name=execution_input['ModelName'],
update=False
) | _____no_output_____ | MIT-0 | notebooks/sagemaker_databrew_ml_workflow_blog.ipynb | aws-samples/aws-databrew-ml-stepfunction-workflow |
Create the Fail State StepIn addition, we create a Fail step which proceeds from our choice state if the validation accuracy of our model is lower than the threshold we define. See [FailStateStep](https://aws-step-functions-data-science-sdk.readthedocs.io/en/latest/states.htmlstepfunctions.steps.states.Fail) in the AW... | fail_step = steps.states.Fail(
'Model Accuracy Too Low',
comment='Validation accuracy lower than threshold'
) | _____no_output_____ | MIT-0 | notebooks/sagemaker_databrew_ml_workflow_blog.ipynb | aws-samples/aws-databrew-ml-stepfunction-workflow |
Add Rules to Choice StateIn the cells below, we add a threshold rule to our choice state. Therefore, if the validation accuracy of our model is below 0.90, we move to the Fail State. If the validation accuracy of our model is above 0.90, we move to the save model step with proceeding endpoint update. See [here](https:... | threshold_rule = steps.choice_rule.ChoiceRule.NumericLessThan(variable=lambda_step.output()['Payload']['trainingMetrics'][0]['Value'], value=.1)
check_accuracy_step.add_choice(rule=threshold_rule, next_step=endpoint_config_step)
check_accuracy_step.default_choice(next_step=fail_step) | _____no_output_____ | MIT-0 | notebooks/sagemaker_databrew_ml_workflow_blog.ipynb | aws-samples/aws-databrew-ml-stepfunction-workflow |
Link all the Steps TogetherFinally, create your workflow definition by chaining all of the steps together that we've created. See [Chain](https://aws-step-functions-data-science-sdk.readthedocs.io/en/latest/sagemaker.htmlstepfunctions.steps.states.Chain) in the AWS Step Functions Data Science SDK documentation to lear... | endpoint_config_step.next(endpoint_step)
workflow_definition = steps.Chain([
recipe_step,
etl_step,
training_step,
model_step,
lambda_step,
check_accuracy_step
]) | _____no_output_____ | MIT-0 | notebooks/sagemaker_databrew_ml_workflow_blog.ipynb | aws-samples/aws-databrew-ml-stepfunction-workflow |
Run the WorkflowCreate your workflow using the workflow definition above, and render the graph with [render_graph](https://aws-step-functions-data-science-sdk.readthedocs.io/en/latest/workflow.htmlstepfunctions.workflow.Workflow.render_graph): | workflow = Workflow(
name='MarketingCampaignInference_{}'.format(id),
definition=workflow_definition,
role=workflow_execution_role,
execution_input=execution_input
)
# render workflow graph
workflow.render_graph()
# create workflow
workflow.create()
# run the workflow
execution = workflow.execute(
... | _____no_output_____ | MIT-0 | notebooks/sagemaker_databrew_ml_workflow_blog.ipynb | aws-samples/aws-databrew-ml-stepfunction-workflow |
__Exercise 1__ | # MACHINE TRANSLATION:
# see e.g. http://www.aclweb.org/anthology/R11-1077, https://nlp.stanford.edu/courses/cs224n/2010/reports/bipins.pdf
# data: parallel corpora, aligned at sentence level (automatically or manually)
# size: usually assumed the larger the better, 2nd paper: 100,00 documents
# reasons for large amoun... | _____no_output_____ | MIT | chapter_6_exercises.ipynb | JuliaNeumann/nltk_book_exercises |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.