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 |
|---|---|---|---|---|---|
Load the duplicate questions scoring app's URL. | scoring_url = aks_service.scoring_uri
api_key = aks_service.get_keys()[0] | _____no_output_____ | MIT | architectures/Python-ML-RealTimeServing/{{cookiecutter.project_name}}/aks/07_RealTimeScoring.ipynb | dciborow/AIArchitecturesAndPractices |
A constructor function for ID-text contents. Constructs buttons and text areas for each text ID and text passage.* Each buttons's description is set to a text's ID, and its click action is set to the handler.* Each text area's content is set to a text.* A dictionary is created to map IDs to text areas. | def buttons_and_texts(
data, id, answerid, text, handle_click, layout=widgets.Layout(width="100%"), n=15
):
"""Construct buttons, text areas, and a mapping from IDs to text areas."""
items = []
text_map = {}
for i in range(min(n, len(data))):
button = widgets.Button(description=data.iloc[i][... | _____no_output_____ | MIT | architectures/Python-ML-RealTimeServing/{{cookiecutter.project_name}}/aks/07_RealTimeScoring.ipynb | dciborow/AIArchitecturesAndPractices |
A constructor function for the duplicates and questions explorer widget. This builds a box containing duplicates and question tabs, each in turn containing boxes that contain the buttons and text areas. | def duplicates_questions_widget(
duplicates, questions, layout=widgets.Layout(width="100%")
):
"""Construct a duplicates and questions exploration widget."""
# Construct the duplicates Tab of buttons and text areas.
duplicates_items, duplicates_map = buttons_and_texts(
duplicates,
duplic... | _____no_output_____ | MIT | architectures/Python-ML-RealTimeServing/{{cookiecutter.project_name}}/aks/07_RealTimeScoring.ipynb | dciborow/AIArchitecturesAndPractices |
A handler function for a question passage button press. If the passage's text window is open, it is collapsed. Otherwise, it is opened. | def questions_click(button):
"""Respond to a click on a question button."""
global questions_map
if button.open:
questions_map[button.description].rows = None
button.open = False
else:
questions_map[button.description].rows = 10
button.open = True
| _____no_output_____ | MIT | architectures/Python-ML-RealTimeServing/{{cookiecutter.project_name}}/aks/07_RealTimeScoring.ipynb | dciborow/AIArchitecturesAndPractices |
A handler function for a duplicate obligation button press. If the obligation is not selected, select it and update the questions tab with its top 15 question passages ordered by match score. Otherwise, if the duplicate's text window is open, it is collapsed, else it is opened. | def duplicates_click(button):
"""Respond to a click on a duplicate button."""
global duplicates_map
if select_duplicate(button):
duplicates_map[button.description].rows = 10
button.open = True
else:
if button.open:
duplicates_map[button.description].rows = None
... | _____no_output_____ | MIT | architectures/Python-ML-RealTimeServing/{{cookiecutter.project_name}}/aks/07_RealTimeScoring.ipynb | dciborow/AIArchitecturesAndPractices |
Functions for interacting with the web service. | def score_text(text):
"""Return a data frame with the original question scores for the text."""
headers = {
"content-type": "application/json",
"Authorization": ("Bearer " + api_key),
}
# jsontext = json.dumps({'input':'{0}'.format(text)})
jsontext = text_to_json(text)
result... | _____no_output_____ | MIT | architectures/Python-ML-RealTimeServing/{{cookiecutter.project_name}}/aks/07_RealTimeScoring.ipynb | dciborow/AIArchitecturesAndPractices |
Control the appearance of cell output boxes. | %%html
<style>
.output_wrapper, .output {
height:auto !important;
max-height:1000px; /* your desired max-height here */
}
.output_scroll {
box-shadow:none !important;
webkit-box-shadow:none !important;
}
</style> | _____no_output_____ | MIT | architectures/Python-ML-RealTimeServing/{{cookiecutter.project_name}}/aks/07_RealTimeScoring.ipynb | dciborow/AIArchitecturesAndPractices |
Load dataLoad the pre-formatted text of questions. | questions_title = 'Questions'
questions_id = 'Id'
questions_answerid = 'AnswerId'
questions_text = 'Text'
questions_probability = 'Probability'
questions_path = './data_folder/questions.tsv'
questions = read_questions(questions_path, questions_id, questions_answerid) | _____no_output_____ | MIT | architectures/Python-ML-RealTimeServing/{{cookiecutter.project_name}}/aks/07_RealTimeScoring.ipynb | dciborow/AIArchitecturesAndPractices |
Load the pre-formatted text of duplicates. | duplicates_title = 'Duplicates'
duplicates_id = 'Id'
duplicates_answerid = 'AnswerId'
duplicates_text = 'Text'
duplicates_path = './data_folder/dupes_test.tsv'
duplicates = read_questions(duplicates_path, duplicates_id, duplicates_answerid) | _____no_output_____ | MIT | architectures/Python-ML-RealTimeServing/{{cookiecutter.project_name}}/aks/07_RealTimeScoring.ipynb | dciborow/AIArchitecturesAndPractices |
Explore original questions matched up with duplicate questionsDefine other variables and settings used in creating the interface. | questions_display = 15
questions_button_color = True
questions_button_score = True
score_label = 'Score'
score_scale = 100 | _____no_output_____ | MIT | architectures/Python-ML-RealTimeServing/{{cookiecutter.project_name}}/aks/07_RealTimeScoring.ipynb | dciborow/AIArchitecturesAndPractices |
This builds the exploration widget as a box containing duplicates and question tabs, each in turn containing boxes that have for each ID-text pair a button and a text area. | duplicates_map, questions_map, duplicates_questions = duplicates_questions_widget(duplicates, questions)
duplicates_questions | _____no_output_____ | MIT | architectures/Python-ML-RealTimeServing/{{cookiecutter.project_name}}/aks/07_RealTimeScoring.ipynb | dciborow/AIArchitecturesAndPractices |
Registration Initialization: We Have to Start SomewhereInitialization is a critical aspect of most registration algorithms, given that most algorithms are formulated as an iterative optimization problem.In many cases we perform initialization in an automatic manner by making assumptions with regard to the contents of ... | import SimpleITK as sitk
import os
import numpy as np
from ipywidgets import interact, fixed
from downloaddata import fetch_data as fdata
import registration_callbacks as rc
import registration_utilities as ru
# Always write output to a separate directory, we don't want to pollute the source directory.
OUTPUT_DIR =... | _____no_output_____ | Apache-2.0 | 63_Registration_Initialization.ipynb | blowekamp/SimpleITK-Notebooks |
Loading Data | data_directory = os.path.dirname(fdata("CIRS057A_MR_CT_DICOM/readme.txt"))
fixed_series_ID = "1.2.840.113619.2.290.3.3233817346.783.1399004564.515"
moving_series_ID = "1.3.12.2.1107.5.2.18.41548.30000014030519285935000000933"
reader = sitk.ImageSeriesReader()
fixed_image = sitk.ReadImage(reader.GetGDCMSeriesFileNames... | _____no_output_____ | Apache-2.0 | 63_Registration_Initialization.ipynb | blowekamp/SimpleITK-Notebooks |
Arbitrarily rotate the moving image. | rotation_x = 0.0
rotation_z = 0.0
def modify_rotation(rx_in_degrees, rz_in_degrees):
global rotation_x, rotation_z
rotation_x = np.radians(rx_in_degrees)
rotation_z = np.radians(rz_in_degrees)
interact(modify_rotation, rx_in_degrees=(0.0,180.0,5.0), rz_in_degrees=(-90.0,180.0,5.0));
resample = si... | _____no_output_____ | Apache-2.0 | 63_Registration_Initialization.ipynb | blowekamp/SimpleITK-Notebooks |
Register using standard initialization (assumes orientation is similar) | initial_transform = sitk.CenteredTransformInitializer(fixed_image,
modified_moving_image,
sitk.Euler3DTransform(),
sitk.CenteredTransformInitializerFilter.... | _____no_output_____ | Apache-2.0 | 63_Registration_Initialization.ipynb | blowekamp/SimpleITK-Notebooks |
Visually evaluate our results: | moving_resampled = sitk.Resample(modified_moving_image, fixed_image, final_transform, sitk.sitkLinear, 0.0, moving_image.GetPixelIDValue())
interact(ru.display_images_with_alpha, image_z=(0,fixed_image.GetSize()[2]), alpha=(0.0,1.0,0.05),
image1 = fixed(sitk.IntensityWindowing(fixed_image, fixed_intensity_ra... | _____no_output_____ | Apache-2.0 | 63_Registration_Initialization.ipynb | blowekamp/SimpleITK-Notebooks |
Register using heuristic initialization approach (using multiple orientations)As we want to account for significant orientation differences due to erroneous patient position (HFS...) we evaluate the similarity measure at locations corresponding to the various orientation differences. This can be done in two ways which... | # Dictionary with all the orientations we will try. We omit the identity (x=0, y=0, z=0) as we always use it. This
# set of rotations is arbitrary. For a complete grid coverage we would have 64 entries (0,pi/2,pi,1.5pi for each angle).
all_orientations = {'x=0, y=0, z=90': (0.0,0.0,np.pi/2.0),
'x=0,... | _____no_output_____ | Apache-2.0 | 63_Registration_Initialization.ipynb | blowekamp/SimpleITK-Notebooks |
Visually evaluate our results: | moving_resampled = sitk.Resample(modified_moving_image, fixed_image, final_transform, sitk.sitkLinear, 0.0, moving_image.GetPixelIDValue())
interact(ru.display_images_with_alpha, image_z=(0,fixed_image.GetSize()[2]), alpha=(0.0,1.0,0.05),
image1 = fixed(sitk.IntensityWindowing(fixed_image, fixed_intensity_ra... | _____no_output_____ | Apache-2.0 | 63_Registration_Initialization.ipynb | blowekamp/SimpleITK-Notebooks |
Exhaustive optimizerThe exhaustive optimizer evaluates the similarity measure using a grid overlaid on the parameter space.The grid is centered on the parameter values set by the SetInitialTransform, and the location of its vertices are determined by the numberOfSteps, stepLength and optimizer scales. To quote the doc... | initial_transform = sitk.CenteredTransformInitializer(fixed_image,
modified_moving_image,
sitk.Euler3DTransform(),
sitk.CenteredTransformInitializerFilter.... | _____no_output_____ | Apache-2.0 | 63_Registration_Initialization.ipynb | blowekamp/SimpleITK-Notebooks |
Visually evaluate our results: | moving_resampled = sitk.Resample(modified_moving_image, fixed_image, final_transform, sitk.sitkLinear, 0.0, moving_image.GetPixelIDValue())
interact(ru.display_images_with_alpha, image_z=(0,fixed_image.GetSize()[2]), alpha=(0.0,1.0,0.05),
image1 = fixed(sitk.IntensityWindowing(fixed_image, fixed_intensity_ra... | _____no_output_____ | Apache-2.0 | 63_Registration_Initialization.ipynb | blowekamp/SimpleITK-Notebooks |
Finetune 🤗 Transformers Models with PyTorch Lightning ⚡This notebook will use HuggingFace's `datasets` library to get data, which will be wrapped in a `LightningDataModule`. Then, we write a class to perform text classification on any dataset from the[ GLUE Benchmark](https://gluebenchmark.com/). (We just show CoLA ... | !pip install pytorch-lightning datasets transformers
from argparse import ArgumentParser
from datetime import datetime
from typing import Optional
import datasets
import numpy as np
import pytorch_lightning as pl
import torch
from torch.utils.data import DataLoader
from transformers import (
AdamW,
AutoModelFo... | _____no_output_____ | Apache-2.0 | notebooks/04-transformers-text-classification.ipynb | inzouzouwetrust/pytorch-lightning |
GLUE DataModule | class GLUEDataModule(pl.LightningDataModule):
task_text_field_map = {
'cola': ['sentence'],
'sst2': ['sentence'],
'mrpc': ['sentence1', 'sentence2'],
'qqp': ['question1', 'question2'],
'stsb': ['sentence1', 'sentence2'],
'mnli': ['premise', 'hypothesis'],
'qn... | _____no_output_____ | Apache-2.0 | notebooks/04-transformers-text-classification.ipynb | inzouzouwetrust/pytorch-lightning |
You could use this datamodule with standalone PyTorch if you wanted... | dm = GLUEDataModule('distilbert-base-uncased')
dm.prepare_data()
dm.setup('fit')
next(iter(dm.train_dataloader())) | _____no_output_____ | Apache-2.0 | notebooks/04-transformers-text-classification.ipynb | inzouzouwetrust/pytorch-lightning |
GLUE Model | class GLUETransformer(pl.LightningModule):
def __init__(
self,
model_name_or_path: str,
num_labels: int,
learning_rate: float = 2e-5,
adam_epsilon: float = 1e-8,
warmup_steps: int = 0,
weight_decay: float = 0.0,
train_batch_size: int = 32,
eval... | _____no_output_____ | Apache-2.0 | notebooks/04-transformers-text-classification.ipynb | inzouzouwetrust/pytorch-lightning |
⚡ Quick Tip - Combine arguments from your DataModule, Model, and Trainer into one for easy and robust configuration | def parse_args(args=None):
parser = ArgumentParser()
parser = pl.Trainer.add_argparse_args(parser)
parser = GLUEDataModule.add_argparse_args(parser)
parser = GLUETransformer.add_model_specific_args(parser)
parser.add_argument('--seed', type=int, default=42)
return parser.parse_args(args)
def m... | _____no_output_____ | Apache-2.0 | notebooks/04-transformers-text-classification.ipynb | inzouzouwetrust/pytorch-lightning |
Training CoLASee an interactive view of the CoLA dataset in [NLP Viewer](https://huggingface.co/nlp/viewer/?dataset=glue&config=cola) | mocked_args = """
--model_name_or_path albert-base-v2
--task_name cola
--max_epochs 3
--gpus 1""".split()
args = parse_args(mocked_args)
dm, model, trainer = main(args)
trainer.fit(model, dm) | _____no_output_____ | Apache-2.0 | notebooks/04-transformers-text-classification.ipynb | inzouzouwetrust/pytorch-lightning |
MRPCSee an interactive view of the MRPC dataset in [NLP Viewer](https://huggingface.co/nlp/viewer/?dataset=glue&config=mrpc) | mocked_args = """
--model_name_or_path distilbert-base-cased
--task_name mrpc
--max_epochs 3
--gpus 1""".split()
args = parse_args(mocked_args)
dm, model, trainer = main(args)
trainer.fit(model, dm) | _____no_output_____ | Apache-2.0 | notebooks/04-transformers-text-classification.ipynb | inzouzouwetrust/pytorch-lightning |
MNLI - The MNLI dataset is huge, so we aren't going to bother trying to train it here. - Let's just make sure our multi-dataloader logic is right by skipping over training and going straight to validation.See an interactive view of the MRPC dataset in [NLP Viewer](https://huggingface.co/nlp/viewer/?dataset=glue&config... | mocked_args = """
--model_name_or_path distilbert-base-uncased
--task_name mnli
--max_epochs 1
--gpus 1
--limit_train_batches 10
--progress_bar_refresh_rate 20""".split()
args = parse_args(mocked_args)
dm, model, trainer = main(args)
trainer.fit(model, dm) | _____no_output_____ | Apache-2.0 | notebooks/04-transformers-text-classification.ipynb | inzouzouwetrust/pytorch-lightning |
Example: View timeline | cd ..
# Imports
import instagram_api
import os
from pprint import pprint
from datetime import date
from IPython.display import Image, display
#import imageio
#imageio.plugins.ffmpeg.download()
#File saved as /home/vikash/.imageio/ffmpeg/ffmpeg-linux64-v3.3.1.
# Config
from dotenv import load_dotenv
from pathlib import... | _____no_output_____ | MIT | examples/timeline.ipynb | Vikash-Kothary/british-express-python |
Convolutional Neural Networks: ApplicationWelcome to Course 4's second assignment! In this notebook, you will:- Implement helper functions that you will use when implementing a TensorFlow model- Implement a fully functioning ConvNet using TensorFlow **After this assignment you will be able to:**- Build and train a Con... | import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import scipy
from PIL import Image
from scipy import ndimage
import tensorflow as tf
from tensorflow.python.framework import ops
from cnn_utils import *
%matplotlib inline
np.random.seed(1) | _____no_output_____ | MIT | Convolution model Application.ipynb | GUXIANFEI/Convolutional-Neural-Networks |
Run the next cell to load the "SIGNS" dataset you are going to use. | # Loading the data (signs)
X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()
X_train_orig.shape
plt.imshow(X_test_orig[1,:,:,:]) | _____no_output_____ | MIT | Convolution model Application.ipynb | GUXIANFEI/Convolutional-Neural-Networks |
As a reminder, the SIGNS dataset is a collection of 6 signs representing numbers from 0 to 5.The next cell will show you an example of a labelled image in the dataset. Feel free to change the value of `index` below and re-run to see different examples. | # Example of a picture
index = 6
plt.imshow(X_train_orig[index])
print ("y = " + str(np.squeeze(Y_train_orig[:, index]))) | y = 2
| MIT | Convolution model Application.ipynb | GUXIANFEI/Convolutional-Neural-Networks |
In Course 2, you had built a fully-connected network for this dataset. But since this is an image dataset, it is more natural to apply a ConvNet to it.To get started, let's examine the shapes of your data. | X_train = X_train_orig/255.
X_test = X_test_orig/255.
Y_train = convert_to_one_hot(Y_train_orig, 6).T
Y_test = convert_to_one_hot(Y_test_orig, 6).T
print ("number of training examples = " + str(X_train.shape[0]))
print ("number of test examples = " + str(X_test.shape[0]))
print ("X_train shape: " + str(X_train.shape))
... | number of training examples = 1080
number of test examples = 120
X_train shape: (1080, 64, 64, 3)
Y_train shape: (1080, 6)
X_test shape: (120, 64, 64, 3)
Y_test shape: (120, 6)
| MIT | Convolution model Application.ipynb | GUXIANFEI/Convolutional-Neural-Networks |
1.1 - Create placeholdersTensorFlow requires that you create placeholders for the input data that will be fed into the model when running the session.**Exercise**: Implement the function below to create placeholders for the input image X and the output Y. You should not define the number of training examples for the m... | # GRADED FUNCTION: create_placeholders
def create_placeholders(n_H0, n_W0, n_C0, n_y):
"""
Creates the placeholders for the tensorflow session.
Arguments:
n_H0 -- scalar, height of an input image
n_W0 -- scalar, width of an input image
n_C0 -- scalar, number of channels of the input
n_... | X = Tensor("Placeholder:0", shape=(?, 64, 64, 3), dtype=float32)
Y = Tensor("Placeholder_1:0", shape=(?, 6), dtype=float32)
| MIT | Convolution model Application.ipynb | GUXIANFEI/Convolutional-Neural-Networks |
**Expected Output** X = Tensor("Placeholder:0", shape=(?, 64, 64, 3), dtype=float32) Y = Tensor("Placeholder_1:0", shape=(?, 6), dtype=float32) 1.2 - Initialize parametersYou will initialize weights/filters $W1$ and $W2$ using `tf.contrib.layers.xavier_initializer(seed = 0)`. You don't need to worry about bias ... | # GRADED FUNCTION: initialize_parameters
def initialize_parameters():
"""
Initializes weight parameters to build a neural network with tensorflow. The shapes are:
W1 : [4, 4, 3, 8]
W2 : [2, 2, 8, 16]
Returns:
parameters -- a dictionary of tensors containi... | W1 = [ 0.00131723 0.14176141 -0.04434952 0.09197326 0.14984085 -0.03514394
-0.06847463 0.05245192]
W2 = [-0.08566415 0.17750949 0.11974221 0.16773748 -0.0830943 -0.08058
-0.00577033 -0.14643836 0.24162132 -0.05857408 -0.19055021 0.1345228
-0.22779644 -0.1601823 -0.16117483 -0.10286498]
| MIT | Convolution model Application.ipynb | GUXIANFEI/Convolutional-Neural-Networks |
** Expected Output:** W1 = [ 0.00131723 0.14176141 -0.04434952 0.09197326 0.14984085 -0.03514394 -0.06847463 0.05245192] W2 = [-0.08566415 0.17750949 0.11974221 0.16773748 -0.0830943 -0.08058 -0.00577033 -0.14643836 0.24162132... | # GRADED FUNCTION: forward_propagation
def forward_propagation(X, parameters):
"""
Implements the forward propagation for the model:
CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED
Arguments:
X -- input dataset placeholder, of shape (input size, number of ex... | Z3 = [[-0.44670227 -1.57208765 -1.53049231 -2.31013036 -1.29104376 0.46852064]
[-0.17601591 -1.57972014 -1.4737016 -2.61672091 -1.00810647 0.5747785 ]]
| MIT | Convolution model Application.ipynb | GUXIANFEI/Convolutional-Neural-Networks |
**Expected Output**: Z3 = [[-0.44670227 -1.57208765 -1.53049231 -2.31013036 -1.29104376 0.46852064] [-0.17601591 -1.57972014 -1.4737016 -2.61672091 -1.00810647 0.5747785 ]] 1.3 - Compute costImplement the compute cost function below. You might find these two functions helpful: - **tf.nn.sof... | # GRADED FUNCTION: compute_cost
def compute_cost(Z3, Y):
"""
Computes the cost
Arguments:
Z3 -- output of forward propagation (output of the last LINEAR unit), of shape (6, number of examples)
Y -- "true" labels vector placeholder, same shape as Z3
Returns:
cost - Tensor of the c... | cost = 2.91034
| MIT | Convolution model Application.ipynb | GUXIANFEI/Convolutional-Neural-Networks |
**Expected Output**: cost = 2.91034 1.4 Model Finally you will merge the helper functions you implemented above to build a model. You will train it on the SIGNS dataset. You have implemented `random_mini_batches()` in the Optimization programming assignment of course 2. Remember that thi... | # GRADED FUNCTION: model
def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.009,
num_epochs = 100, minibatch_size = 64, print_cost = True):
"""
Implements a three-layer ConvNet in Tensorflow:
CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED
A... | _____no_output_____ | MIT | Convolution model Application.ipynb | GUXIANFEI/Convolutional-Neural-Networks |
Run the following cell to train your model for 100 epochs. Check if your cost after epoch 0 and 5 matches our output. If not, stop the cell and go back to your code! | _, _, parameters = model(X_train, Y_train, X_test, Y_test) | Cost after epoch 0: 1.917929
Cost after epoch 5: 1.506757
Cost after epoch 10: 0.955359
Cost after epoch 15: 0.845802
Cost after epoch 20: 0.701174
Cost after epoch 25: 0.571977
Cost after epoch 30: 0.518435
Cost after epoch 35: 0.495806
Cost after epoch 40: 0.429827
Cost after epoch 45: 0.407291
Cost after epoch 50: 0... | MIT | Convolution model Application.ipynb | GUXIANFEI/Convolutional-Neural-Networks |
**Expected output**: although it may not match perfectly, your expected output should be close to ours and your cost value should decrease. **Cost after epoch 0 =** 1.917929 **Cost after epoch 5 =** 1.506757 **Train Accuracy =** 0.940741 ... | fname = "images/thumbs_up.jpg"
image = np.array(ndimage.imread(fname, flatten=False))
my_image = scipy.misc.imresize(image, size=(64,64))
plt.imshow(my_image) | _____no_output_____ | MIT | Convolution model Application.ipynb | GUXIANFEI/Convolutional-Neural-Networks |
Rebound modelAim: Quantify the environmental impact due to the savings of households in consumption expenses, across different - industrial sectors and scenarios: - housing (rent): baseline for 2011, - energy: efficient_devices, renewable_energy - food-waste: avoidable_waste_saving - clothing: sufficienc... | # model and folder settings
directory_name = 'housing' # 'housing' or 'furniture' or 'clothing' or 'energy'
iter_n=1
model_name='RF' # 'RF' or 'ANN'
## preprocessing methods
option_deseason = 'deseasonal' # 'deseasonal' [option 1] or 'month-ind' [option 2]
if option_deseason == 'month-ind':
n_ind = 63
... | _____no_output_____ | BSD-3-Clause | rebound_model.ipynb | rhythimashinde/rebound |
TODO: update the right values for energy and food industry scenarios, and then merge in the above script | if directory_name =='housing':
scenarios = {'baseline_2011':500}
target_data ='ABZ'
# target_data = 'subset-HBS'
idx_column_savings_cons = 'net_rent_and_mortgage_interest_of_principal_residence' #289
if directory_name == 'furniture':
scenarios = {'refuse_2035':17,'refuse_2050':17.4,'reuse_1_2... | _____no_output_____ | BSD-3-Clause | rebound_model.ipynb | rhythimashinde/rebound |
1. Preprocessing TOC: - 1.1. Prepare training data- 1.2. Deseasonalise- 1.3. Normalize- 1.4. Checks 1.1. Prepare training data back 1.1.1. Rename HBS columns | var_translate = pd.read_excel(seasonal_file_SI, sheet_name='translator', header=3,
usecols=['habe_code', 'habe_eng_p', 'habe_eng', 'vcode', 'qcode'])
var_translate['habe_eng'] = var_translate['habe_eng'].str.strip()
var_translate['habe_eng'] = var_translate['habe_eng'].str.replace(' ', '_... | _____no_output_____ | BSD-3-Clause | rebound_model.ipynb | rhythimashinde/rebound |
1.1.2. Inflation adjustment | df_habe_rename = pd.read_csv('preprocessing/0_habe_rename.csv')
df_new = pd.merge(df_habe_rename, df_habe_month, on='haushaltid')
pd.DataFrame.to_csv(df_new,'preprocessing/0_habe_rename_month.csv', sep=',',index=False)
list_var_total = dependent_indices_pd_name.tolist()
list_var_total.pop()
# monetary variables infla... | _____no_output_____ | BSD-3-Clause | rebound_model.ipynb | rhythimashinde/rebound |
1.1.3. Adapt the columns (optional - one hot encoding) | def new_columns(xx,directory_name):
pd_df_saved = df_inf
pd_df_saved.loc[:,'disposable_income'] = pd_df_saved['disposable_income'] - pd_df_saved.loc[:,xx]
# pd_df_saved['total_expenditures'] = pd_df_saved['total_expenditures'] - pd_df_saved.iloc[:,313]
fullname = make_pre_directory('1_habe_rename_new_c... | _____no_output_____ | BSD-3-Clause | rebound_model.ipynb | rhythimashinde/rebound |
1.1.4. Remove outliers | def remove_outliers():
df_outliers = df_habe_rename_saved # TODO if using the new definition of disposable income: use the df_habe_rename_saved
# df_outliers = df_outliers[np.abs(stats.zscore(df_outliers['disposable_income']))<10]
# df_outliers = df_outliers[np.abs(stats.zscore(df_outliers['saved_amount_(... | _____no_output_____ | BSD-3-Clause | rebound_model.ipynb | rhythimashinde/rebound |
1.2. Deasonalising - [Option 1] Clustering based on months - [Option 2] Use month and period as independent variableback 1.2.1. [Option 1] Create monthly datasets, Plots/ Tables / Statistical tests for HABE monthly data | if option_deseason == 'deseasonal' :
def split_month():
df_new = pd.read_csv('preprocessing/'+directory_name+'/2_habe_rename_removeoutliers.csv')
df_month = df_new.groupby('month_name')
for i in range(12):
df_new_month=pd.DataFrame(list(df_month)[i][1])
df_new_m... | _____no_output_____ | BSD-3-Clause | rebound_model.ipynb | rhythimashinde/rebound |
1.2.2. [Option 1] Making final clusters USER INPUT NEEDED: edit the cluster-list belowTODO - join clusters based on the p-values calculated above directly | ## current clusters are made based on the mean table above
if option_deseason == 'deseasonal' :
Cluster_month_lists = {1:('January',),2:('February','March','April'),3:('May','June','July'),
4:('August','September','October','November'),5:('December',)}
cluster_number_length = len(C... | _____no_output_____ | BSD-3-Clause | rebound_model.ipynb | rhythimashinde/rebound |
1.2.3. Option 2: Month as independent variable | if option_deseason == 'month-ind' :
cluster_number_length = 1
# do one-hot encoding for month and year
hbs_all = pd.read_csv('preprocessing/'+directory_name+'/1_habe_rename_new_columns.csv')
month_encoding = pd.get_dummies(hbs_all.month_name, prefix='month')
year_encoding = pd.get_dummies(hbs_a... | _____no_output_____ | BSD-3-Clause | rebound_model.ipynb | rhythimashinde/rebound |
1.3. Normalisation back 1.3.1. Normalisation of HBS and target data | # ## NORMALISATION
# if input_normalise == 'normalise':
# def normalise_habe(cluster):
# transformer = FunctionTransformer(np.log1p, validate=True)
# if option_deseason == 'deseasonal':
# df_deseasonal_file = pd.read_csv('preprocessing/'+directory_name+ '/' + option_deseason +... | _____no_output_____ | BSD-3-Clause | rebound_model.ipynb | rhythimashinde/rebound |
1.3.2. Preprocessing without normalisation | if input_normalise == 'no-normalise':
def normalise_habe(cluster):
transformer = FunctionTransformer(np.log1p, validate=True)
if option_deseason == 'deseasonal':
df_deseasonal_file = pd.read_csv('preprocessing/'+directory_name+ '/' + option_deseason +
... | _____no_output_____ | BSD-3-Clause | rebound_model.ipynb | rhythimashinde/rebound |
1.4. Checksback | if input_normalise =='normalise':
def truncate(cluster_number):
if option_deseason == 'deseasonal':
df_seasonal_normalised = pd.read_csv('preprocessing/'+directory_name+ '/' + option_deseason +
'/4_habe_deseasonal_'+str(cluster_number)+'_normalise... | _____no_output_____ | BSD-3-Clause | rebound_model.ipynb | rhythimashinde/rebound |
2. MODEL backTOC:- 2.1. Prepare train-test-target datasets- 2.2. Prediction 2.1. Prepare train-test-target datasets back | def to_haushalts(values,id_ix=0):
haushalts = dict()
haushalt_ids = np.unique(values[:,id_ix])
for haushalt_id in haushalt_ids:
selection = values[:, id_ix] == haushalt_id
haushalts[haushalt_id] = values[selection]
return haushalts
def split_train_test(haushalts,length_training,month_nam... | _____no_output_____ | BSD-3-Clause | rebound_model.ipynb | rhythimashinde/rebound |
2.2. Clustered Prediction back | ## NORMALISATION
if input_normalise =='normalise':
def fit_predict_cluster(i,y,cluster_number,key):
df = pd.read_csv('preprocessing/'+directory_name+'/'+option_deseason+
'/4_habe_deseasonal_'+str(cluster_number)+'_normalised.csv',
delimiter=',',error_bad_l... | _____no_output_____ | BSD-3-Clause | rebound_model.ipynb | rhythimashinde/rebound |
3.POSTPROCESSING back 3.1. Average of the clustered predictions |
if option_deseason == 'month-ind':
df_habe_outliers = pd.read_csv('preprocessing/'+directory_name+'/'+option_deseason+'/4_habe_deseasonal_'+
str(cluster_number)+ '_short.csv', delimiter=',')
if option_deseason == 'deseasonal':
df_habe_outliers = pd.read_csv('preproc... | _____no_output_____ | BSD-3-Clause | rebound_model.ipynb | rhythimashinde/rebound |
3.2. Calculate differences/ rebounds | list_dependent_columns = pd.read_csv(dependent_indices, delimiter=',', encoding='ISO-8859–1')['name'].to_list()
def difference_new():
for cluster_number in list(range(1,cluster_number_length+1)):
for key in scenarios:
list_incomechange=[0,scenarios[key]]
for i in range(0,iter_n):
... | _____no_output_____ | BSD-3-Clause | rebound_model.ipynb | rhythimashinde/rebound |
4. LCA back 1. Make a file with associated impacts_per_FU for each HABE category: - a. Get the ecoinvent data from brightway - b. Get the exiobase data from direct file (Livia's) - c. Attach the heia and Agribalyse values 2. Convert the impact_per_FU to impact_per_expenses3. Run the following scripts to ... | import pickle
import csv
file = open('LCA/contribution_scores_sectors_allfu1.pickle','rb')
x = pickle.load(file)
print(x)
with open('LCA/impacts_per_FU_sectors.csv', 'w') as output:
writer = csv.writer(output)
for key, value in x:
writer.writerow([key, value])
import pickle
import csv
import pickle
impo... | _____no_output_____ | BSD-3-Clause | rebound_model.ipynb | rhythimashinde/rebound |
 **Regressão Linear** Este notebook mostra uma implementação básica de Regressão Linear e o uso da biblioteca [MLlib](http://spark.apache.org/docs/1.4.0/api/python/pyspark.ml.html) do PySpark para a tarefa de regressão na base de dados [Million Song Dataset](http://... | from pyspark import SparkContext
sc = SparkContext.getOrCreate()
# carregar base de dados
import os.path
fileName = os.path.join('Data', 'millionsong.txt')
numPartitions = 2
rawData = sc.textFile(fileName, numPartitions)
# EXERCICIO
numPoints = rawData.count()
print (numPoints)
samplePoints = rawData.take(5)
print (sa... | OK
OK
| MIT | ATIVIDADE3/Lab02.ipynb | titocaco/BIGDATA2018 |
** (1b) Usando `LabeledPoint` ** Na MLlib, bases de dados rotuladas devem ser armazenadas usando o objeto [LabeledPoint](https://spark.apache.org/docs/latest/api/python/pyspark.mllib.htmlpyspark.mllib.regression.LabeledPoint). Escreva a função `parsePoint` que recebe como entrada uma amostra de dados, transforma os d... | from pyspark.mllib.regression import LabeledPoint
import numpy as np
# Here is a sample raw data point:
# '2001.0,0.884,0.610,0.600,0.474,0.247,0.357,0.344,0.33,0.600,0.425,0.60,0.419'
# In this raw data point, 2001.0 is the label, and the remaining values are features
# EXERCICIO
def parsePoint(line):
"""Converts... | OK
| MIT | ATIVIDADE3/Lab02.ipynb | titocaco/BIGDATA2018 |
**Visualização 1: Atributos** A próxima célula mostra uma forma de visualizar os atributos através de um mapa de calor. Nesse mapa mostramos os 50 primeiros objetos e seus atributos representados por tons de cinza, sendo o branco representando o valor 0 e o preto representando o valor 1. Esse tipo de visualização ajud... | import matplotlib.pyplot as plt
import matplotlib.cm as cm
%matplotlib inline
sampleMorePoints = rawData.take(50)
parsedSampleMorePoints = map(parsePoint, sampleMorePoints)
dataValues = list(map(lambda lp: lp.features.toArray(), parsedSampleMorePoints))
def preparePlot(xticks, yticks, figsize=(10.5, 6), hideLabels=F... | _____no_output_____ | MIT | ATIVIDADE3/Lab02.ipynb | titocaco/BIGDATA2018 |
**(1c) Deslocando os rótulos ** Para melhor visualizar as soluções obtidas, calcular o erro de predição e visualizar a relação dos atributos com os rótulos, costuma-se deslocar os rótulos para iniciarem em zero. Como primeiro passo, aplique a função `parsePoint` no RDD criado anteriormente, em seguida, crie uma RDD ap... | # EXERCICIO
parsedDataInit = rawData.map(parsePoint)
onlyLabels = parsedDataInit.map(lambda p: p.label)
minYear = onlyLabels.min()
maxYear = onlyLabels.max()
print (maxYear, minYear)
# TEST Find the range (1c)
assert len(parsedDataInit.take(1)[0].features)==12, 'unexpected number of features in sample point'
sumFeatTwo... | OK
| MIT | ATIVIDADE3/Lab02.ipynb | titocaco/BIGDATA2018 |
** (1d) Conjuntos de treino, validação e teste ** Como próximo passo, vamos dividir nossa base de dados em conjunto de treino, validação e teste conforme discutido em sala de aula. Use o método [randomSplit method](https://spark.apache.org/docs/latest/api/python/pyspark.htmlpyspark.RDD.randomSplit) com os pesos (weigh... | # EXERCICIO
weights = [.8, .1, .1]
seed = 42
parsedTrainData, parsedValData, parsedTestData = parsedData.randomSplit(weights, seed)
parsedTrainData.cache()
parsedValData.cache()
parsedTestData.cache()
nTrain = parsedTrainData.count()
nVal = parsedValData.count()
nTest = parsedTestData.count()
print (nTrain, nVal, nTes... | OK
| MIT | ATIVIDADE3/Lab02.ipynb | titocaco/BIGDATA2018 |
** Part 2: Criando o modelo de *baseline* ** **(2a) Rótulo médio ** O baseline é útil para verificarmos que nosso modelo de regressão está funcionando. Ele deve ser um modelo bem simples que qualquer algoritmo possa fazer melhor. Um baseline muito utilizado é fazer a mesma predição independente dos dados analisados u... | # EXERCICIO
averageTrainYear = (parsedTrainData
.map(lambda p: p.label)
.mean()
)
print (averageTrainYear)
# TEST Average label (2a)
assert np.allclose(averageTrainYear, 53.6792311), 'incorrect value for averageTrainYear'
print("OK") | OK
| MIT | ATIVIDADE3/Lab02.ipynb | titocaco/BIGDATA2018 |
**(2b) Erro quadrático médio ** Para comparar a performance em problemas de regressão, geralmente é utilizado o Erro Quadrático Médio ([RMSE](http://en.wikipedia.org/wiki/Root-mean-square_deviation)). Implemente uma função que calcula o RMSE a partir de um RDD de tuplas (rótulo, predição). | # EXERCICIO
def squaredError(label, prediction):
"""Calculates the the squared error for a single prediction.
Args:
label (float): The correct value for this observation.
prediction (float): The predicted value for this observation.
Returns:
float: The difference between the `label... | OK
| MIT | ATIVIDADE3/Lab02.ipynb | titocaco/BIGDATA2018 |
**(2c) RMSE do baseline para os conjuntos de treino, validação e teste ** Vamos calcular o RMSE para nossa baseline. Primeiro crie uma RDD de (rótulo, predição) para cada conjunto, e então chame a função `calcRMSE`. | # EXERCICIO
labelsAndPredsTrain = parsedTrainData.map(lambda p: (p.label, averageTrainYear))
rmseTrainBase = calcRMSE(labelsAndPredsTrain)
labelsAndPredsVal = parsedValData.map(lambda p: (p.label, averageTrainYear))
rmseValBase = calcRMSE(labelsAndPredsVal)
labelsAndPredsTest = parsedTestData.map(lambda p: (p.label, ... | OK
| MIT | ATIVIDADE3/Lab02.ipynb | titocaco/BIGDATA2018 |
** Visualização 2: Predição vs. real ** Vamos visualizar as predições no conjunto de validação. Os gráficos de dispersão abaixo plotam os pontos com a coordenada X sendo o valor predito pelo modelo e a coordenada Y o valor real do rótulo. O primeiro gráfico mostra a situação ideal, um modelo que acerta todos os rótulo... | from matplotlib.colors import ListedColormap, Normalize
from matplotlib.cm import get_cmap
cmap = get_cmap('YlOrRd')
norm = Normalize()
actual = np.asarray(parsedValData
.map(lambda lp: lp.label)
.collect())
error = np.asarray(parsedValData
.map(lambda lp: (lp... | _____no_output_____ | MIT | ATIVIDADE3/Lab02.ipynb | titocaco/BIGDATA2018 |
** Parte 3: Treinando e avaliando o modelo de regressão linear ** ** (3a) Gradiente do erro ** Vamos implementar a regressão linear através do gradiente descendente. Lembrando que para atualizar o peso da regressão linear fazemos: $$ \scriptsize \mathbf{w}_{i+1} = \mathbf{w}_i - \alpha_i \sum_j (\mathbf{w}_i^\top\mat... | from pyspark.mllib.linalg import DenseVector
# EXERCICIO
def gradientSummand(weights, lp):
"""Calculates the gradient summand for a given weight and `LabeledPoint`.
Note:
`DenseVector` behaves similarly to a `numpy.ndarray` and they can be used interchangably
within this function. For example,... | OK
| MIT | ATIVIDADE3/Lab02.ipynb | titocaco/BIGDATA2018 |
** (3b) Use os pesos para fazer a predição ** Agora, implemente a função `getLabeledPredictions` que recebe como parâmetro o conjunto de pesos e um `LabeledPoint` e retorna uma tupla (rótulo, predição). Lembre-se que podemos predizer um rótulo calculando o produto interno dos pesos com os atributos. | # EXERCICIO
def getLabeledPrediction(weights, observation):
"""Calculates predictions and returns a (label, prediction) tuple.
Note:
The labels should remain unchanged as we'll use this information to calculate prediction
error later.
Args:
weights (np.ndarray): An array with one w... | OK
| MIT | ATIVIDADE3/Lab02.ipynb | titocaco/BIGDATA2018 |
** (3c) Gradiente descendente ** Finalmente, implemente o algoritmo gradiente descendente para regressão linear e teste a função em um exemplo. | # EXERCICIO
def linregGradientDescent(trainData, numIters):
"""Calculates the weights and error for a linear regression model trained with gradient descent.
Note:
`DenseVector` behaves similarly to a `numpy.ndarray` and they can be used interchangably
within this function. For example, they bo... | OK
| MIT | ATIVIDADE3/Lab02.ipynb | titocaco/BIGDATA2018 |
** (3d) Treinando o modelo na base de dados ** Agora iremos treinar o modelo de regressão linear na nossa base de dados de treino e calcular o RMSE na base de validação. Lembrem-se que não devemos utilizar a base de teste até que o melhor parâmetro do modelo seja escolhido. Para essa tarefa vamos utilizar as funções ... | # EXERCICIO
numIters = 50
weightsLR0, errorTrainLR0 = linregGradientDescent(parsedTrainData, numIters)
labelsAndPreds = parsedValData.map(lambda lp: getLabeledPrediction(weightsLR0, lp))
rmseValLR0 = calcRMSE(labelsAndPreds)
print ('Validation RMSE:\n\tBaseline = {0:.3f}\n\tLR0 = {1:.3f}'.format(rmseValBase, rmseValL... | OK
| MIT | ATIVIDADE3/Lab02.ipynb | titocaco/BIGDATA2018 |
** Visualização 3: Erro de Treino ** Vamos verificar o comportamento do algoritmo durante as iterações. Para isso vamos plotar um gráfico em que o eixo x representa a iteração e o eixo y o log do RMSE. O primeiro gráfico mostra as primeiras 50 iterações enquanto o segundo mostra as últimas 44 iterações. Note que inici... | norm = Normalize()
clrs = cmap(np.asarray(norm(np.log(errorTrainLR0))))[:,0:3]
fig, ax = preparePlot(np.arange(0, 60, 10), np.arange(2, 6, 1))
ax.set_ylim(2, 6)
plt.scatter(list(range(0, numIters)), np.log(errorTrainLR0), s=14**2, c=clrs, edgecolors='#888888', alpha=0.75)
ax.set_xlabel('Iteration'), ax.set_ylabel(r'$\... | _____no_output_____ | MIT | ATIVIDADE3/Lab02.ipynb | titocaco/BIGDATA2018 |
** Part 4: Treino utilizando MLlib e Busca em Grade (Grid Search) ** **(4a) `LinearRegressionWithSGD` ** Nosso teste inicial já conseguiu obter um desempenho melhor que o baseline, mas vamos ver se conseguimos fazer melhor introduzindo a ordenada de origem da reta além de outros ajustes no algoritmo. MLlib [LinearRe... | from pyspark.mllib.regression import LinearRegressionWithSGD
# Values to use when training the linear regression model
numIters = 500 # iterations
alpha = 1.0 # step
miniBatchFrac = 1.0 # miniBatchFraction
reg = 1e-1 # regParam
regType = 'l2' # regType
useIntercept = True # intercept
# EXERCICIO
firstModel = Line... | OK
| MIT | ATIVIDADE3/Lab02.ipynb | titocaco/BIGDATA2018 |
**(4b) Predição** Agora use o método [LinearRegressionModel.predict()](http://spark.apache.org/docs/latest/api/python/pyspark.mllib.htmlpyspark.mllib.regression.LinearRegressionModel.predict) para fazer a predição de um objeto. Passe o atributo `features` de um `LabeledPoint` comp parâmetro. | # EXERCICIO
samplePoint = parsedTrainData.take(1)[0]
samplePrediction = firstModel.predict(samplePoint.features)
print (samplePrediction)
# TEST Predict (4b)
assert np.allclose(samplePrediction, 56.4065674104), 'incorrect value for samplePrediction'
print("OK") | OK
| MIT | ATIVIDADE3/Lab02.ipynb | titocaco/BIGDATA2018 |
** (4c) Avaliar RMSE ** Agora avalie o desempenho desse modelo no teste de validação. Use o método `predict()` para criar o RDD `labelsAndPreds` RDD, e então use a função `calcRMSE()` da Parte (2b) para calcular o RMSE. | # EXERCICIO
labelsAndPreds = parsedValData.map(lambda lp: (lp.label, firstModel.predict(lp.features)))
rmseValLR1 = calcRMSE(labelsAndPreds)
print ('Validation RMSE:\n\tBaseline = {0:.3f}\n\tLR0 = {1:.3f}\n\tLR1 = {2:.3f}'.format(rmseValBase, rmseValLR0, rmseValLR1))
# TEST Evaluate RMSE (4c)
assert np.allclose(rmseVa... | OK
| MIT | ATIVIDADE3/Lab02.ipynb | titocaco/BIGDATA2018 |
** (4d) Grid search ** Já estamos superando o baseline em pelo menos dois anos na média, vamos ver se encontramos um conjunto de parâmetros melhor. Faça um grid search para encontrar um bom parâmetro de regularização. Tente valores para `regParam` dentro do conjunto `1e-10`, `1e-5`, e `1`. | # EXERCICIO
bestRMSE = rmseValLR1
bestRegParam = reg
bestModel = firstModel
numIters = 500
alpha = 1.0
miniBatchFrac = 1.0
for reg in [1e-10, 1e-5, 1.0]:
model = LinearRegressionWithSGD.train(parsedTrainData, numIters, alpha,
miniBatchFrac, regParam=reg,
... | OK
| MIT | ATIVIDADE3/Lab02.ipynb | titocaco/BIGDATA2018 |
** Visualização 5: Predições do melhor modelo** Agora, vamos criar um gráfico para verificar o desempenho do melhor modelo. Reparem nesse gráfico que a quantidade de pontos mais escuros reduziu bastante em relação ao baseline. | predictions = np.asarray(parsedValData
.map(lambda lp: bestModel.predict(lp.features))
.collect())
actual = np.asarray(parsedValData
.map(lambda lp: lp.label)
.collect())
error = np.asarray(parsedValData
.map(la... | _____no_output_____ | MIT | ATIVIDADE3/Lab02.ipynb | titocaco/BIGDATA2018 |
** (4e) Grid Search para o valor de alfa e número de iterações ** Agora, vamos verificar diferentes valores para alfa e número de iterações para perceber o impacto desses parâmetros em nosso modelo. Especificamente tente os valores `1e-5` e `10` para `alpha` e os valores `500` e `5` para número de iterações. Avalie t... | # EXERCICIO
reg = bestRegParam
modelRMSEs = []
for alpha in [1e-5, 10]:
for numIters in [500, 5]:
model = LinearRegressionWithSGD.train(parsedTrainData, numIters, alpha,
miniBatchFrac, regParam=reg,
regType='l2', in... | OK
| MIT | ATIVIDADE3/Lab02.ipynb | titocaco/BIGDATA2018 |
Anomaly detectionAnomaly detection is a machine learning task that consists in spotting so-called outliers.“An outlier is an observation in a data set which appears to be inconsistent with the remainder of that set of data.”Johnson 1992“An outlier is an observation which deviates so much from the other observations as... | %matplotlib inline
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import matplotlib
import matplotlib.pyplot as plt | _____no_output_____ | CC0-1.0 | notebooks/22.Unsupervised_learning-anomaly_detection.ipynb | anthony-wang/scipy-2018-sklearn |
Let's first get familiar with different unsupervised anomaly detection approaches and algorithms. In order to visualise the output of the different algorithms we consider a toy data set consisting in a two-dimensional Gaussian mixture. Generating the data set | from sklearn.datasets import make_blobs
X, y = make_blobs(n_features=2, centers=3, n_samples=500,
random_state=42)
X.shape
plt.figure()
plt.scatter(X[:, 0], X[:, 1])
plt.show() | _____no_output_____ | CC0-1.0 | notebooks/22.Unsupervised_learning-anomaly_detection.ipynb | anthony-wang/scipy-2018-sklearn |
Anomaly detection with density estimation | from sklearn.neighbors.kde import KernelDensity
# Estimate density with a Gaussian kernel density estimator
kde = KernelDensity(kernel='gaussian')
kde = kde.fit(X)
kde
kde_X = kde.score_samples(X)
print(kde_X.shape) # contains the log-likelihood of the data. The smaller it is the rarer is the sample
from scipy.stats.... | _____no_output_____ | CC0-1.0 | notebooks/22.Unsupervised_learning-anomaly_detection.ipynb | anthony-wang/scipy-2018-sklearn |
now with One-Class SVM The problem of density based estimation is that they tend to become inefficient when the dimensionality of the data increase. It's the so-called curse of dimensionality that affects particularly density estimation algorithms. The one-class SVM algorithm can be used in such cases. | from sklearn.svm import OneClassSVM
nu = 0.05 # theory says it should be an upper bound of the fraction of outliers
ocsvm = OneClassSVM(kernel='rbf', gamma=0.05, nu=nu)
ocsvm.fit(X)
X_outliers = X[ocsvm.predict(X) == -1]
Z_ocsvm = ocsvm.decision_function(grid)
Z_ocsvm = Z_ocsvm.reshape(xx.shape)
plt.figure()
c_0 = pl... | _____no_output_____ | CC0-1.0 | notebooks/22.Unsupervised_learning-anomaly_detection.ipynb | anthony-wang/scipy-2018-sklearn |
Support vectors - OutliersThe so-called support vectors of the one-class SVM form the outliers | X_SV = X[ocsvm.support_]
n_SV = len(X_SV)
n_outliers = len(X_outliers)
print('{0:.2f} <= {1:.2f} <= {2:.2f}?'.format(1./n_samples*n_outliers, nu, 1./n_samples*n_SV)) | _____no_output_____ | CC0-1.0 | notebooks/22.Unsupervised_learning-anomaly_detection.ipynb | anthony-wang/scipy-2018-sklearn |
Only the support vectors are involved in the decision function of the One-Class SVM.1. Plot the level sets of the One-Class SVM decision function as we did for the true density.2. Emphasize the Support vectors. | plt.figure()
plt.contourf(xx, yy, Z_ocsvm, 10, cmap=plt.cm.Blues_r)
plt.scatter(X[:, 0], X[:, 1], s=1.)
plt.scatter(X_SV[:, 0], X_SV[:, 1], color='orange')
plt.show() | _____no_output_____ | CC0-1.0 | notebooks/22.Unsupervised_learning-anomaly_detection.ipynb | anthony-wang/scipy-2018-sklearn |
EXERCISE: **Change** the `gamma` parameter and see it's influence on the smoothness of the decision function. | # %load solutions/22_A-anomaly_ocsvm_gamma.py | _____no_output_____ | CC0-1.0 | notebooks/22.Unsupervised_learning-anomaly_detection.ipynb | anthony-wang/scipy-2018-sklearn |
Isolation ForestIsolation Forest is an anomaly detection algorithm based on trees. The algorithm builds a number of random trees and the rationale is that if a sample is isolated it should alone in a leaf after very few random splits. Isolation Forest builds a score of abnormality based the depth of the tree at which ... | from sklearn.ensemble import IsolationForest
iforest = IsolationForest(n_estimators=300, contamination=0.10)
iforest = iforest.fit(X)
Z_iforest = iforest.decision_function(grid)
Z_iforest = Z_iforest.reshape(xx.shape)
plt.figure()
c_0 = plt.contour(xx, yy, Z_iforest,
levels=[iforest.threshold_],
... | _____no_output_____ | CC0-1.0 | notebooks/22.Unsupervised_learning-anomaly_detection.ipynb | anthony-wang/scipy-2018-sklearn |
EXERCISE: Illustrate graphically the influence of the number of trees on the smoothness of the decision function? | # %load solutions/22_B-anomaly_iforest_n_trees.py | _____no_output_____ | CC0-1.0 | notebooks/22.Unsupervised_learning-anomaly_detection.ipynb | anthony-wang/scipy-2018-sklearn |
Illustration on Digits data setWe will now apply the IsolationForest algorithm to spot digits written in an unconventional way. | from sklearn.datasets import load_digits
digits = load_digits() | _____no_output_____ | CC0-1.0 | notebooks/22.Unsupervised_learning-anomaly_detection.ipynb | anthony-wang/scipy-2018-sklearn |
The digits data set consists in images (8 x 8) of digits. | images = digits.images
labels = digits.target
images.shape
i = 102
plt.figure(figsize=(2, 2))
plt.title('{0}'.format(labels[i]))
plt.axis('off')
plt.imshow(images[i], cmap=plt.cm.gray_r, interpolation='nearest')
plt.show() | _____no_output_____ | CC0-1.0 | notebooks/22.Unsupervised_learning-anomaly_detection.ipynb | anthony-wang/scipy-2018-sklearn |
To use the images as a training set we need to flatten the images. | n_samples = len(digits.images)
data = digits.images.reshape((n_samples, -1))
data.shape
X = data
y = digits.target
X.shape | _____no_output_____ | CC0-1.0 | notebooks/22.Unsupervised_learning-anomaly_detection.ipynb | anthony-wang/scipy-2018-sklearn |
Let's focus on digit 5. | X_5 = X[y == 5]
X_5.shape
fig, axes = plt.subplots(1, 5, figsize=(10, 4))
for ax, x in zip(axes, X_5[:5]):
img = x.reshape(8, 8)
ax.imshow(img, cmap=plt.cm.gray_r, interpolation='nearest')
ax.axis('off') | _____no_output_____ | CC0-1.0 | notebooks/22.Unsupervised_learning-anomaly_detection.ipynb | anthony-wang/scipy-2018-sklearn |
1. Let's use IsolationForest to find the top 5% most abnormal images.2. Let's plot them ! | from sklearn.ensemble import IsolationForest
iforest = IsolationForest(contamination=0.05)
iforest = iforest.fit(X_5) | _____no_output_____ | CC0-1.0 | notebooks/22.Unsupervised_learning-anomaly_detection.ipynb | anthony-wang/scipy-2018-sklearn |
Compute the level of "abnormality" with `iforest.decision_function`. The lower, the more abnormal. | iforest_X = iforest.decision_function(X_5)
plt.hist(iforest_X); | _____no_output_____ | CC0-1.0 | notebooks/22.Unsupervised_learning-anomaly_detection.ipynb | anthony-wang/scipy-2018-sklearn |
Let's plot the strongest inliers | X_strong_inliers = X_5[np.argsort(iforest_X)[-10:]]
fig, axes = plt.subplots(2, 5, figsize=(10, 5))
for i, ax in zip(range(len(X_strong_inliers)), axes.ravel()):
ax.imshow(X_strong_inliers[i].reshape((8, 8)),
cmap=plt.cm.gray_r, interpolation='nearest')
ax.axis('off') | _____no_output_____ | CC0-1.0 | notebooks/22.Unsupervised_learning-anomaly_detection.ipynb | anthony-wang/scipy-2018-sklearn |
Let's plot the strongest outliers | fig, axes = plt.subplots(2, 5, figsize=(10, 5))
X_outliers = X_5[iforest.predict(X_5) == -1]
for i, ax in zip(range(len(X_outliers)), axes.ravel()):
ax.imshow(X_outliers[i].reshape((8, 8)),
cmap=plt.cm.gray_r, interpolation='nearest')
ax.axis('off') | _____no_output_____ | CC0-1.0 | notebooks/22.Unsupervised_learning-anomaly_detection.ipynb | anthony-wang/scipy-2018-sklearn |
EXERCISE: Rerun the same analysis with all the other digits | # %load solutions/22_C-anomaly_digits.py | _____no_output_____ | CC0-1.0 | notebooks/22.Unsupervised_learning-anomaly_detection.ipynb | anthony-wang/scipy-2018-sklearn |
Intro to machine learning - k-means--- Scikit-learn has a nice set of unsupervised learning routines which can be used to explore clustering in the parameter space.In this notebook we will use k-means, included in Scikit-learn, to demonstrate how the different rocks occupy different regions in the available parameter ... | import pandas as pd
import numpy as np
df = pd.read_csv("../data/2016_ML_contest_training_data.csv")
df.head()
df.describe()
df = df.dropna() | _____no_output_____ | Apache-2.0 | notebooks/Intro_to_machine_learning_kmeans.ipynb | michael-scarn/geocomp-0118 |
Calculate RHOB from DeltaPHI and PHIND | def rhob(phi_rhob, Rho_matrix= 2650.0, Rho_fluid=1000.0):
"""
Rho_matrix (sandstone) : 2.65 g/cc
Rho_matrix (Limestome): 2.71 g/cc
Rho_matrix (Dolomite): 2.876 g/cc
Rho_matrix (Anyhydrite): 2.977 g/cc
Rho_matrix (Salt): 2.032 g/cc
Rho_fluid (fresh water): 1.0 g/cc (is this more mud-like?)
... | _____no_output_____ | Apache-2.0 | notebooks/Intro_to_machine_learning_kmeans.ipynb | michael-scarn/geocomp-0118 |
We can define a Python dictionary to relate facies with the integer label on the `DataFrame` | facies_dict = {1:'sandstone', 2:'c_siltstone', 3:'f_siltstone', 4:'marine_silt_shale',
5:'mudstone', 6:'wackentstone', 7:'dolomite', 8:'packstone', 9:'bafflestone'}
df["s_Facies"] = df.Facies.map(lambda x: facies_dict[x])
df.head() | _____no_output_____ | Apache-2.0 | notebooks/Intro_to_machine_learning_kmeans.ipynb | michael-scarn/geocomp-0118 |
We can easily visualize the properties of each facies and how they compare using a `PairPlot`. The library `seaborn` integrates with matplotlib to make these kind of plots easily. | import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
g = sns.PairGrid(df, hue="s_Facies", vars=['GR','RHOB','PE','ILD_log10'], size=4)
g.map_upper(plt.scatter,**dict(alpha=0.4))
g.map_lower(plt.scatter,**dict(alpha=0.4))
g.map_diag(plt.hist,**dict(bins=20))
g.add_legend()
g.set(alpha=0.5) | _____no_output_____ | Apache-2.0 | notebooks/Intro_to_machine_learning_kmeans.ipynb | michael-scarn/geocomp-0118 |
It is very clear that it's hard to separate these facies in feature space. Let's just select a couple of facies and using Pandas, select the rows in the `DataFrame` that contain information about those facies | selected = ['f_siltstone', 'bafflestone', 'wackentstone']
dfs = pd.concat(list(map(lambda x: df[df.s_Facies == x], selected)))
g = sns.PairGrid(dfs, hue="s_Facies", vars=['GR','RHOB','PE','ILD_log10'], size=4)
g.map_upper(plt.scatter,**dict(alpha=0.4))
g.map_lower(plt.scatter,**dict(alpha=0.4))
g.map_diag(plt.his... | _____no_output_____ | Apache-2.0 | notebooks/Intro_to_machine_learning_kmeans.ipynb | michael-scarn/geocomp-0118 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.