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
appears so! 4. If so, eliminate them using the technique you think most suitable.
winsorized_budget = winsorize(education_df['Deficit'], (0.05, 0.05)) plt.boxplot(winsorized_budget, whis = 5)
_____no_output_____
MIT
Data_cleaning_Outlier_EDA_Practice.ipynb
sgf-afk/Class_Assignments
Looks like outliers were taken care of 5. Now create another variable by subtracting the TOTAL_EXPENDITURE from TOTAL_REVENUE. This time, use the outlier eliminated versions of TOTAL_EXPENDITURE from TOTAL_REVENUE. In this newly created variable, can you find any outliers? If so, eliminate them.
education_df['winsordeficit'] = winsorized_revenue - winsorized_expenditure plt.boxplot(education_df['winsordeficit'], whis=5) winsorizedbudget2 = winsorize(education_df['winsordeficit'], (0.05, 0.05)) plt.boxplot(winsorizedbudget2, whis=5)
_____no_output_____
MIT
Data_cleaning_Outlier_EDA_Practice.ipynb
sgf-afk/Class_Assignments
6. Compare some basic descriptive statistics of the budget variables you end up with in the 3rd and the 4th questions. Do you see any differences?
education_df.describe()
_____no_output_____
MIT
Data_cleaning_Outlier_EDA_Practice.ipynb
sgf-afk/Class_Assignments
Developing an AI applicationGoing forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall applica...
# http://pytorch.org/ from os.path import exists from wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag platform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag()) cuda_output = !ldconfig -p|grep cudart.so|sed -e 's/.*\.\([0-9]*\)\.\([0-9]*\)$/cu\1\2/' accelerator = cuda_output[0] if exis...
_____no_output_____
MIT
Image_Classifier_Project.ipynb
Ayanlola2002/deep-learning-flower-identifier
Download the dataset
!wget -O cat_to_name.json "https://raw.githubusercontent.com/GabrielePicco/deep-learning-flower-identifier/master/cat_to_name.json" !wget "https://s3.amazonaws.com/content.udacity-data.com/courses/nd188/flower_data.zip" !unzip flower_data.zip
--2018-12-10 15:16:17-- https://raw.githubusercontent.com/GabrielePicco/deep-learning-flower-identifier/master/cat_to_name.json Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 151.101.0.133, 151.101.64.133, 151.101.128.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|151....
MIT
Image_Classifier_Project.ipynb
Ayanlola2002/deep-learning-flower-identifier
Import the test environment
!git clone https://github.com/GabrielePicco/deep-learning-flower-identifier !pip install requests !pip install airtable import sys sys.path.insert(0, 'deep-learning-flower-identifier') from test_model_pytorch_facebook_challenge import publish_evaluated_model, calc_accuracy
Cloning into 'deep-learning-flower-identifier'... remote: Enumerating objects: 31, done. remote: Counting objects: 100% (31/31), done. remote: Compressing objects: 100% (27/27), done. remote: Total 31 (delta 13), reused 18 (delta 2), pack-reused 0 Unpacking objects: 100% (31/31), done. Requirement already s...
MIT
Image_Classifier_Project.ipynb
Ayanlola2002/deep-learning-flower-identifier
Import
!pip install --no-cache-dir -I pillow # Imports here %matplotlib inline import time import os import json import copy import matplotlib.pyplot as plt import seaborn as sns import numpy as np from PIL import Image from collections import OrderedDict import torch from torch import nn, optim from torch.optim import lr_sch...
Collecting pillow [?25l Downloading https://files.pythonhosted.org/packages/62/94/5430ebaa83f91cc7a9f687ff5238e26164a779cca2ef9903232268b0a318/Pillow-5.3.0-cp36-cp36m-manylinux1_x86_64.whl (2.0MB)  100% |████████████████████████████████| 2.0MB 4.1MB/s [?25hInstalling collected packages: pillow Successfully in...
MIT
Image_Classifier_Project.ipynb
Ayanlola2002/deep-learning-flower-identifier
Load the dataHere you'll use `torchvision` to load the data ([documentation](http://pytorch.org/docs/0.3.0/torchvision/index.html)). You can [download the data here](https://s3.amazonaws.com/content.udacity-data.com/courses/nd188/flower_data.zip). The dataset is split into two parts, training and validation. For the t...
data_dir = './flower_data' train_dir = os.path.join(data_dir, 'train') valid_dir = os.path.join(data_dir, 'valid') dirs = {'train': train_dir, 'valid': valid_dir} size = 224 data_transforms = data_transforms = { 'train': transforms.Compose([ transforms.RandomRotation(45), transforms.Random...
_____no_output_____
MIT
Image_Classifier_Project.ipynb
Ayanlola2002/deep-learning-flower-identifier
Label mappingYou'll also need to load in a mapping from category label to category name. You can find this in the file `cat_to_name.json`. It's a JSON object which you can read in with the [`json` module](https://docs.python.org/2/library/json.html). This will give you a dictionary mapping the integer encoded categori...
with open('cat_to_name.json', 'r') as f: cat_to_name = json.load(f)
_____no_output_____
MIT
Image_Classifier_Project.ipynb
Ayanlola2002/deep-learning-flower-identifier
Building and training the classifierNow that the data is ready, it's time to build and train the classifier. As usual, you should use one of the pretrained models from `torchvision.models` to get the image features. Build and train a new feed-forward classifier using those features.We're going to leave this part up to...
model = models.vgg19(pretrained=True) # freeze all pretrained model parameters for param in model.parameters(): param.requires_grad_(False) print(model) classifier = nn.Sequential(OrderedDict([ ('fc1', nn.Linear(25088, 4096)), ('relu', nn.ReLU()), ...
Epoch 0/4 ---------- train Loss: 2.4615 Acc: 0.4750 valid Loss: 0.9368 Acc: 0.7445 Epoch 1/4 ---------- train Loss: 1.1086 Acc: 0.6958 valid Loss: 0.6747 Acc: 0.8093 Epoch 2/4 ---------- train Loss: 0.9610 Acc: 0.7427 valid Loss: 0.6377 Acc: 0.8289 Epoch 3/4 ---------- train Loss: 0.8783 Acc: 0.7592 valid Loss: 0.52...
MIT
Image_Classifier_Project.ipynb
Ayanlola2002/deep-learning-flower-identifier
Save the checkpointNow that your network is trained, save the model so you can load it later for making predictions. You probably want to save other things such as the mapping of classes to indices which you get from one of the image datasets: `image_datasets['train'].class_to_idx`. You can attach this to the model as...
model_file_name = 'classifier.pth' model.class_to_idx = image_datasets['train'].class_to_idx model.cpu() torch.save({'arch': 'vgg19', 'state_dict': model.state_dict(), 'class_to_idx': model.class_to_idx}, model_file_name)
_____no_output_____
MIT
Image_Classifier_Project.ipynb
Ayanlola2002/deep-learning-flower-identifier
Loading the checkpointAt this point it's good to write a function that can load a checkpoint and rebuild the model. That way you can come back to this project and keep working on it without having to retrain the network.
def load_model(checkpoint_path): chpt = torch.load(checkpoint_path) pretrained_model = getattr(models, chpt['arch']) if callable(pretrained_model): model = pretrained_model(pretrained=True) for param in model.parameters(): param.requires_grad = False else: print("Sorr...
Batch accuracy (Size 32): 0.8125 Batch accuracy (Size 32): 0.8125 Batch accuracy (Size 32): 0.78125 Batch accuracy (Size 32): 0.78125 Batch accuracy (Size 32): 0.875 Batch accuracy (Size 32): 0.9375 Batch accuracy (Size 32): 0.96875 Batch accuracy (Size 32): 0.9375 Batch accuracy (Size 32): 0.90625 Batch accuracy (Size...
MIT
Image_Classifier_Project.ipynb
Ayanlola2002/deep-learning-flower-identifier
Inference for classificationNow you'll write a function to use a trained network for inference. That is, you'll pass an image into the network and predict the class of the flower in the image. Write a function called `predict` that takes an image and a model, then returns the top $K$ most likely classes along with the...
def process_image(image_path): ''' Scales, crops, and normalizes a PIL image for a PyTorch model, returns an Numpy array ''' # Open the image from PIL import Image img = Image.open(image_path) # Resize if img.size[0] > img.size[1]: img.thumbnail((10000, 256)) else...
_____no_output_____
MIT
Image_Classifier_Project.ipynb
Ayanlola2002/deep-learning-flower-identifier
To check your work, the function below converts a PyTorch tensor and displays it in the notebook. If your `process_image` function works, running the output through this function should return the original image (except for the cropped out portions).
def imshow(image, ax=None, title=None): if ax is None: fig, ax = plt.subplots() if title: plt.title(title) # PyTorch tensors assume the color channel is first # but matplotlib assumes is the third dimension image = image.transpose((1, 2, 0)) # Undo preprocessing mean = n...
_____no_output_____
MIT
Image_Classifier_Project.ipynb
Ayanlola2002/deep-learning-flower-identifier
Class PredictionOnce you can get images in the correct format, it's time to write a function for making predictions with your model. A common practice is to predict the top 5 or so (usually called top-$K$) most probable classes. You'll want to calculate the class probabilities then find the $K$ largest values.To get t...
def predict(image_path, model, top_num=5): # Process image img = process_image(image_path) # Numpy -> Tensor image_tensor = torch.from_numpy(img).type(torch.FloatTensor) # Add batch of size 1 to image model_input = image_tensor.unsqueeze(0) image_tensor.to('cpu') model_input.to...
_____no_output_____
MIT
Image_Classifier_Project.ipynb
Ayanlola2002/deep-learning-flower-identifier
Sanity CheckingNow that you can use a trained model for predictions, check to make sure it makes sense. Even if the validation accuracy is high, it's always good to check that there aren't obvious bugs. Use `matplotlib` to plot the probabilities for the top 5 classes as a bar graph, along with the input image. It shou...
def plot_solution(image_path, model): # Set up plot plt.figure(figsize = (6,10)) ax = plt.subplot(2,1,1) # Set up title flower_num = image_path.split('/')[3] title_ = cat_to_name[flower_num] # Plot flower img = process_image(image_path) imshow(img, ax, title = title_); # Make pre...
/usr/local/lib/python3.6/dist-packages/seaborn/categorical.py:1428: FutureWarning: remove_na is deprecated and is a private function. Do not use. stat_data = remove_na(group_data)
MIT
Image_Classifier_Project.ipynb
Ayanlola2002/deep-learning-flower-identifier
Download the model Alternatively, download the file from the google colaboratory explorer menu
#files.download('classifier.pth')
_____no_output_____
MIT
Image_Classifier_Project.ipynb
Ayanlola2002/deep-learning-flower-identifier
Publish the result on the Airtable shared leaderboard
publish_evaluated_model(model, input_image_size=224, username="@Slack.Username", model_name="VGG19", optim="Adam", criteria="NLLLoss", scheduler="StepLR", epoch=5)
Downloading the dataset from: https://www.dropbox.com/s/3zmf1kq58o909rq/google_test_data.zip?dl=1
MIT
Image_Classifier_Project.ipynb
Ayanlola2002/deep-learning-flower-identifier
Some Rough
# Split the dataset by class values, returns a dictionary def separate_by_class(dataset): separated = dict() for i in range(len(dataset)): vector = dataset[i] class_value = vector[-1] if (class_value not in separated): separated[class_value] = list() separated[class_v...
_____no_output_____
MIT
course work/Problem 3/.ipynb_checkpoints/Assignment_3-checkpoint.ipynb
taareek/machine_learning
Iris
# Convert string column to float def str_column_to_float(dataset, column): for row in dataset: row[column] = float(row[column].strip()) # Convert string column to integer def str_column_to_int(dataset, column): class_values = [row[column] for row in dataset] unique = set(class_values) lookup = d...
Variance of classifier: 7.111111111111126
MIT
course work/Problem 3/.ipynb_checkpoints/Assignment_3-checkpoint.ipynb
taareek/machine_learning
The below derives fromhttps://github.com/yihui/knitr/blob/master/inst/examples/knitr-spin.RThis is a special R script which can be used to generate a report. You canwrite normal text in roxygen comments.First we set up some options (you do not have to do this):
library(knitr) opts_chunk$set(fig.path = 'figure/silk-')
_____no_output_____
MIT
tests/notebooks/mirror/script_to_ipynb/knitr-spin.ipynb
Skylion007/jupytext
The report begins here.
# boring examples as usual set.seed(123) x = rnorm(5) mean(x)
_____no_output_____
MIT
tests/notebooks/mirror/script_to_ipynb/knitr-spin.ipynb
Skylion007/jupytext
You can not use here the special syntax {{code}} to embed inline expressions, e.g.
{{mean(x) + 2}}
_____no_output_____
MIT
tests/notebooks/mirror/script_to_ipynb/knitr-spin.ipynb
Skylion007/jupytext
is the mean of x plus 2.The code itself may contain braces, but these are not checked. Thus,perfectly valid (though very strange) R code such as `{{2 + 3}} - {{4 - 5}}`can lead to errors because `2 + 3}} - {{4 - 5` will be treated as inline code.Now we continue writing the report. We can draw plots as well.
par(mar = c(4, 4, .1, .1)); plot(x)
_____no_output_____
MIT
tests/notebooks/mirror/script_to_ipynb/knitr-spin.ipynb
Skylion007/jupytext
Actually you do not have to write chunk options, in which case knitr will usedefault options. For example, the code below has no options attached:
var(x) quantile(x)
_____no_output_____
MIT
tests/notebooks/mirror/script_to_ipynb/knitr-spin.ipynb
Skylion007/jupytext
And you can also write two chunks successively like this:
sum(x^2) # chi-square distribution with df 5 sum((x - mean(x))^2) # df is 4 now
_____no_output_____
MIT
tests/notebooks/mirror/script_to_ipynb/knitr-spin.ipynb
Skylion007/jupytext
Done. Call spin('knitr-spin.R') to make silk from sow's ear now and knit alovely purse.
# /* you can write comments between /* and */ like C comments (the preceding # # is optional) Sys.sleep(60) # */ # /* there is no inline comment; you have to write block comments */
_____no_output_____
MIT
tests/notebooks/mirror/script_to_ipynb/knitr-spin.ipynb
Skylion007/jupytext
Stochastic Variational GP Regression OverviewIn this notebook, we'll give an overview of how to use SVGP stochastic variational regression ((https://arxiv.org/pdf/1411.2005.pdf)) to rapidly train using minibatches on the `3droad` UCI dataset with hundreds of thousands of training examples. This is one of the more comm...
import tqdm import math import torch import gpytorch from matplotlib import pyplot as plt # Make plots inline %matplotlib inline
_____no_output_____
MIT
examples/04_Variational_and_Approximate_GPs/SVGP_Regression_CUDA.ipynb
lrast/gpytorch
For this example notebook, we'll be using the `song` UCI dataset used in the paper. Running the next cell downloads a copy of the dataset that has already been scaled and normalized appropriately. For this notebook, we'll simply be splitting the data using the first 80% of the data as training and the last 20% as testi...
import urllib.request import os from scipy.io import loadmat from math import floor # this is for running the notebook in our testing framework smoke_test = ('CI' in os.environ) if not smoke_test and not os.path.isfile('../elevators.mat'): print('Downloading \'elevators\' UCI dataset...') urllib.request.url...
_____no_output_____
MIT
examples/04_Variational_and_Approximate_GPs/SVGP_Regression_CUDA.ipynb
lrast/gpytorch
Creating a DataLoaderThe next step is to create a torch `DataLoader` that will handle getting us random minibatches of data. This involves using the standard `TensorDataset` and `DataLoader` modules provided by PyTorch.In this notebook we'll be using a fairly large batch size of 1024 just to make optimization run fast...
from torch.utils.data import TensorDataset, DataLoader train_dataset = TensorDataset(train_x, train_y) train_loader = DataLoader(train_dataset, batch_size=1024, shuffle=True) test_dataset = TensorDataset(test_x, test_y) test_loader = DataLoader(test_dataset, batch_size=1024, shuffle=False)
_____no_output_____
MIT
examples/04_Variational_and_Approximate_GPs/SVGP_Regression_CUDA.ipynb
lrast/gpytorch
Creating a SVGP ModelFor most variational/approximate GP models, you will need to construct the following GPyTorch objects:1. A **GP Model** (`gpytorch.models.ApproximateGP`) - This handles basic variational inference.1. A **Variational distribution** (`gpytorch.variational._VariationalDistribution`) - This tells us ...
from gpytorch.models import ApproximateGP from gpytorch.variational import CholeskyVariationalDistribution from gpytorch.variational import VariationalStrategy class GPModel(ApproximateGP): def __init__(self, inducing_points): variational_distribution = CholeskyVariationalDistribution(inducing_points.size(...
_____no_output_____
MIT
examples/04_Variational_and_Approximate_GPs/SVGP_Regression_CUDA.ipynb
lrast/gpytorch
Training the ModelThe cell below trains the model above, learning both the hyperparameters of the Gaussian process **and** the parameters of the neural network in an end-to-end fashion using Type-II MLE.Unlike when using the exact GP marginal log likelihood, performing variational inference allows us to make use of st...
num_epochs = 1 if smoke_test else 4 model.train() likelihood.train() optimizer = torch.optim.Adam([ {'params': model.parameters()}, {'params': likelihood.parameters()}, ], lr=0.01) # Our loss object. We're using the VariationalELBO mll = gpytorch.mlls.VariationalELBO(likelihood, model, num_data=train_y.size...
_____no_output_____
MIT
examples/04_Variational_and_Approximate_GPs/SVGP_Regression_CUDA.ipynb
lrast/gpytorch
Making PredictionsThe next cell gets the predictive covariance for the test set (and also technically gets the predictive mean, stored in `preds.mean()`). Because the test set is substantially smaller than the training set, we don't need to make predictions in mini batches here, although this can be done by passing in...
model.eval() likelihood.eval() means = torch.tensor([0.]) with torch.no_grad(): for x_batch, y_batch in test_loader: preds = model(x_batch) means = torch.cat([means, preds.mean.cpu()]) means = means[1:] print('Test MAE: {}'.format(torch.mean(torch.abs(means - test_y.cpu()))))
Test MAE: 0.11148034781217575
MIT
examples/04_Variational_and_Approximate_GPs/SVGP_Regression_CUDA.ipynb
lrast/gpytorch
MRCA estimation -------You can access your data via the dataset number. For example, ``handle = open(get(42), 'r')``.To save data, write your data to a file, and then call ``put('filename.txt')``. The dataset will then be available in your galaxy history.Notebooks can be saved to Galaxy by clicking the large green but...
# Set history items for datasets containing accession/dates and a maximum likelihood tree: # These numbers correspond to numbers of Galaxy datasets acc_date = 1 tree = 116 !pip install --upgrade pip==20.0.2 !pip install --upgrade statsmodels==0.11.0 !pip install --upgrade pandas==0.24.2 from Bio import Phylo as phylo f...
_____no_output_____
MIT
genomics/3-MRCA/MRCA_Estimation_Notebook.ipynb
bwlang/SARS-CoV-2
MRCA timing is ...
import datetime def decimal_to_calendar (decimal): years = int (decimal) d = datetime.datetime (years, 1,1) + datetime.timedelta (days = int ((decimal-years)*365)) return d model = smf.ols(formula='distance_to_root ~ date_as_numeric ', data=df) results = model.fit() print( results.summary() ) print ("Root ...
OLS Regression Results ============================================================================== Dep. Variable: distance_to_root R-squared: 0.056 Model: OLS Adj. R-squared: 0.023 Meth...
MIT
genomics/3-MRCA/MRCA_Estimation_Notebook.ipynb
bwlang/SARS-CoV-2
**Notas para contenedor de docker:** Comando de docker para ejecución de la nota de forma local:nota: cambiar `` por la ruta de directorio que se desea mapear a `/datos` dentro del contenedor de docker.```docker run --rm -v :/datos --name jupyterlab_numerical -p 8888:8888 -d palmoreck/jupyterlab_numerical:1.1.0```passw...
!pip3 install --user -q cvxpy import os cur_directory = os.getcwd() dir_alg_python = '/algoritmos/Python' os.chdir(cur_directory + dir_alg_python) import math import numpy as np from utils_2nd_version import compute_error from algorithms_for_cieco_2nd_version import path_following_method_infeasible_init_point_2nd_ve...
_____no_output_____
Apache-2.0
temas/IV.optimizacion_convexa_y_machine_learning/4.6.Metodo_de_BL_para_puntos_iniciales_no_factibles_Python_2nd_version.ipynb
Danahirmt/analisis-numerico-computo-cientifico
Está lista la implementación para puntos iniciales no factibles en $Ax=b$ pero no para la parte de las desigualdades $f_i(x) <0 \quad \forall i=1,\dots,m$ Primer ejemplo $$ \min \quad x_1^2 + x_2^2 + x_3^2 + x_4^2 -2x_1-3x_4$$ $$\text{sujeto a: } $$ $$\begin{array}{c}2x_1 + x_2 + x_3 + 4x_4 = 7 \\x_1 + x_2 + 2x_3 + x...
from utils_2nd_version import constraint_inequalities_funcs_eval fo = lambda x: x[0]**2 + x[1]**2 + x[2]**2 + x[3]**2-2*x[0]-3*x[3] const = {0: lambda x: -x[0], 1: lambda x: -x[1], 2: lambda x: -x[2], 3: lambda x: -x[3] } A= np.array([[2,1,1,4], [1,1,2,1]]) b=np.array([7,...
_____no_output_____
Apache-2.0
temas/IV.optimizacion_convexa_y_machine_learning/4.6.Metodo_de_BL_para_puntos_iniciales_no_factibles_Python_2nd_version.ipynb
Danahirmt/analisis-numerico-computo-cientifico
Comparación con [cvxpy](https://github.com/cvxgrp/cvxpy)
import cvxpy as cp x1 = cp.Variable() x2 = cp.Variable() x3 = cp.Variable() x4 = cp.Variable() # Create two constraints. constraints = [2*x1+x2+x3+4*x4-7 == 0,x1+x2+2*x3+x4-6 == 0,x1>=0,x2>=0,x3>=0,x4>=0] # Form objective. obj = cp.Minimize(x1**2+x2**2+x3**2+x4**2-2*x1-3*x4) # Form and solve problem. prob = cp.Probl...
status: optimal optimal value 1.4006849315068515 optimal var 1.1232876712328763 0.6506849315068494 1.8287671232876717 0.5684931506849316
Apache-2.0
temas/IV.optimizacion_convexa_y_machine_learning/4.6.Metodo_de_BL_para_puntos_iniciales_no_factibles_Python_2nd_version.ipynb
Danahirmt/analisis-numerico-computo-cientifico
Segundo ejemplo $$\min 2x_1 + 5x_2$$ $$\text{sujeto a: }$$ $$\begin{array}{c}6-x_1-x_2 \leq 0 \\-18 + x_1 +2x_2 \leq 0\\x_1, x_2 \geq 0\end{array}$$
fo = lambda x: 2*x[0] + 5*x[1] const = {0: lambda x: 6-x[0]-x[1], 1: lambda x: -18+x[0]+2*x[1], 2: lambda x: -x[0], 3: lambda x: -x[1] } A=np.array([0,0],dtype=float) b = 0 x_ast = np.array([6,0], dtype=float) #x_0 = np.array([-2,-2], dtype=float) x_0 = np.array([5,0], dtype=float) #x...
_____no_output_____
Apache-2.0
temas/IV.optimizacion_convexa_y_machine_learning/4.6.Metodo_de_BL_para_puntos_iniciales_no_factibles_Python_2nd_version.ipynb
Danahirmt/analisis-numerico-computo-cientifico
Comparación con [cvxpy](https://github.com/cvxgrp/cvxpy)
x1 = cp.Variable() x2 = cp.Variable() # Create two constraints. constraints = [6-x1-x2 <= 0,-18+x1+2*x2<=0,x1>=0,x2>=0] # Form objective. obj = cp.Minimize(2*x1+5*x2) # Form and solve problem. prob = cp.Problem(obj, constraints) prob.solve() # Returns the optimal value. print("status:", prob.status) print("optim...
status: optimal optimal value 12.0000000016275 optimal var 6.000000000175689 2.552244387851183e-10
Apache-2.0
temas/IV.optimizacion_convexa_y_machine_learning/4.6.Metodo_de_BL_para_puntos_iniciales_no_factibles_Python_2nd_version.ipynb
Danahirmt/analisis-numerico-computo-cientifico
Introduction to PandasUnidata Python Workshop Overview:* **Teaching:** 30 minutes* **Exercises:** 30 minutes Questions1. What is Pandas?1. What are the basic Pandas data structures?1. How can I read data into Pandas?1. What are some of the data operations available in Pandas? Objectives1. Data Series1. Data Frames1. Lo...
from pandas import Series temperatures = Series([23, 20, 25, 18]) temperatures
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
The values on the left are the index (zero based integers by default) and on the right are the values. Notice that the data type is an integer. Any NumPy datatype is acceptable in a series.That's great, but it'd be more useful if the station were associated with those values. In fact you could say we want the values *i...
temperatures = Series([23, 20, 25, 18], index=['TOP', 'OUN', 'DAL', 'DEN']) temperatures
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
Now, very similar to a dictionary, we can use the index to access and modify elements.
temperatures['DAL'] temperatures[['DAL', 'OUN']]
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
We can also do basic filtering, math, etc.
temperatures[temperatures > 20] temperatures + 2
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
Remember how I said that series are like dictionaries? We can create a series striaght from a dictionary.
dps = {'TOP': 14, 'OUN': 18, 'DEN': 9, 'PHX': 11, 'DAL': 23} dewpoints = Series(dps) dewpoints
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
It's also easy to check and see if an index exists in a given series:
'PHX' in dewpoints 'PHX' in temperatures
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
Series have a name attribute and their index has a name attribute.
temperatures.name = 'temperature' temperatures.index.name = 'station' temperatures
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
EXERCISE: Create a series of pressures for stations TOP, OUN, DEN, and DAL (assign any values you like). Set the series name and series index name. Print the pressures for all stations which have a dewpoint below 15.
# Your code goes here
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
View Solutionpressures = Series([1012.1, 1010.6, 1008.8, 1011.2], index=['TOP', 'OUN', 'DEN', 'DAL'])pressures.name = 'pressure'pressures.index.name = 'station'print(pressures[dewpoints < 15]) Top Data FramesSeries are great, but what about a bunch of related series? Something like a table or a spreadsheet? Enter the ...
from pandas import DataFrame data = {'station': ['TOP', 'OUN', 'DEN', 'DAL'], 'temperature': [23, 20, 25, 18], 'dewpoint': [14, 18, 9, 23]} df = DataFrame(data) df
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
You can access columns (data series) using dictionary type notation or attribute type notation.
df['temperature'] df.dewpoint
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
Notice the index is shared and that the name of the column is attached as the series name.You can also create a new column and assign values. If I only pass a scalar it is duplicated.
df['wspeed'] = 0. df
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
Let's set the index to be the station.
df.index = df.station df
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
Well, that's close, but we now have a redundant column, so let's get rid of it.
df.drop('station', 1, inplace=True) df
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
Now let's get a row from the dataframe instead of a column.
df.loc['DEN']
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
We can even transpose the data easily if we needed that do make things easier to merge/munge later.
df.T
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
Look at the `values` attribute to access the data as a 1D or 2D array for series and data frames recpectively.
df.values df.temperature.values
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
EXERCISE: Add a series of rain observations to the existing data frame. Apply an instrument correction of -2 to the dewpoint observations.
# Your code goes here
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
View Solutiondf['rain'] = [0, 0.4, 0.2, 0]df.dewpoint = df.dewpoint - 2df Top Loading Data in PandasThe real power of pandas is in manupulating and summarizing large sets of tabular data. To do that, we'll need a large set of tabular data. We've included a file in this directory called `JAN17_CO_ASOS.txt` that has all...
import pandas as pd df = pd.read_table('Jan17_CO_ASOS.txt') df.head() df = pd.read_table('Jan17_CO_ASOS.txt', parse_dates=['valid']) df.head() df = pd.read_table('Jan17_CO_ASOS.txt', parse_dates=['valid'], na_values='M') df.head()
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
Let's look in detail at those column names. Turns out we need to do some cleaning of this file. Welcome to real world data analysis.
df.columns df.columns = ['station', 'time', 'temperature', 'dewpoint', 'pressure'] df.head()
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
For other formats of data CSV, fixed width, etc. that are tools to read it as well. You can even read excel files straight into Pandas. Top Missing DataWe've already dealt with some missing data by turning the 'M' string into actual NaN's while reading the file in. We can do one better though and delete any rows that ...
len(df) df.dropna(axis=0, how='all', subset=['temperature', 'dewpoint', 'pressure'], inplace=True) len(df) df.head()
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
EXERCISE: Create a new data frame called df2 that contains all data that only have temperature, dewpoint and pressure observations.
# Your code goes here # df2 =
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
View Solutiondf2 = df.dropna(how='any')df2 Lastly, we still have the original index values. Let's reindex to a new zero-based index for only the rows that have valid data in them.
df.reset_index(drop=True, inplace=True) df.head()
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
Top Manipulating DataWe can now take our data and do some intersting things with it. Let's start with a simple min/max.
print('Min: {}\nMax: {}'.format(df.temperature.min(), df.temperature.max()))
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
You can also do some useful statistics on data with attached methods like corr for correlation coefficient.
df.temperature.corr(df.dewpoint)
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
We can also call a `groupby` on the data frame to start getting some summary information for each station.
df.groupby('station').mean()
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
EXERCISE: Calculate the min, max, and standard deviation of the temperature field grouped by each station.
# Calculate min # Calculate max # Calculate standard deviation
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
View Solutionprint(df.groupby('station').min())print(df.groupby('station').max())print(df.groupby('station').std()) Now, let me show you how to do all of that and more in a single call.
df.groupby('station').describe()
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
Now let's suppose we're going to make a meteogram or similar and want to get all of the data for a single station.
df.groupby('station').get_group('0CO').head().reset_index(drop=True)
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
EXERCISE: Round the temperature column to whole degrees. Group the observations by temperaturee and use the count method to see how many instances of the rounded temperatures there are in the dataset.
# Your code goes here
_____no_output_____
MIT
notebooks/Pandas/Pandas Introduction.ipynb
jthielen/unidata-python-workshop
Generate test.txt, train.txt, validation.txt and class_weights to be used in training
%load_ext autoreload %autoreload 2 import os os.getcwd() import sys, glob, shutil os.chdir(os.path.dirname(os.getcwd())) os.getcwd()
_____no_output_____
MIT
notebooks/test_train_val-split with class_weights.ipynb
skyimager/charni
Input params
import fnmatch import numpy as np import pickle base = "data/English" datasets = ["GoodImg","BadImg"] config = {"GoodImg":{"train":0.8, "validation":0.10, "test":0.10}, "BadImg":{"train":0.8, "validation":0.10, "test":0.10} ...
GoodImg train 6140 GoodImg test 824 GoodImg validation 741 file shuffling completed for GoodImg BadImg train 3814 BadImg test 531 BadImg validation 453 file shuffling completed for BadImg
MIT
notebooks/test_train_val-split with class_weights.ipynb
skyimager/charni
Just for Checking the generated class_weights
f = open('data/English/GoodImg/GoodImg.pkl', 'rb') class_weight = pickle.load(f) class_weight[0]
_____no_output_____
MIT
notebooks/test_train_val-split with class_weights.ipynb
skyimager/charni
420-A52-SF - Algorithmes d'apprentissage supervisé - Hiver 2020 - Spécialisation technique en Intelligence ArtificielleMIT License - Copyright (c) 2020 Mikaël Swawola![Projet 2 - Solution](static/project2-banner.png)
%reload_ext autoreload %autoreload 2 %matplotlib inline
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
0 - Import des bibliothèques
from datetime import datetime from tqdm import tqdm from collections import defaultdict import numpy as np import pandas as pd from sklearn.model_selection import cross_val_score from sklearn.metrics import roc_auc_score, log_loss, f1_score, roc_curve, confusion_matrix from sklearn.preprocessing import StandardScale...
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
1 - Chargement et exploration sommaire des données
AUS = pd.read_csv('AUS_train.csv', index_col=['Date'], parse_dates=True) AUS.head() AUS = AUS.drop(columns=['Unnamed: 0']) AUS.columns
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
Date
AUS['Year'] = AUS.index.year AUS['Month'] = AUS.index.month
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
Location
AUS['Location'].unique() AUS['Location'].value_counts().plot(kind='barh') AUS = pd.get_dummies(AUS, columns = ['Location'], prefix="loc", drop_first=True) AUS.columns
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
Wind direction
AUS['WindGustDir'] = AUS['WindGustDir'].apply(lambda d : convertDir2Deg(d)) AUS['WindDir9am'] = AUS['WindDir9am'].apply(lambda d : convertDir2Deg(d)) AUS['WindDir3pm'] = AUS['WindDir3pm'].apply(lambda d : convertDir2Deg(d)) AUS['Wind1Cos'] = np.cos(AUS['WindGustDir']*2*np.pi/360) AUS['Wind1Sin'] = np.sin(AUS['WindGustD...
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
Vérification de la proportion des classes positives (Rain) et négatives (No rain)
AUS['RainTomorrow'].value_counts().plot(kind='bar') AUS['RainTomorrow'] = (AUS['RainTomorrow'] == 'Yes').astype(int) AUS['RainToday'] = (AUS['RainToday'] == 'Yes').astype(int) y = AUS[['RainTomorrow']].values.ravel() # Le ravel sert à éviter un warning tanant ... AUS = AUS.drop(columns=['RainTomorrow']) X = AUS.values...
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
3 - Sous-échantillonnage du jeu de données Puisque le jeu de données est volumineux, nous allons commencer cette étude d'apprentissage supervisé avec seulement 20 % des données
X_sub, y_sub = resample(X, y, n_samples=0.2*m, stratify=y, random_state=2020)
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
4 - Modèle de référence
clf_dummy = DummyClassifier(strategy="most_frequent").fit(X_sub, y_sub) dummy_score = log_loss(y_sub, clf_dummy.predict_proba(X_sub)[:,1]) history = {} history['Baseline'] = dummy_score history
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
5 - Régression logistique [class sklearn.linear_model.LogisticRegression(penalty='l2', dual=False, tol=0.0001, C=1.0, fit_intercept=True, intercept_scaling=1, class_weight=None, random_state=None, solver='lbfgs', max_iter=100, multi_class='auto', verbose=0, warm_start=False, n_jobs=None, l1_ratio=None)](https://scikit...
# Standardisation scaler = StandardScaler().fit(X_sub) X_sub_scale = scaler.transform(X_sub) # Grille de recherche parameters = {'C':[0.01, 0.1, 1], 'l1_ratio':[0, 0.1, 0.2, 0.3, 0.4], 'penalty': ['none', 'elasticnet']} # Modèle clf_logreg = LogisticRegression(max_iter=10000, ...
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
6 - K plus proches voisins [class sklearn.neighbors.KNeighborsClassifier(n_neighbors=5, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, n_jobs=None, **kwargs)](https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html)
# Grille de recherche parameters = {'n_neighbors':[75, 100, 125, 150], 'p':[1, 2], 'weights':['uniform', 'distance']} # Modèle clf_knn = KNeighborsClassifier() # Recherche sur grille avec validation croisée clf_knn_grid = GridSearchCV(clf_knn, parameters, cv=5, scoring="neg_log_loss", verb...
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
7 - Arbres de décision [class sklearn.tree.DecisionTreeClassifier(criterion='gini', splitter='best', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features=None, random_state=None, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, class_weight=None, p...
# Distributions des hyperparamètres distributions = dict( criterion=['gini', 'entropy'], ccp_alpha=loguniform(1e-4, 1e3), max_depth=randint(2, 128)) # Modèle clf_tree = DecisionTreeClassifier(random_state=2020) # Recherche aléatoire avec validation croisée clf_tree_rnd = RandomizedSearchCV(clf_tree, ...
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
8 - Bagging (arbres de décision) [class sklearn.ensemble.BaggingClassifier(base_estimator=None, n_estimators=10, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, oob_score=False, warm_start=False, n_jobs=None, random_state=None, verbose=0)](https://scikit-learn.org/stable/modules/generated/...
clf_bag = BaggingClassifier(base_estimator=clf_tree_rnd.best_estimator_, n_estimators=1000, verbose=1, n_jobs=-1, random_state=2020) clf_bag.fit(X_sub, y_sub) # Score de validation croisée cv_score = cross_val_score(clf_bag, X_sub, y_sub, cv=5, scoring="neg_log_loss", verbose=1, n_jobs=-1).mean() print(f'Score (mean CV...
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
9 - Forêts aléatoires [class sklearn.ensemble.RandomForestClassifier(n_estimators=100, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, bootstrap=True, oob_score=False, ...
# Grille de recherche parameters = {'ccp_alpha': [1e-3, 1e-2, 1e-1, 1], 'criterion':['gini','entropy'], 'max_features': [None, 'log2', 'sqrt']} # Modèle clf_rf = RandomForestClassifier(n_estimators=100, random_state=2020) # Recherche sur grille avec validation croisée clf_rf_grid = GridSea...
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
10 - Gradient Boosting
# Grille de recherche parameters = { 'learning_rate': [0.01, 0.1, 1], 'max_features': ['sqrt', None], 'loss': ['deviance', 'exponential'], 'ccp_alpha': [1e-5, 1e-4, 1e-3]} # Modèle clf_gb = GradientBoostingClassifier(n_estimators=100, random_state=2020) # Recherche sur grille avec validation croisée c...
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
11 - XGBoost
# Grille de recherche parameters = { 'learning_rate': [0.001, 0.01, 0.1], 'reg_alpha': [1e-4, 1e-3, 1e-2], 'reg_lambda': [1e-4, 1e-3, 1e-2]} # Modèle clf_xgb = xgb.XGBClassifier(objective='binary:logistic', colsample_bytree=0.3, max_depth=30, ...
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
12 - Courbes d'apprentissage pour le meilleur modèle XGBoost
lcurves = defaultdict(list) for p in tqdm([0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7]): X_, y_ = resample(X, y, n_samples=p*m, stratify=y, random_state=2020) Xt, Xv, yt, yv = train_test_split(X_, y_, test_size=0.3, stratify=y_, random_state=2020) clf_xgb_grid.best_estimator_.fit(Xt, y...
100%|██████████| 11/11 [00:56<00:00, 5.12s/it]
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
Affichage des courbes d'apprentissage
plt.plot(lcurves['Train'], label="Train") plt.plot(lcurves['Val'], label="Validation") plt.legend()
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
Gradient Boosting
lcurves = defaultdict(list) for p in tqdm([0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7]): X_, y_ = resample(X, y, n_samples=p*m, stratify=y, random_state=2020) Xt, Xv, yt, yv = train_test_split(X_, y_, test_size=0.3, stratify=y_, random_state=2020) clf_gb_grid.best_estimator_.fit(Xt, yt...
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
13 - Réentraînement du meilleur modèle en prenant en compte les meilleurs hyperparamètres
clf_best = GradientBoostingClassifier( n_estimators=100, ccp_alpha=0.0001, learning_rate=0.1, loss='exponential', max_features= None, random_state=2020) clf_best.fit(X, y) cv_score = cross_val_score(clf_best, X, y, cv=5, scoring="neg_log_loss", verbose=1, n_jobs=-1) cv_score.mean()
[Parallel(n_jobs=-1)]: Using backend LokyBackend with 8 concurrent workers. [Parallel(n_jobs=-1)]: Done 2 out of 5 | elapsed: 51.5s remaining: 1.3min [Parallel(n_jobs=-1)]: Done 5 out of 5 | elapsed: 1.1min finished
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
14 - Métriques Prédictions
y_train_pred_proba_best = clf_best.predict_proba(X)[:,1]
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
Aire sous la courbe
print(f'AUC = {roc_auc_score(y, y_train_pred_proba_best)}')
AUC = 0.8793425672328384
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
Courbe ROC
fpr_rf, tpr_rf, thresholds = roc_curve(y, y_train_pred_proba_best) fig = plt.figure(4, figsize=(6, 6)) plt.plot([0, 1], [0, 1], 'k--') plt.plot(fpr_rf, tpr_rf, label='Meilleur modèle') plt.xlabel('False positive rate') plt.ylabel('True positive rate') plt.title('ROC curve') plt.show()
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
Recherche du meilleur seuil
selected_threshold = thresholds[np.argmax(-fpr_rf + tpr_rf)] selected_threshold
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
F1 score
f1_score(y, y_train_pred_proba_best > selected_threshold)
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
Matrice de confusion
fig = plt.figure(3, figsize=(6, 6)) cnf_matrix = confusion_matrix(y, y_train_pred_proba_best > selected_threshold) np.set_printoptions(precision=2) plot_confusion_matrix(cnf_matrix, classes=['0','1'], title='Matrice de confusion') # Accuracy (61331+17755)/(61331+17755+15846+4604)
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
15 - Prédictions sur le jeu de test On applique les mêmes transformations que pour le jeu d'entraînement
AUS_test = pd.read_csv('AUS_test.csv', index_col=['Date'], parse_dates=True) AUS_test = AUS_test.drop(columns=['Unnamed: 0']) AUS_test['Year'] = AUS_test.index.year AUS_test['Month'] = AUS_test.index.month AUS_test = pd.get_dummies(AUS_test, columns = ['Location'], prefix="loc", drop_first=True) AUS_test['WindGustDir']...
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
Calcul des prédictions sur le jeu de test
y_test_pred_proba_best = clf_best.predict_proba(X_test)[:,1]
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final