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 |
|---|---|---|---|---|---|
SVG Drawing FunctionHere's Hardmaru's Drawing Functions from _write-rnn-tensorflow_. Big hat tip to Hardmaru for this!Here's the source: https://github.com/hardmaru/write-rnn-tensorflow/blob/master/utils.py | import svgwrite
from IPython.display import SVG, display
def get_bounds(data, factor):
min_x = 0
max_x = 0
min_y = 0
max_y = 0
abs_x = 0
abs_y = 0
for i in range(len(data)):
x = float(data[i, 0]) / factor
y = float(data[i, 1]) / factor
abs_x += x
abs_y += y
... | _____no_output_____ | MIT | transformer-mdn-kanji.ipynb | cpmpercussion/keras-transformer-mdn |
Imports | import pandas as pd
import numpy as np
#Python Standard Libs Imports
import json
import urllib2
import sys
from datetime import datetime
from os.path import isfile, join, splitext
from glob import glob
#Imports to enable visualizations
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Functions Basic Functions OTP Functions Analysis Functions Main Code Reading itinerary alternatives data | all_itineraries = pd.read_csv('/local/tarciso/data/its/itineraries/all_itineraries.csv', parse_dates=['planned_start_time','actual_start_time','exec_start_time'])
all_itineraries.head()
all_itineraries.dtypes
len(all_itineraries)
len(all_itineraries.user_trip_id.unique()) | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Adding metadata for further analysis | def get_trip_len_bucket(trip_duration):
if (trip_duration < 10):
return '<10'
elif (trip_duration < 20):
return '10-20'
elif (trip_duration < 30):
return '20-30'
elif (trip_duration < 40):
return '30-40'
elif (trip_duration < 50):
return '40-50'
elif (trip... | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Filtering trips for whose executed itineraries there is no schedule information | def filter_trips_alternatives(trips_alternatives):
min_trip_dur = 10
max_trip_dur = 50
max_trip_start_diff = 20
return trips_alternatives[(trips_alternatives['actual_duration_mins'] >= min_trip_dur) & (trips_alternatives['actual_duration_mins'] <= max_trip_dur)] \
... | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Compute Inefficiency Metrics  | def select_best_itineraries(trips_itineraries,metric_name):
return trips_itineraries.sort_values([metric_name]) \
.groupby(['date','user_trip_id']) \
.nth(0) \
.reset_index() | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Observed Inefficiency | #Choose best itinerary for each trip by selecting the ones with lower actual duration
best_trips_itineraries = select_best_itineraries(clean_itineraries,'actual_duration_mins')
best_trips_itineraries.head()
trips_inefficiency = best_trips_itineraries \
.assign(dur_diff = lambda x: x['exec_durati... | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Number of Trips with/without improvent per Trip Length Bucket | trips_per_length = trips_inefficiency.groupby('trip_length_bucket').size().reset_index(name='total')
trips_per_length
trips_per_length_improved = pos_trips_inefficiency.groupby('trip_length_bucket').size().reset_index(name='total')
trips_per_length_improved
sns.set_style("whitegrid")
#Plot 1 - background - "total" (to... | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Per Trip Length Bucket | trip_len_order=['10-20','20-30','30-40','40-50']
ax = sns.boxplot(x='observed_inef',y='trip_length_bucket', orient='h', data=pos_trips_inefficiency, order=trip_len_order, color='#fc8d62')
ax.set(xlabel='Inefficiency (%)',ylabel='Trip Length')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarci... | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Per Period of Day | period_of_day_order = ['very_late_night','early_morning','morning','midday','afternoon','evening','night','late_night']
ax = sns.boxplot(x='observed_inef',y='period_of_day', data=pos_trips_inefficiency, order=period_of_day_order, color='#fc8d62')
ax.set(xlabel='Inefficiency (%)',ylabel='Period of Day')
fig = ax.get_fi... | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Per Weekday/Weekend | ax = sns.barplot(x='trip_length_bucket',y='observed_inef', hue='weekday', data=pos_trips_inefficiency, color='#fc8d62')
ax.set(xlabel='Trip Length',ylabel='Inefficiency (%)')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/imp_capacity_per_day_period.pdf', bbox_inche... | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Per Day Type | ax = sns.barplot(x='trip_length_bucket',y='observed_inef', hue='day_type', data=pos_trips_inefficiency, color='#fc8d62')
ax.set(xlabel='Trip Length',ylabel='Inefficiency (%)')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/imp_capacity_per_day_period.pdf', bbox_inch... | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Schedule Inefficiency | shortest_planned_itineraries = select_best_itineraries(clean_itineraries[pd.notnull(clean_itineraries['planned_duration_mins'])],'planned_duration_mins') \
[['date','user_trip_id','planned_duration_mins','actual_duration_mins']] \
.rename(index=str,columns={'plann... | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Number of Trips with/without improvent per Trip Length Bucket | trips_per_length = sched_inef.groupby('trip_length_bucket').size().reset_index(name='total')
trips_per_length
trips_per_length_improved = pos_sched_inef.groupby('trip_length_bucket').size().reset_index(name='total')
trips_per_length_improved
sns.set_style("whitegrid")
#Plot 1 - background - "total" (top) series
ax = s... | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Per Trip Length Bucket | trip_len_order=['10-20','20-30','30-40','40-50']
ax = sns.boxplot(x='sched_inef',y='trip_length_bucket', orient='h', data=pos_sched_inef, order=trip_len_order, color='#fc8d62')
ax.set(xlabel='Schedule Inefficiency (%)',ylabel='Trip Length')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso... | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Per Period of Day | period_of_day_order = ['very_late_night','early_morning','morning','midday','afternoon','evening','night','late_night']
ax = sns.boxplot(x='sched_inef',y='period_of_day', data=pos_sched_inef, order=period_of_day_order, color='#fc8d62')
ax.set(xlabel='Schedule Inefficiency (%)',ylabel='Period of Day')
fig = ax.get_figu... | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Per Weekday/Weekend | ax = sns.barplot(x='trip_length_bucket',y='sched_inef', hue='weekday', data=pos_sched_inef, color='#fc8d62')
ax.set(xlabel='Trip Length',ylabel='Schedule Inefficiency (%)')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/imp_capacity_per_day_period.pdf', bbox_inches=... | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Per Day Type | ax = sns.barplot(x='trip_length_bucket',y='sched_inef', hue='day_type', data=pos_sched_inef, color='#fc8d62')
ax.set(xlabel='Trip Length',ylabel='Schedule Inefficiency (%)')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/imp_capacity_per_day_period.pdf', bbox_inches... | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
User choice plan inefficiency | best_scheduled_itineraries = select_best_itineraries(clean_itineraries2,'planned_duration_mins') \
[['date','user_trip_id','planned_duration_mins']] \
.rename(index=str,columns={'planned_duration_mins':'best_planned_duration_mins'})
best_scheduled_itinerar... | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Number of Trips with/without improvent per Trip Length Bucket | trips_per_length = plan_inef.groupby('trip_length_bucket').size().reset_index(name='total')
trips_per_length
trips_per_length_improved = pos_plan_inef.groupby('trip_length_bucket').size().reset_index(name='total')
trips_per_length_improved
sns.set_style("whitegrid")
#Plot 1 - background - "total" (top) series
ax = sns... | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Per Trip Length Bucket | trip_len_order=['10-20','20-30','30-40','40-50']
ax = sns.boxplot(x='plan_inef',y='trip_length_bucket', orient='h', data=pos_plan_inef, order=trip_len_order, color='#fc8d62')
ax.set(xlabel='Plan Inefficiency (%)',ylabel='Trip Length')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/maste... | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Per Period of Day | period_of_day_order = ['very_late_night','early_morning','morning','midday','afternoon','evening','night','late_night']
ax = sns.boxplot(x='plan_inef',y='period_of_day', data=pos_plan_inef, order=period_of_day_order, color='#fc8d62')
ax.set(xlabel='Plan Inefficiency (%)',ylabel='Period of Day')
fig = ax.get_figure()
f... | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Per Weekday/Weekend | ax = sns.barplot(x='trip_length_bucket',y='plan_inef', hue='weekday', data=pos_plan_inef, color='#fc8d62')
ax.set(xlabel='Trip Length',ylabel='Plan Inefficiency (%)')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/imp_capacity_per_day_period.pdf', bbox_inches='tight... | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Per Day Type | ax = sns.barplot(x='trip_length_bucket',y='plan_inef', hue='day_type', data=pos_plan_inef, color='#fc8d62')
ax.set(xlabel='Trip Length',ylabel='Plan Inefficiency (%)')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/imp_capacity_per_day_period.pdf', bbox_inches='tigh... | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
System Schedule Deviation$$\begin{equation*} {Oe - Op}\end{equation*}$$ | sched_deviation = clean_itineraries[clean_itineraries['itinerary_id'] > 0] \
.assign(sched_dev = lambda x: x['actual_duration_mins'] - x['planned_duration_mins'])
sched_deviation.head()
sns.distplot(sched_deviation.sched_dev) | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
User stop waiting time offset$$\begin{equation*} {start(Oe) - start(Op)}\end{equation*}$$ | user_boarding_timediff = clean_itineraries[clean_itineraries['itinerary_id'] > 0] \
.assign(boarding_timediff = lambda x: (x['actual_start_time'] - x['planned_start_time'])/pd.Timedelta(minutes=1))
user_boarding_timediff.head()
sns.distplot(user_boarding_timediff.boarding_timediff) | _____no_output_____ | CNRI-Python | notebooks/inefficiency-analysis-pandas.ipynb | tarcisobraz/trips-optimality-exp |
Whale Sound ExplorationIn this tutorial we will explore some data which contain right whale up-calls. The dataset was shared as part of a [2013 Kaggle competition](https://www.kaggle.com/c/whale-detection-challenge). Our goal is not to show the best winning algorithm to detect a call, but share a simple pipeline for ... | # ignore warnings
import warnings
warnings.filterwarnings("ignore")
# importing multiple visualization libraries
%matplotlib inline
import matplotlib.pyplot as plt
from matplotlib import mlab
import pylab as pl
import seaborn
# importing libraries to manipulate the data files
import os
from glob import glob
# importing... | _____no_output_____ | CC-BY-4.0 | notebooks/1_data_loading_colab.ipynb | valentina-s/Oceans19-data-science-tutorial |
The `train` folder contains many `.aiff` files (2 second snippets) and we have `.csv` document which contains the corresponding labels. | !wget http://oceanhackweek2018.s3.amazonaws.com/oceans_data/train.tar.gz
!wget http://oceanhackweek2018.s3.amazonaws.com/oceans_data/labels.csv
!tar xvzf train.tar.gz
# read the audio filenames
filenames = sorted(glob(os.path.join('train','*.aiff')))
print('There are '+str(len(filenames))+' files.' )
# read the labels
... | _____no_output_____ | CC-BY-4.0 | notebooks/1_data_loading_colab.ipynb | valentina-s/Oceans19-data-science-tutorial |
The format of the labels is: | labels.head(10) | _____no_output_____ | CC-BY-4.0 | notebooks/1_data_loading_colab.ipynb | valentina-s/Oceans19-data-science-tutorial |
Let's look at one of those files. | # reading the file info
whale_sample_file = 'train00006.aiff'
whale_aiff = aifc.open(os.path.join('train',whale_sample_file),'r')
print ("Frames:", whale_aiff.getnframes() )
print ("Frame rate (frames per second):", whale_aiff.getframerate())
# reading the data
whale_strSig = whale_aiff.readframes(whale_aiff.getnframes... | _____no_output_____ | CC-BY-4.0 | notebooks/1_data_loading_colab.ipynb | valentina-s/Oceans19-data-science-tutorial |
Working directly with the signals is hard (there is important frequency information). Let's calculate the spectrograms for each of the signals and use as features. | # a function for plotting spectrograms
def PlotSpecgram(P, freqs, bins):
"""Spectrogram"""
Z = np.flipud(P) # flip rows so that top goes to bottom, bottom to top, etc.
xextent = 0, np.amax(bins)
xmin, xmax = xextent
extent = xmin, xmax, freqs[0], freqs[-1]
im = pl.imshow(Z, extent=extent,cmap = ... | _____no_output_____ | CC-BY-4.0 | notebooks/1_data_loading_colab.ipynb | valentina-s/Oceans19-data-science-tutorial |
Feature Extraction--- We will go through the files and extract the spectrograms from each of them. We will do it for the first N files. | N = 10000 #number of files to use
# create a dictionary which contains all the spectrograms, labeled by the filename
spec_dict = {}
# threshold to cut higher frequencies
m = 60
# loop through all the files
for filename in filenames[:N]:
# read the file
aiff = aifc.open(filename,'r')
whale_strSig = aiff.re... | _____no_output_____ | CC-BY-4.0 | notebooks/1_data_loading_colab.ipynb | valentina-s/Oceans19-data-science-tutorial |
Most machine learning algorithms in Python expect the data to come in a format **observations** x **features**. In order to get the data in this format we need to convert the two-dimensional spectrogram into a long vector. For that we will use the `ravel` function. | # We will put the data in a dictionary
feature_dict = {}
for key in filenames[:N]:
# vectorize the spectrogram
feature_dict[key.split('/')[-1]] = spec_dict[key].ravel()
# convert to a pandas dataframe
X = pd.DataFrame(feature_dict).T
X.head(5)
# we do not need these objects anymore so let's release them from m... | _____no_output_____ | CC-BY-4.0 | notebooks/1_data_loading_colab.ipynb | valentina-s/Oceans19-data-science-tutorial |
References:https://www.kaggle.com/c/whale-detection-challengehttps://github.com/jaimeps/whale-sound-classification | _____no_output_____ | CC-BY-4.0 | notebooks/1_data_loading_colab.ipynb | valentina-s/Oceans19-data-science-tutorial | |
Multi-Layer Perceptron, MNIST---In this notebook, we will train an MLP to classify images from the [MNIST database](http://yann.lecun.com/exdb/mnist/) hand-written digit database.The process will be broken down into the following steps:>1. Load and visualize the data2. Define a neural network3. Train the model4. Evalu... | # import libraries
import torch
import numpy as np | _____no_output_____ | MIT | convolutional-neural-networks/mnist-mlp/mnist_mlp_exercise.ipynb | Oriolac/deep-learning-pytorch-exs |
--- Load and Visualize the [Data](http://pytorch.org/docs/stable/torchvision/datasets.html)Downloading may take a few moments, and you should see your progress as the data is loading. You may also choose to change the `batch_size` if you want to load more data at a time.This cell will create DataLoaders for each of our... | # The MNIST datasets are hosted on yann.lecun.com that has moved under CloudFlare protection
# Run this script to enable the datasets download
# Reference: https://github.com/pytorch/vision/issues/1938
from six.moves import urllib
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0'... | Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz
Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz to data/MNIST/raw/train-images-idx3-ubyte.gz
| MIT | convolutional-neural-networks/mnist-mlp/mnist_mlp_exercise.ipynb | Oriolac/deep-learning-pytorch-exs |
Visualize a Batch of Training DataThe first step in a classification task is to take a look at the data, make sure it is loaded in correctly, then make any initial observations about patterns in that data. | import matplotlib.pyplot as plt
%matplotlib inline
# obtain one batch of training images
dataiter = iter(train_loader)
images, labels = dataiter.next()
images = images.numpy()
# plot the images in the batch, along with the corresponding labels
fig = plt.figure(figsize=(25, 4))
for idx in np.arange(20):
ax = f... | /tmp/ipykernel_2060/611598023.py:12: MatplotlibDeprecationWarning: Passing non-integers as three-element position specification is deprecated since 3.3 and will be removed two minor releases later.
ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[])
| MIT | convolutional-neural-networks/mnist-mlp/mnist_mlp_exercise.ipynb | Oriolac/deep-learning-pytorch-exs |
View an Image in More Detail | img = np.squeeze(images[1])
fig = plt.figure(figsize = (12,12))
ax = fig.add_subplot(111)
ax.imshow(img, cmap='gray')
width, height = img.shape
thresh = img.max()/2.5
for x in range(width):
for y in range(height):
val = round(img[x][y],2) if img[x][y] !=0 else 0
ax.annotate(str(val), xy=(y,x),
... | _____no_output_____ | MIT | convolutional-neural-networks/mnist-mlp/mnist_mlp_exercise.ipynb | Oriolac/deep-learning-pytorch-exs |
--- Define the Network [Architecture](http://pytorch.org/docs/stable/nn.html)The architecture will be responsible for seeing as input a 784-dim Tensor of pixel values for each image, and producing a Tensor of length 10 (our number of classes) that indicates the class scores for an input image. This particular example u... | import torch.nn as nn
import torch.nn.functional as F
## TODO: Define the NN architecture
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# linear layer (784 -> 1 hidden node)
self.fc1 = nn.Linear(28 * 28, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = ... | Net(
(fc1): Linear(in_features=784, out_features=512, bias=True)
(fc2): Linear(in_features=512, out_features=256, bias=True)
(fc3): Linear(in_features=256, out_features=128, bias=True)
(fc4): Linear(in_features=128, out_features=10, bias=True)
(dropout): Dropout(p=0.2, inplace=False)
)
| MIT | convolutional-neural-networks/mnist-mlp/mnist_mlp_exercise.ipynb | Oriolac/deep-learning-pytorch-exs |
Specify [Loss Function](http://pytorch.org/docs/stable/nn.htmlloss-functions) and [Optimizer](http://pytorch.org/docs/stable/optim.html)It's recommended that you use cross-entropy loss for classification. If you look at the documentation (linked above), you can see that PyTorch's cross entropy function applies a soft... | ## TODO: Specify loss and optimization functions
# specify loss function
criterion = nn.CrossEntropyLoss()
# specify optimizer
optimizer = torch.optim.SGD(model.parameters(), lr=0.01) | _____no_output_____ | MIT | convolutional-neural-networks/mnist-mlp/mnist_mlp_exercise.ipynb | Oriolac/deep-learning-pytorch-exs |
--- Train the NetworkThe steps for training/learning from a batch of data are described in the comments below:1. Clear the gradients of all optimized variables2. Forward pass: compute predicted outputs by passing inputs to the model3. Calculate the loss4. Backward pass: compute gradient of the loss with respect to mode... | # number of epochs to train the model
n_epochs = 30 # suggest training between 20-50 epochs
model.train() # prep model for training
for epoch in range(n_epochs):
# monitor training loss
train_loss = 0.0
###################
# train the model #
###################
for data, target in train... | Epoch: 1 Training Loss: 1.263758
Epoch: 2 Training Loss: 0.382051
Epoch: 3 Training Loss: 0.266715
Epoch: 4 Training Loss: 0.200021
Epoch: 5 Training Loss: 0.162390
Epoch: 6 Training Loss: 0.137244
Epoch: 7 Training Loss: 0.119641
Epoch: 8 Training Loss: 0.105442
Epoch: 9 Training Loss: 0.094517
Epoch: 10 Tra... | MIT | convolutional-neural-networks/mnist-mlp/mnist_mlp_exercise.ipynb | Oriolac/deep-learning-pytorch-exs |
--- Test the Trained NetworkFinally, we test our best model on previously unseen **test data** and evaluate it's performance. Testing on unseen data is a good way to check that our model generalizes well. It may also be useful to be granular in this analysis and take a look at how this model performs on each class as w... | # initialize lists to monitor test loss and accuracy
test_loss = 0.0
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
model.eval() # prep model for *evaluation*
for data, target in test_loader:
# forward pass: compute predicted outputs by passing inputs to the model
output... | Test Loss: 0.066156
Test Accuracy of 0: 98% (970/980)
Test Accuracy of 1: 99% (1124/1135)
Test Accuracy of 2: 97% (1010/1032)
Test Accuracy of 3: 98% (994/1010)
Test Accuracy of 4: 98% (966/982)
Test Accuracy of 5: 98% (877/892)
Test Accuracy of 6: 97% (937/958)
Test Accuracy of 7: 97% ... | MIT | convolutional-neural-networks/mnist-mlp/mnist_mlp_exercise.ipynb | Oriolac/deep-learning-pytorch-exs |
Visualize Sample Test ResultsThis cell displays test images and their labels in this format: `predicted (ground-truth)`. The text will be green for accurately classified examples and red for incorrect predictions. | # obtain one batch of test images
dataiter = iter(test_loader)
images, labels = dataiter.next()
# get sample outputs
output = model(images)
# convert output probabilities to predicted class
_, preds = torch.max(output, 1)
# prep images for display
images = images.numpy()
# plot the images in the batch, along with pre... | /tmp/ipykernel_2060/3350221300.py:15: MatplotlibDeprecationWarning: Passing non-integers as three-element position specification is deprecated since 3.3 and will be removed two minor releases later.
ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[])
| MIT | convolutional-neural-networks/mnist-mlp/mnist_mlp_exercise.ipynb | Oriolac/deep-learning-pytorch-exs |
Prepare the Model | SAGEMAKER_PATH = r'/home/ec2-user/SageMaker'
MODEL_PATH = os.path.join(SAGEMAKER_PATH, r'sidewalk-cv-assets19/pytorch_pretrained/models/20e_slid_win_no_feats_r18.pt')
os.path.exists(MODEL_PATH)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device
# Use PyTorch's ResNet18
# https://stackoverflow... | _____no_output_____ | MIT | exploratory/2020-03-09-GPUInference.ipynb | w210-accessibility/classify-streetview |
Prep Data | # From Galen
test_transforms = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
#device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# the dataset loads the fil... | _____no_output_____ | MIT | exploratory/2020-03-09-GPUInference.ipynb | w210-accessibility/classify-streetview |
Execute Inference on 2 Sample Images | # Note on how to make sure the model and the input tensors are both on cuda device (gpu)
# https://discuss.pytorch.org/t/runtimeerror-input-type-torch-cuda-floattensor-and-weight-type-torch-floattensor-should-be-the-same/21782/6
def predict_image(image, model):
image_tensor = test_transforms(image).float()
imag... | _____no_output_____ | MIT | exploratory/2020-03-09-GPUInference.ipynb | w210-accessibility/classify-streetview |
ENTRADA Y SALIDA DE DATOS 1. Entrada de Información por teclado (Input) En python la funcion input() nos ayudará con la tarea de capturar datos del usuario | # input por defecto nos devuelve datos de tipo texto
# SHIFT + TAB -> Documentacion de la palabra a ejecutar
decimal = input("Introduce un número decimal con punto: ")
type(decimal)
numero = float(decimal)
# tab autocompleta texto
numero
type(numero) | _____no_output_____ | Apache-2.0 | Modulo1/4. Entrada y Salida de Datos.ipynb | IsabelMamani/PythonMamani |
2. Entrada de datos por Argumentos Para poder enviar información a un script y manejarla, tenemos que utilizar la librería de sistema [sys](https://www.geeksforgeeks.org/how-to-use-sys-argv-in-python/). En ella encontraremos la lista argv que almacena los argumentos enviados al script. | import sys
print(sys.argv) | ['C:\\Users\\valer\\anaconda3\\lib\\site-packages\\ipykernel_launcher.py', '-f', 'C:\\Users\\valer\\AppData\\Roaming\\jupyter\\runtime\\kernel-0dde64eb-5976-4dc0-aad5-83f93a56f1e0.json']
| Apache-2.0 | Modulo1/4. Entrada y Salida de Datos.ipynb | IsabelMamani/PythonMamani |
3. Salida de información (Output) La función print nos ayudará a realizar salidas de información | print('hola') | hola
| Apache-2.0 | Modulo1/4. Entrada y Salida de Datos.ipynb | IsabelMamani/PythonMamani |
EJERCICIOS 1. Realiza un programa que lea 2 números por teclado y determine los siguientes aspectos (es suficiene con mostrar True o False):- Si los dos números son iguales- Si los dos números son diferentes- Si el primero es mayor que el segundo- Si el segundo es mayor o igual que el primero | num1=float(input("Escribir numero 1:"))
num2=float(input("Escribir numero 2:"))
print("Son iguales?",num1==num2)
print("Son diferentes?",num1!=num2)
print("Número1 mayor?",num1>num2)
print("Número2 mayor o igual que Numero2?",num1<=num2)
a = float( input("Primer número: ") )
b = float( input("Segundo número: ") )
print... | Los dos números son iguales: False
Los dos números son diferentes: True
El primero es mayor que el segundo: True
El segundo es mayor o igual que el primero: False
| Apache-2.0 | Modulo1/4. Entrada y Salida de Datos.ipynb | IsabelMamani/PythonMamani |
2. Escribir un programa que pregunte el nombre del usuario en la consola y después de que el usuario lo introduzca muestre por pantalla la cadena ¡Hola "nombre"!, donde "nombre" es el nombre que el usuario haya introducido. | nombre=input("¿Cuál es tu nombre?")
"¡Hola " + nombre+"!" | ¿Cuál es tu nombre? Valeria
| Apache-2.0 | Modulo1/4. Entrada y Salida de Datos.ipynb | IsabelMamani/PythonMamani |
CLX WorkflowThis is an introduction to the CLX Workflow and it's I/O components. What is a CLX Workflow?A CLX Workflow receives data from a particular source, performs operations on that data within a GPU dataframe, and outputs that data to a particular destination. This guide will teach you how to configure your wor... | from clx.workflow.workflow import Workflow
class CustomWorkflow(Workflow):
def workflow(self, dataframe):
dataframe["enriched"] = "enriched output"
return dataframe | _____no_output_____ | Apache-2.0 | docs/source/intro-clx-workflow.ipynb | jakirkham/clx |
The Workflow relies on the Workflow class which handles the I/O and general data processing functionality. To implement a new Workflow, the developer need only implement the `workflow` function which receives an input dataframe, as shown above. A more advanced example of a Worlflow can be found [here](https://github.... | source = {
"type": "fs",
"input_format": "csv",
"input_path": "/full/path/to/input/data",
"schema": ["raw"],
"delimiter": ",",
"required_cols": ["raw"],
"dtype": ["str"],
"header": 0
}
destination = {
"type": "fs",
"output_format": "csv",
"output_path": "/full/path/to/output/data"
} | _____no_output_____ | Apache-2.0 | docs/source/intro-clx-workflow.ipynb | jakirkham/clx |
The first step to configuring the input and output of a workflow is to determine the source and destination type. Then to set the associated parameters for that specific type.As seen above the `type` property is listed first and can be one of the following. Source Types * `fs` - Read from a local filesystem* `dask_fs`... | source = {
"type": "fs",
"input_format": "parquet",
"input_path": "/full/path/to/input/data",
"columns": ["x"]
} | _____no_output_____ | Apache-2.0 | docs/source/intro-clx-workflow.ipynb | jakirkham/clx |
Dask Filesystem If the `dask_fs` type is used the developer must distinguish the data format using the `input_format` attribute. Formats available are: csv, parquet, and orc. The associated parameters available for the `dask_fs` type and `input_format` are listed within the [Dask cuDF](https://rapidsai.github.io/pro... | source = {
"type": "dask_fs",
"input_format": "csv",
"input_path": "/full/path/to/input/data/*.csv"
} | _____no_output_____ | Apache-2.0 | docs/source/intro-clx-workflow.ipynb | jakirkham/clx |
KafkaIf the `kafka` type is used the following parameters must be indicated Source * `kafka_brokers` - Kafka brokers* `group_id` - Group ID for consuming kafka messages* `consumer_kafka_topics` - Names of kafka topics to read from* `batch_size` - Indicates number of kafka messages to read before data is processe... | source = {
"type": "kafka",
"kafka_brokers": "kafka:9092",
"group_id": "cyber",
"batch_size": 10,
"consumer_kafka_topics": ["topic1", "topic2"],
"time_window": 5
}
dest = {
"type": "kafka",
"kafka_brokers": "kafka:9092"
"batch_size": 10,
"publisher_kafka_topic": "topic3",
"ou... | _____no_output_____ | Apache-2.0 | docs/source/intro-clx-workflow.ipynb | jakirkham/clx |
Tying it together Once we have established our workflow and source and destination configurations we can now run our workflow. Let's create a workflow using the `CustomWorkflow` we created above.Firstly, we must know the parameters for instantiating a basic workflow * `name` - The name of the workflow* `source` - The... | from clx.workflow.workflow import Workflow
class CustomWorkflow(Workflow):
def workflow(self, dataframe):
dataframe["enriched"] = "enriched output"
return dataframe
source = {
"type": "fs",
"input_format": "csv",
"input_path": "/full/path/to/input/data",
"schema": ["raw"],
"delim... | _____no_output_____ | Apache-2.0 | docs/source/intro-clx-workflow.ipynb | jakirkham/clx |
Workflow configurations in an external fileSometimes workflow configurations may need to change dependent upon the environment. To avoid declaring workflow configurations within sourcecode you may also declare them in an external yaml file. A workflow will look for and establish I/O connections by searching for config... | # Workflow config located at /etc/clx/my_new_workflow/workflow.yaml
my_new_workflow = CustomWorkflow(name="my_new_workflow") | _____no_output_____ | Apache-2.0 | docs/source/intro-clx-workflow.ipynb | jakirkham/clx |
Generate dataset | np.random.seed(12)
y = np.random.randint(0,10,5000)
idx= []
for i in range(10):
print(i,sum(y==i))
idx.append(y==i)
x = np.zeros((5000,2))
np.random.seed(12)
x[idx[0],:] = np.random.multivariate_normal(mean = [4,6.5],cov=[[0.01,0],[0,0.01]],size=sum(idx[0]))
x[idx[1],:] = np.random.multivariate_normal(mean = [5... | _____no_output_____ | MIT | AAAI/Interpretability/dataset1/second_layer_averaging_adam_lr001.ipynb | lnpandey/DL_explore_synth_data |
load mosaic data | class MosaicDataset(Dataset):
"""MosaicDataset dataset."""
def __init__(self, mosaic_list, mosaic_label,fore_idx):
"""
Args:
csv_file (string): Path to the csv file with annotations.
root_dir (string): Directory with all the images.
transform (callable, optional): Optional transfo... | _____no_output_____ | MIT | AAAI/Interpretability/dataset1/second_layer_averaging_adam_lr001.ipynb | lnpandey/DL_explore_synth_data |
models | class Focus_deep(nn.Module):
'''
deep focus network averaged at zeroth layer
input : elemental data
'''
def __init__(self,inputs,output,K,d):
super(Focus_deep,self).__init__()
self.inputs = inputs
self.output = output
self.K = K
self.d = d
self.... | _____no_output_____ | MIT | AAAI/Interpretability/dataset1/second_layer_averaging_adam_lr001.ipynb | lnpandey/DL_explore_synth_data |
training | number_runs = 10
FTPT_analysis = pd.DataFrame(columns = ["FTPT","FFPT", "FTPF","FFPF"])
full_analysis= []
for n in range(number_runs):
print("--"*40)
# instantiate focus and classification Model
torch.manual_seed(n)
where = Focus_deep(2,1,9,2).double()
where.linear2.weight.data[25:,:] = where.linear2.weigh... | _____no_output_____ | MIT | AAAI/Interpretability/dataset1/second_layer_averaging_adam_lr001.ipynb | lnpandey/DL_explore_synth_data |
说明: 给定一个仅由字符a,b和c组成的字符串s。 返回至少包含所有这些字符a,b和c的子字符串的数目。Example 1: Input: s = "abcabc" Output: 10 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again). ... | class Solution:
def numberOfSubstrings(self, s: str) -> int:
letters = {'a', 'b', 'c'}
N = len(s)
count = 0
for gap in range(3, N + 1):
for start in range(N - gap + 1):
sub_str = s[start:start + gap]
if set(sub_str) == letters:
... | _____no_output_____ | Apache-2.0 | String/1012/1358. Number of Substrings Containing All Three Characters.ipynb | YuHe0108/Leetcode |
Reflect Tables into SQLAlchemy ORM | # Python SQL toolkit and Object Relational Mapper
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
engine = create_engine("sqlite:///Resources/hawaii.sqlite")
# reflect an existing database into a new model
Base = automap_bas... | _____no_output_____ | ADSL | climate_starter.ipynb | pbhoomika888/sqlalchemy_challenge |
Exploratory Climate Analysis | # Design a query to retrieve the last 12 months of precipitation data and plot the results
last_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first()[0]
last_date
# Calculate the date 1 year ago from the last data point in the database
last_year = dt.datetime.strptime(last_date, "%Y-%m-%d") -... | _____no_output_____ | ADSL | climate_starter.ipynb | pbhoomika888/sqlalchemy_challenge |
 | # Use Pandas to calcualte the summary statistics for the precipitation data
prec_df.describe() | _____no_output_____ | ADSL | climate_starter.ipynb | pbhoomika888/sqlalchemy_challenge |
 | # Design a query to show how many stations are available in this dataset?
station_count = session.query(Station.station).count()
station_count
# What are the most active stations? (i.e. what stations have the most rows)?
# List the stations and the counts in descending order.
active_station = session.query(Measurement.... | _____no_output_____ | ADSL | climate_starter.ipynb | pbhoomika888/sqlalchemy_challenge |
 | # This function called `calc_temps` will accept start date and end date in the format '%Y-%m-%d'
# and return the minimum, average, and maximum temperatures for that range of dates
def calc_temps(start_date, end_date):
"""TMIN, TAVG, and TMAX for a list of dates.
Args:
start_date (string): A date ... | [('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6, 0.38), ('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0, 0.36), ('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9, 0.3), ('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4,... | ADSL | climate_starter.ipynb | pbhoomika888/sqlalchemy_challenge |
Optional Challenge Assignment | # Create a query that will calculate the daily normals
# (i.e. the averages for tmin, tmax, and tavg for all historic data matching a specific month and day)
def daily_normals(date):
"""Daily Normals.
Args:
date (str): A date string in the format '%m-%d'
Returns:
A list of tu... | _____no_output_____ | ADSL | climate_starter.ipynb | pbhoomika888/sqlalchemy_challenge |
02 | Decision Tree. A Supervised Classification Model - Subscribe to my [Blog ↗](https://blog.pythonassembly.com/)- Let's keep in touch on [LinkedIn ↗](www.linkedin.com/in/jsulopz) 😄 Discipline to Search Solutions in Google > Apply the following steps when **looking for solutions in Google**:>> 1. **Necesity**: How t... | import seaborn as sns
df = sns.load_dataset(name='titanic').iloc[:, :4]
df.head() | _____no_output_____ | MIT | II Machine Learning & Deep Learning/02_Decision Tree. A Supervised Classification Model/02session_decision-tree.ipynb | isisfisica/resolving-python-data-science |
`DecisionTreeClassifier()` Model in Python Build the Model > 1. **Necesity**: Build Model> 2. **Google**: How do you search for the solution?> 3. **Solution**: Find the `function()` that makes it happen Code Thinking> Which function computes the Model?> - `fit()`>> How could can you **import the function in Python**... | fit()
model.fit() | _____no_output_____ | MIT | II Machine Learning & Deep Learning/02_Decision Tree. A Supervised Classification Model/02session_decision-tree.ipynb | isisfisica/resolving-python-data-science |
`model = ?` | from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier()
model.__dict__
model.fit() | _____no_output_____ | MIT | II Machine Learning & Deep Learning/02_Decision Tree. A Supervised Classification Model/02session_decision-tree.ipynb | isisfisica/resolving-python-data-science |
Separate Variables for the Model> Regarding their role:> 1. **Target Variable `y`**>> - [ ] What would you like **to predict**?>> 2. **Explanatory Variable `X`**>> - [ ] Which variable will you use **to explain** the target? | explanatory = df.drop(columns='survived')
target = df.survived | _____no_output_____ | MIT | II Machine Learning & Deep Learning/02_Decision Tree. A Supervised Classification Model/02session_decision-tree.ipynb | isisfisica/resolving-python-data-science |
Finally `fit()` the Model | model.__dict__
model.fit(X=explanatory, y=target)
import pandas as pd
pd.get_dummies(data=df)
df = pd.get_dummies(data=df, drop_first=True)
df
explanatory = df.drop(columns='survived')
target = df.survived
model.fit(X=explanatory, y=target)
df
df.isna().sum()
df.fillna('hola')
df.dropna(inplace=True) # df = df.dropna()... | _____no_output_____ | MIT | II Machine Learning & Deep Learning/02_Decision Tree. A Supervised Classification Model/02session_decision-tree.ipynb | isisfisica/resolving-python-data-science |
Calculate a Prediction with the Model > - `model.predict_proba()` | model.predict_proba() | _____no_output_____ | MIT | II Machine Learning & Deep Learning/02_Decision Tree. A Supervised Classification Model/02session_decision-tree.ipynb | isisfisica/resolving-python-data-science |
Model Visualization > - `tree.plot_tree()` Model Interpretation > Why `sex` is the most important column? What has to do with **EDA** (Exploratory Data Analysis)? | %%HTML
<iframe width="560" height="315" src="https://www.youtube.com/embed/7VeUPuFGJHk" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> | _____no_output_____ | MIT | II Machine Learning & Deep Learning/02_Decision Tree. A Supervised Classification Model/02session_decision-tree.ipynb | isisfisica/resolving-python-data-science |
Prediction vs Reality > How good is our model? | dfsel = df[['survived']].copy()
dfsel['pred'] = model.predict(X=explanatory)
dfsel.sample(10)
comp = dfsel.survived == dfsel.pred
comp.sum()
comp.sum()/714
comp.mean() | _____no_output_____ | MIT | II Machine Learning & Deep Learning/02_Decision Tree. A Supervised Classification Model/02session_decision-tree.ipynb | isisfisica/resolving-python-data-science |
Precision > - `model.score()` | model.score(X=explanatory, y=target) | _____no_output_____ | MIT | II Machine Learning & Deep Learning/02_Decision Tree. A Supervised Classification Model/02session_decision-tree.ipynb | isisfisica/resolving-python-data-science |
Parse Java Methods----(C) Maxim Gansert, 2020, Mindscan Engineering | import sys
sys.path.insert(0,'../src')
import os
import datetime
from com.github.c2nes.javalang import tokenizer, parser, ast
from de.mindscan.fluentgenesis.dataprocessing.method_extractor import tokenize_file, extract_allmethods_from_compilation_unit
from de.mindscan.fluentgenesis.bpe.bpe_model import BPEModel
from ... | _____no_output_____ | MIT | ipynb/parse_java_methods_0x01.ipynb | mindscan-de/FluentGenesis-Classifier |
Simple Perceptron | import tensorflow as tf
import pandas as pd
import numpy as np
%load_ext tensorboard
# Import the dataset
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# For now, we'll focus on digit images of fives
is_five_train = y_train == 5
is_five_test = y_test == 5
labels = ["Not five", "five"]
# ... | _____no_output_____ | MIT | supervised/classification/neural-networks/mnist/YT tutorial - Weights and biases.ipynb | HarshaRamayanam/ml-algorithms |
Creating a model**Step 1: Design your model**Model 1:```(28, 28) ---> Flatten (784) ---> Dense (1)loss : mse (default attr.)optimizer : adam (default attr.)``` | # Imports required for building model
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Flatten, Dense
# Create a simple perceptron model
model = Sequential(name="model_1")
model.add(Flatten(input_shape=(img_width, img_height)))
model.add(Dense(1))
# Shows how your model was built
mod... | Model: "model_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
flatten (Flatten) (None, 784) 0
_______________________________________... | MIT | supervised/classification/neural-networks/mnist/YT tutorial - Weights and biases.ipynb | HarshaRamayanam/ml-algorithms |
**Step 2: Specify your model parameters** | model_params = {
"epochs": 10,
"batch_size": 32,
"loss": "mse",
"optimizer": "adam",
} | _____no_output_____ | MIT | supervised/classification/neural-networks/mnist/YT tutorial - Weights and biases.ipynb | HarshaRamayanam/ml-algorithms |
**Step 3: Compile the model with the parameters** | model.compile(loss=model_params["loss"],
optimizer=model_params["optimizer"],
metrics=['accuracy']) | _____no_output_____ | MIT | supervised/classification/neural-networks/mnist/YT tutorial - Weights and biases.ipynb | HarshaRamayanam/ml-algorithms |
**Step 4: Fit / Train the model*****(Optional)*** Specify tensorboard callbacks. Run tensorboard command first (after below cell) and then run the below cell. Then click on refersh icon on top right of tensorboard after every epoch to live track the accuracy and loss | from tensorflow.keras.callbacks import TensorBoard
log_dir = "logs/fit/" + model.name
tb_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)
model.fit(x_train, is_five_train,
epochs=model_params["epochs"],
batch_size=model_params["batch_size"],
validation_data... | _____no_output_____ | MIT | supervised/classification/neural-networks/mnist/YT tutorial - Weights and biases.ipynb | HarshaRamayanam/ml-algorithms |
**Step 5: Evaluate the model**Predict the test dataset and analyze them with corresponding test labels to check whether they make sense. | # Predict first 10 test samples
n_samples = 10000
predictions = model.predict(x_test[:n_samples, :, :])
true_labels = y_test[:n_samples]
is_five = is_five_test[:n_samples]
pd.DataFrame(data={
"predicted_label": predictions.flatten(),
"true_label": true_labels,
"is_five": is_five
}) | _____no_output_____ | MIT | supervised/classification/neural-networks/mnist/YT tutorial - Weights and biases.ipynb | HarshaRamayanam/ml-algorithms |
**Step 6: Debug, rebuild, retrain and re-evaluate your model** | # Let's try more epochs, say 100
model_params["epochs"] = 100
# create a new model with same architecture
new_model = tf.keras.models.clone_model(model)
new_model._name = "model_2"
new_model.summary()
new_model.compile(loss=model_params["loss"],
optimizer=model_params["optimizer"],
metrics=[... | _____no_output_____ | MIT | supervised/classification/neural-networks/mnist/YT tutorial - Weights and biases.ipynb | HarshaRamayanam/ml-algorithms |
We haven't tried an activation function. That's why our model is broken. Let's add a sigmoid activation to our perceptron | model_params["epochs"] = 10
model_params
new_model = Sequential(name="model_3")
new_model.add(Flatten(input_shape=(img_width, img_height)))
new_model.add(Dense(1, activation='relu'))
new_model.summary()
new_model.compile(loss=model_params["loss"],
optimizer=model_params["optimizer"],
metric... | _____no_output_____ | MIT | supervised/classification/neural-networks/mnist/YT tutorial - Weights and biases.ipynb | HarshaRamayanam/ml-algorithms |
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 | intro-to-pytorch/Part 8 - Transfer Learning (Exercises).ipynb | agisga/deep-learning-v2-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/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 | intro-to-pytorch/Part 8 - Transfer Learning (Exercises).ipynb | agisga/deep-learning-v2-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 | /home/user/miniconda/envs/py36/lib/python3.6/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 | intro-to-pytorch/Part 8 - Transfer Learning (Exercises).ipynb | agisga/deep-learning-v2-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 | intro-to-pytorch/Part 8 - Transfer Learning (Exercises).ipynb | agisga/deep-learning-v2-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']:
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 ... | Device = cpu; Time per batch: 11.147 seconds
Device = cuda; Time per batch: 0.014 seconds
| MIT | intro-to-pytorch/Part 8 - Transfer Learning (Exercises).ipynb | agisga/deep-learning-v2-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... | device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(f"Device {device}")
model = models.resnet101(pretrained=True)
model | Device cuda:0
| MIT | intro-to-pytorch/Part 8 - Transfer Learning (Exercises).ipynb | agisga/deep-learning-v2-pytorch |
Freeze parameters. | for param in model.parameters():
param.requires_grad = False | _____no_output_____ | MIT | intro-to-pytorch/Part 8 - Transfer Learning (Exercises).ipynb | agisga/deep-learning-v2-pytorch |
Replace model head. | model.fc = nn.Sequential(nn.Linear(2048, 256),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(256, 2),
nn.LogSoftmax(dim=1))
model.to(device) | _____no_output_____ | MIT | intro-to-pytorch/Part 8 - Transfer Learning (Exercises).ipynb | agisga/deep-learning-v2-pytorch |
Define the loss function and the optimizer. | criterion = nn.NLLLoss()
optimizer = optim.Adam(model.fc.parameters()) | _____no_output_____ | MIT | intro-to-pytorch/Part 8 - Transfer Learning (Exercises).ipynb | agisga/deep-learning-v2-pytorch |
Training loop. | n_epochs = 1
print_every = 5
step, train_loss, train_acc, test_loss, test_acc = 0, 0, 0, 0, 0
def get_batch_acc(preds, labels):
_, pred_class = preds.topk(1, dim=1)
correct_class = (pred_class == labels.view(*pred_class.shape))
batch_acc = torch.mean(correct_class.type(torch.FloatTensor))
return batch_... | Epoch: 0 | Step: 0/70 | Train loss: 0.1420997977256775 | Train acc: 0.09375 | Test loss: 0.5888391725718976 | Test acc: 0.5136718750000002
Epoch: 0 | Step: 5/70 | Train loss: 0.6307643175125123 | Train acc: 0.628125 | Test loss: 0.23891626708209512 | Test acc: 0.9695312500000004
Epoch: 0 | Step: 10/70 | Train loss: 0.2... | MIT | intro-to-pytorch/Part 8 - Transfer Learning (Exercises).ipynb | agisga/deep-learning-v2-pytorch |
Densenet121 | # Use GPU if it's available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = models.densenet121(pretrained=True)
# Freeze parameters so we don't backprop through them
for param in model.parameters():
param.requires_grad = False
model.classifier = nn.Sequential(nn.Linear(1024, 256... | Epoch 1/1.. Train loss: 1.046.. Test loss: 0.468.. Test accuracy: 0.691
Epoch 1/1.. Train loss: 0.476.. Test loss: 0.286.. Test accuracy: 0.880
Epoch 1/1.. Train loss: 0.347.. Test loss: 0.218.. Test accuracy: 0.920
Epoch 1/1.. Train loss: 0.316.. Test loss: 0.100.. Test accuracy: 0.976
Epoch 1/1.. Train loss: 0.262.. ... | MIT | intro-to-pytorch/Part 8 - Transfer Learning (Exercises).ipynb | agisga/deep-learning-v2-pytorch |
-------------------------------------------------------------------------------------------------------------------------------- | forest_params = {'max_depth': range(4, 21),
'max_features': range(7, 45),
'random_state': range(1, 100)}
locally_best_forest = GridSearchCV(rf, forest_params, n_jobs=-1)
locally_best_forest.fit(X = X_train, y = y_train)
print("Best params:", locally_best_forest.best_params_)
print("Best ... | _____no_output_____ | MIT | model/Forest.ipynb | bogdanovdya/Clients_Lifetime |
TEXTThis notebook serves as supporting material for topics covered in **Chapter 22 - Natural Language Processing** from the book *Artificial Intelligence: A Modern Approach*. This notebook uses implementations from [text.py](https://github.com/aimacode/aima-python/blob/master/text.py). | from text import *
from utils import open_data
from notebook import psource | _____no_output_____ | MIT | text.ipynb | Gerson1366/projeto_ia |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.