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
2.1 - TensorFlow implementationFor this assignment you will execute two implemenations, one in TensorFlow and one in PyTorch. Train and test datasets**Note:*** In the TensorFlow implementation, you will have to set the data format type to tensors, which may create ragged tensors (tensors of different lengths). * You ...
import tensorflow as tf columns_to_return = ['input_ids','attention_mask', 'start_positions', 'end_positions'] train_ds.set_format(type='tf', columns=columns_to_return) train_features = {x: train_ds[x].to_tensor(default_value=0, shape=[None, tokenizer.model_max_length]) for x in ['input_ids', 'attention_mask']} trai...
_____no_output_____
MIT
5-sequence-models/week4/QA_dataset.ipynb
alekshiidenhovi/Deep-Learning-Specialization
Training It is finally time to start training your model! * Create a custom training function using [tf.GradientTape()](https://www.tensorflow.org/api_docs/python/tf/GradientTape)* Target two loss functions, one for the start index and one for the end index. * `tf.GradientTape()` records the operations performed durin...
EPOCHS = 3 loss_fn1 = tf.keras.losses.SparseCategoricalCrossentropy( from_logits=True) loss_fn2 = tf.keras.losses.SparseCategoricalCrossentropy( from_logits=True) opt = tf.keras.optimizers.Adam(learning_rate=3e-5) losses = [] for epoch in range(EPOCHS): print("Starting epoch: %d"% epoch ) for step, (x_batch_tr...
_____no_output_____
MIT
5-sequence-models/week4/QA_dataset.ipynb
alekshiidenhovi/Deep-Learning-Specialization
Take a look at your losses and try playing around with some of the hyperparameters for better results!
from matplotlib.pyplot import plot plot(losses)
_____no_output_____
MIT
5-sequence-models/week4/QA_dataset.ipynb
alekshiidenhovi/Deep-Learning-Specialization
You have successfully trained your model to help automatically answer questions! Try asking it a question about a story.
question, text = 'What is south of the bedroom?','The hallway is south of the garden. The garden is south of the bedroom.' input_dict = tokenizer(text, question, return_tensors='tf') outputs = model(input_dict) start_logits = outputs[0] end_logits = outputs[1] all_tokens = tokenizer.convert_ids_to_tokens(input_dict["i...
_____no_output_____
MIT
5-sequence-models/week4/QA_dataset.ipynb
alekshiidenhovi/Deep-Learning-Specialization
Congratulations! You just implemented your first QA model in TensorFlow. 2.2 PyTorch implementation[PyTorch](https://pytorch.org/) is an open source machine learning framework developed by Facebook's AI Research lab that can be used for computer vision and natural language processing. As you can imagine, it is quite ...
from torch.utils.data import DataLoader columns_to_return = ['input_ids','attention_mask', 'start_positions', 'end_positions'] train_ds.set_format(type='pt', columns=columns_to_return) test_ds.set_format(type='pt', columns=columns_to_return)
_____no_output_____
MIT
5-sequence-models/week4/QA_dataset.ipynb
alekshiidenhovi/Deep-Learning-Specialization
For the accuracy metrics for the PyTorch implementation, you will change things up a bit and use the [F1 score](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html) for start and end indicies over the entire test dataset as the loss functions.
from sklearn.metrics import f1_score def compute_metrics(pred): start_labels = pred.label_ids[0] start_preds = pred.predictions[0].argmax(-1) end_labels = pred.label_ids[1] end_preds = pred.predictions[1].argmax(-1) f1_start = f1_score(start_labels, start_preds, average='macro') f1_end = f...
_____no_output_____
MIT
5-sequence-models/week4/QA_dataset.ipynb
alekshiidenhovi/Deep-Learning-Specialization
TrainingNow it is time to load a pre-trained model. **Note:** You will be using the DistilBERT instead of TFDistilBERT for a PyTorch implementation.
del model # We delete the tensorflow model to avoid memory issues from transformers import DistilBertForQuestionAnswering pytorch_model = DistilBertForQuestionAnswering.from_pretrained("model/pytorch")
_____no_output_____
MIT
5-sequence-models/week4/QA_dataset.ipynb
alekshiidenhovi/Deep-Learning-Specialization
Instead of a custom training loop, you will use the [🤗 Trainer](https://huggingface.co/transformers/main_classes/trainer.html), which contains a basic training loop and is fairly easy to implement in PyTorch.
from transformers import Trainer, TrainingArguments training_args = TrainingArguments( output_dir='results', # output directory overwrite_output_dir=True, num_train_epochs=3, # total number of training epochs per_device_train_batch_size=8, # batch size per device during training ...
_____no_output_____
MIT
5-sequence-models/week4/QA_dataset.ipynb
alekshiidenhovi/Deep-Learning-Specialization
Now it is time to ask your PyTorch model a question! * Before testing your model with a question, you can tell PyTorch to send your model and inputs to the GPU if your machine has one, or the CPU if it does not. * You can then proceed to tokenize your input and create PyTorch tensors and send them to your device. * The...
import torch device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') pytorch_model.to(device) question, text = 'What is east of the hallway?','The kitchen is east of the hallway. The garden is south of the bedroom.' input_dict = tokenizer(text, question, return_tensors='pt') input_ids =...
_____no_output_____
MIT
5-sequence-models/week4/QA_dataset.ipynb
alekshiidenhovi/Deep-Learning-Specialization
Congratulations! You've completed this notebook, and can now implement Transformer models for QA tasks!You are now able to:* Perform extractive Question Answering * Fine-tune a pre-trained transformer model to a custom dataset* Implement a QA model in TensorFlow and PyTorch What you should remember:- Transformer model...
%%javascript let element = document.getElementById('submit-notebook-button-group'); if (!element) { window._save_and_close = function(){ IPython.notebook.save_checkpoint(); IPython.notebook.session.delete(); window.onbeforeunload = null setTimeout(function() {window.close();}, 1000) ...
_____no_output_____
MIT
5-sequence-models/week4/QA_dataset.ipynb
alekshiidenhovi/Deep-Learning-Specialization
Lambda School Data Science Module 142 Sampling, Confidence Intervals, and Hypothesis Testing Prepare - examine other available hypothesis testsIf you had to pick a single hypothesis test in your toolbox, t-test would probably be the best choice - but the good news is you don't have to pick just one! Here's some of th...
import numpy as np from scipy.stats import chisquare # One-way chi square test # Chi square can take any crosstab/table and test the independence of rows/cols # The null hypothesis is that the rows/cols are independent -> low chi square # The alternative is that there is a dependence -> high chi square # Be aware! Ch...
KruskalResult(statistic=0.2727272727272734, pvalue=0.6015081344405895) KruskalResult(statistic=7.0, pvalue=0.0301973834223185)
MIT
module2-sampling-confidence-intervals-and-hypothesis-testing/LS_DS_142_Sampling_Confidence_Intervals_and_Hypothesis_Testing.ipynb
extrajp2014/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments
And there's many more! `scipy.stats` is fairly comprehensive, though there are even more available if you delve into the extended world of statistics packages. As tests get increasingly obscure and specialized, the importance of knowing them by heart becomes small - but being able to look them up and figure them out wh...
# Taking requests! Come to lecture with a topic or problem and we'll try it.
_____no_output_____
MIT
module2-sampling-confidence-intervals-and-hypothesis-testing/LS_DS_142_Sampling_Confidence_Intervals_and_Hypothesis_Testing.ipynb
extrajp2014/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments
Assignment - Build a confidence intervalA confidence interval refers to a neighborhood around some point estimate, the size of which is determined by the desired p-value. For instance, we might say that 52% of Americans prefer tacos to burritos, with a 95% confidence interval of +/- 5%.52% (0.52) is the point estimate...
# TODO - your code!
_____no_output_____
MIT
module2-sampling-confidence-intervals-and-hypothesis-testing/LS_DS_142_Sampling_Confidence_Intervals_and_Hypothesis_Testing.ipynb
extrajp2014/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments
Visit the NASA mars news site
# Visit the Mars news site url = 'https://redplanetscience.com/' browser.visit(url) # Optional delay for loading the page--wait_time browser.is_element_present_by_css('div.list_text', wait_time=1) # Convert the browser html to a soup object html = browser.html news_soup = soup(html, 'html.parser') # display the curren...
NASA-JPL's coverage of the Mars InSight landing earns one of the two wins, making this the NASA center's second Emmy.
ADSL
Instructions/.ipynb_checkpoints/Mission_to_Mars-Starter-checkpoint.ipynb
jcus/web-scraping-challenge
JPL Space Images Featured Image
# Visit URL url = 'https://spaceimages-mars.com' browser.visit(url) # Find and click the full image button image_url = browser.find_by_tag('button')[1] image_url.click() # Parse the resulting html with soup # get HTML object html = browser.html # use beautiful soup parser on HTML image_soup = soup(html, 'html.parser') ...
_____no_output_____
ADSL
Instructions/.ipynb_checkpoints/Mission_to_Mars-Starter-checkpoint.ipynb
jcus/web-scraping-challenge
Mars Facts
# Use `pd.read_html` to pull the data from the Mars-Earth Comparison section # hint use index 0 to find the table df = pd.read_html('https://galaxyfacts-mars.com/')[0] df.head() df.to_html() df df.to_html()
_____no_output_____
ADSL
Instructions/.ipynb_checkpoints/Mission_to_Mars-Starter-checkpoint.ipynb
jcus/web-scraping-challenge
Hemispheres
url = 'https://marshemispheres.com/' browser.visit(url) # Create a list to hold the images and titles. hemisphere_image_urls = [] # Get a list of all of the hemispheres links = browser.find_by_css('a.product-item img') # Next, loop through those links, click the link, find the sample anchor, return the href for i in...
_____no_output_____
ADSL
Instructions/.ipynb_checkpoints/Mission_to_Mars-Starter-checkpoint.ipynb
jcus/web-scraping-challenge
Wind statisticsFig. 3 from:>B. Moore-Maley and S. E. Allen: Wind-driven upwelling and surface nutrient delivery in a semi-enclosed coastal sea, Ocean Sci., 2022.Description:Hourly wind observations and HRDPS results for the 2015-2019 period at Sentry Shoal, Sisters Islet, Halibut Bank and Sand Heads.***
import numpy as np import xarray as xr import requests from pandas import read_csv from datetime import datetime from io import BytesIO from xml.etree import cElementTree as ElementTree from matplotlib import pyplot as plt from windrose import WindroseAxes from tqdm.notebook import tqdm %matplotlib inline plt.rcParams...
_____no_output_____
Apache-2.0
notebooks/windstatistics.ipynb
SalishSeaCast/SoG_upwelling_EOF_paper
*** Functions for loading data
def load_HRDPS(HRDPS, j, i, timerange): """Load HRDPS model results from salishsea.eos.ubc.ca/erddap """ # Extract velocities from ERDDAP and calculate wspd, wdir tslc = slice(*timerange) u, v = [HRDPS.sel(time=tslc)[var][:, j, i].values for var in ('u_wind', 'v_wind')] time = HRDPS.sel(time=ts...
_____no_output_____
Apache-2.0
notebooks/windstatistics.ipynb
SalishSeaCast/SoG_upwelling_EOF_paper
*** Load dataDefinitions
# Station attributes stations = { 'Sentry Shoal' : {'ID': 46131, 'ji': (183, 107)}, 'Sisters Islet': {'ID': 6813, 'ji': (160, 120)}, 'Halibut Bank' : {'ID': 46146, 'ji': (149, 141)}, 'Sand Heads' : {'ID': 6831, 'ji': (135, 151)}, } # Assign HRDPS as netcdf object from erddap HRDPS = xr.open_dataset...
_____no_output_____
Apache-2.0
notebooks/windstatistics.ipynb
SalishSeaCast/SoG_upwelling_EOF_paper
Load data (~15 minutes)
# Initialize lists keys, variables = ('obs', 'HRDPS'), ('time', 'wspd', 'wdir') data = {station: {key: {var: [] for var in variables} for key in keys} for station in stations} # Load DFO data and truncate to the 2015-2019 range timerange = [datetime(2015, 1, 1), datetime(2020, 1, 1)] for station in ['Halibut Bank', 'S...
_____no_output_____
Apache-2.0
notebooks/windstatistics.ipynb
SalishSeaCast/SoG_upwelling_EOF_paper
*** Plot windroses
# Make figure subplot_kw, gridspec_kw = {'axes_class': WindroseAxes}, {'wspace': 0.15, 'hspace': 0.15} fig, axs = plt.subplots(4, 4, figsize=(12, 14), subplot_kw=subplot_kw, gridspec_kw=gridspec_kw) # Loop through stations and seasons keylist, seasonlist = np.meshgrid(keys, ['Oct-Mar', 'Apr-Sep']) for row, key, season...
_____no_output_____
Apache-2.0
notebooks/windstatistics.ipynb
SalishSeaCast/SoG_upwelling_EOF_paper
Getting an Overview of Regular 3D DataIn this notebook, we're going to talk a little bit about how you might get an overview of regularized 3D data, specifically using matplotlib.In a subsequent notebook we'll address the next few steps, specifically how you might use tools like ipyvolume and yt.To start with, let's g...
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LogNorm import scipy.special
_____no_output_____
MIT
Session12/Day3/NotebookIII_part2_overview_regular_3d.ipynb
lmwalkowicz/LSSTC-DSFP-Sessions
We'll use the scipy [spherical harmonics](https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.sph_harm.html) function to make some data, but first we need a reference coordinate system. We'll start with $x, y, z$ and then transform them into spherical coordinates.**Note**: we'll be using the convention ...
N = 64 x = np.mgrid[-1.0:1.0:N*1j][:,None,None] y = np.mgrid[-1.0:1.0:N*1j][None,:,None] z = np.mgrid[-1.0:1.0:N*1j][None,None,:] r = np.sqrt(x*x + y*y + z*z) theta = np.arctan2(np.sqrt(x*x + y*y), z) phi = np.arctan2(y, x) np.abs(x - r * np.sin(theta)*np.cos(phi)).max() np.abs(y - r * np.sin(theta)*np.sin(phi)).max()...
_____no_output_____
MIT
Session12/Day3/NotebookIII_part2_overview_regular_3d.ipynb
lmwalkowicz/LSSTC-DSFP-Sessions
Now we have some data! And, we can use matplotlib to visualize it in *reduced* form. Let's try this out:
plt.imshow(data["sph_n4_m4"][:,:,N//4], norm=LogNorm()) plt.colorbar() phi.min(), phi.max() plt.imshow(data["sph_n1_m0"].max(axis=0), norm=LogNorm()) plt.colorbar()
_____no_output_____
MIT
Session12/Day3/NotebookIII_part2_overview_regular_3d.ipynb
lmwalkowicz/LSSTC-DSFP-Sessions
This is getting a bit cumbersome, though! Let's try using the [`ipywidgets`](https://ipywidgets.readthedocs.org) library to speed this up just a bit.We're going to use the `ipywidgets.interact` decorator around our function to add some inputs. This is a pretty powerful decorator, as it sets up new widgets based on th...
import ipywidgets @ipywidgets.interact(dataset = list(sorted(data.keys())), slice_position = (0, N, 1)) def make_plots(dataset, slice_position): plt.imshow(data[dataset][slice_position,:,:], norm=LogNorm()) plt.colorbar()
_____no_output_____
MIT
Session12/Day3/NotebookIII_part2_overview_regular_3d.ipynb
lmwalkowicz/LSSTC-DSFP-Sessions
We still have some artifacts here we want to get rid of; let's see if we can restrict our colorbar a bit.
print(min(_.min() for _ in data.values()), max(_.max() for _ in data.values()))
_____no_output_____
MIT
Session12/Day3/NotebookIII_part2_overview_regular_3d.ipynb
lmwalkowicz/LSSTC-DSFP-Sessions
Typically in these cases, the more interesting values are the ones at the top -- the bottom are usually falling off rather quickly to zero. So let's set our maximum, and then drop 5 orders of magnitude for the minimum. I'm changing the colorbar's "extend" value to reflect this.
@ipywidgets.interact(dataset = list(sorted(data.keys())), slice_position = (0, N, 1)) def make_plots(dataset, slice_position): plt.imshow(data[dataset][slice_position,:,:], norm=LogNorm(vmin=1e-5, vmax=1.0)) plt.colorbar(extend = 'min')
_____no_output_____
MIT
Session12/Day3/NotebookIII_part2_overview_regular_3d.ipynb
lmwalkowicz/LSSTC-DSFP-Sessions
We're going to do one more thing for getting an overview, and then we'll see if we can do some other, cooler things with it using plotly.We're going to change our `slice_position` to be in units of actual coordinates, instead of integers, and we'll add on a multiplot so we can see all three at once.
@ipywidgets.interact(dataset = list(sorted(data.keys())), x = (-1.0, 1.0, 2.0/N), y = (-1.0, 1.0, 2.0/N), z = (-1.0, 1.0, 2.0/N)) def make_plots(dataset, x, y, z): xi, yi, zi = (int(_*N + 1.0) for _ in (x, y, z)) fig, axes = plt.subplots(nrows=2, ncols=2, dpi = 200) datax = data[dataset][xi,:,:] datay =...
_____no_output_____
MIT
Session12/Day3/NotebookIII_part2_overview_regular_3d.ipynb
lmwalkowicz/LSSTC-DSFP-Sessions
One thing I've run into with plotly while making this notebook has been that in many cases, the 3D plots strain a bit under large data sizes. This is to be expected, and is completely understandable! One of the really nice things about regular mesh data like this is that you can usually cut it down quite effectively ...
plt.imshow(data["sph_n4_m3"].sum(axis=0), extent=[-1.0, 1.0, -1.0, 1.0])
_____no_output_____
MIT
Session12/Day3/NotebookIII_part2_overview_regular_3d.ipynb
lmwalkowicz/LSSTC-DSFP-Sessions
* Creating one graph per group
machine_number = len(data.index.values) print(machine_number) color = ['indianred', 'darkolivegreen','steelblue', 'saddlebrown'] init_list = [0,15,30,45] for i in range(1,5): # 1 to 4 target = 15 * i if init_list[i-1] < machine_number: fig, axs = plt.subplots(figsize = [15,10] ) x = machines[in...
_____no_output_____
MIT
notebooks/5_scrap_per_machine.ipynb
SanTaroZ/production-_analysis
Read parsed, and splitted data:
import os execfile("../script/utils.py") eventsPath = os.environ["YAHOO_DATA"] splitedRdd = sc.textFile(eventsPath + "/splitedData") splitedRdd = splitedRdd.map(parseContextData2) a = splitedRdd.take(1) len(a[0][1][0]) + len(a[0][1][1]) #80% training and #20%test data already separated a number = 5 splitedRdd.filter(la...
_____no_output_____
BSD-2-Clause
notebooks/ParseEventData.ipynb
rubattino/apprecsys
Part 6: Build an Encrypted, Decentralized DatabaseIn the last section (Part 5), we learned about the basic tools PySyft supports for encrypted computation. In this section, we're going to give one example of how to use those tools to build an encrypted, decentralized database. EncryptedThe database will be encrypted ...
import syft as sy hook = sy.TorchHook() bob = sy.VirtualWorker(id="bob") alice = sy.VirtualWorker(id="alice") bill = sy.VirtualWorker(id="bill")
_____no_output_____
Apache-2.0
examples/tutorials/Part 6 - Build an Encrypted, Decentralized Database.ipynb
andreas-hjortgaard/PySyft
Section 1: Constructing a Key SystemIn this section, we're going to show how to use the equality operation to build a simple key system. The only tricky part about this is that we need to choose the datatype we want to use for keys. The most common usecase is probably strings, so that's what we're going to use here.No...
# Note that sy.mpc.securenn.field is the max value that we can encode using SMPC by default # This is, however, somewhat configurable in the system. def string2key(input_str): return sy.LongTensor([hash(input_str) % sy.mpc.securenn.field]) string2key("hello") string2key("world")
_____no_output_____
Apache-2.0
examples/tutorials/Part 6 - Build an Encrypted, Decentralized Database.ipynb
andreas-hjortgaard/PySyft
Section 2: Constructing a Value Storage SystemNow, we are able to convert our string "keys" to integers which we can use for our database, but now we need to figure out how to encode the values in our database using numbers as well. For this, we're going to simply encode each string as a list of numbers like so.
import string string.punctuation import string char2int = {} int2char = {} for i, c in enumerate(' ' + string.ascii_letters + '0123456789' + string.punctuation): char2int[c] = i int2char[i] = c def string2values(input_str): values = list() for char in input_str: values.append(char2int[char]) ...
_____no_output_____
Apache-2.0
examples/tutorials/Part 6 - Build an Encrypted, Decentralized Database.ipynb
andreas-hjortgaard/PySyft
Section 3: Creating the Tensor Based Key-Value StoreNow for our next operation, we want to write some logic which will allow us to query this database using ONLY addition, multiplication, and comparison operations. For this we will use a simple strategy. The database will be a list of integer keys and a list of intege...
keys = list() values = list()
_____no_output_____
Apache-2.0
examples/tutorials/Part 6 - Build an Encrypted, Decentralized Database.ipynb
andreas-hjortgaard/PySyft
To add a value to the database, we'll just add its key and value to the lists.
def add_entry(string_key, string_value): keys.append(string2key(string_key)) values.append(string2values(string_value)) add_entry("Bob","(123) 456-7890") add_entry("Bill", "(234) 567-8901") add_entry("Sue","(345) 678-9012") keys values
_____no_output_____
Apache-2.0
examples/tutorials/Part 6 - Build an Encrypted, Decentralized Database.ipynb
andreas-hjortgaard/PySyft
Section 4: Querying the Key->Value StoreOur query will be in three:- 1) check for equality between the query key and every key in the database - returning a 1 or 0 for each row. We'll call each row's result it's "key_match" integer.- 2) Multiply each row's "key_match" integer by all the values in its corresponding row...
# this is our query query = "Bob" # convert our query to a hash qhash = string2key(query) qhash[0] # see if our query matches any key key_match = list() for key in keys: key_match.append((key == qhash).long()) key_match # Multiply each row's value by its corresponding keymatch value_match = list() for i, value in ...
_____no_output_____
Apache-2.0
examples/tutorials/Part 6 - Build an Encrypted, Decentralized Database.ipynb
andreas-hjortgaard/PySyft
Section 5: Putting It TogetherHere's what this logic looks like when put together in a simple database class.
import string char2int = {} int2char = {} for i, c in enumerate(' ' + string.ascii_letters + '0123456789' + string.punctuation): char2int[c] = i int2char[i] = c def string2key(input_str): return sy.LongTensor([hash(input_str) % sy.mpc.securenn.field]) def string2values(input_str): values = list() ...
_____no_output_____
Apache-2.0
examples/tutorials/Part 6 - Build an Encrypted, Decentralized Database.ipynb
andreas-hjortgaard/PySyft
Section 6: Building an Encrypted, Decentralized DatabaseNow, the interesting thing here is that we have not used a single operation other than addition, multiplication, and comparison (equality). Thus, we can trivially create an encrypted database by simply encrypting all of our keys and values!
import string char2int = {} int2char = {} for i, c in enumerate(' ' + string.ascii_letters + '0123456789' + string.punctuation): char2int[c] = i int2char[i] = c def string2key(input_str): return sy.LongTensor([(hash(input_str)+1234) % int(sy.mpc.securenn.field)]) def string2values(input_str): values...
_____no_output_____
Apache-2.0
examples/tutorials/Part 6 - Build an Encrypted, Decentralized Database.ipynb
andreas-hjortgaard/PySyft
Success!!!And there you have it! We now have a key-value store capable of storing arbitrary strings and values in an encrypted, decentralized state such that even the queries are also private/encrypted. Section 7: Increasing Performance Strategy 1: One-hot Encoded KeysAs it turns out, comparisons (like ==) can be ver...
import string char2int = {} int2char = {} for i, c in enumerate(' ' + string.ascii_lowercase + '0123456789' + string.punctuation): char2int[c] = i int2char[i] = c def one_hot(index, length): vect = sy.zeros(length).long() vect[index] = 1 return vect def string2one_hot_matrix(str_input, max_...
_____no_output_____
Apache-2.0
examples/tutorials/Part 6 - Build an Encrypted, Decentralized Database.ipynb
andreas-hjortgaard/PySyft
Success!!And there we have it - a marginally more performant version. We could further add performance by running the query on all the rows in parallel, but we'll leave that for someone else to work on :).Note: we can add as many owners to the database as we want! (although the more owners you have the slower queries ...
import syft as sy hook = sy.TorchHook() bob = sy.VirtualWorker(id="bob") alice = sy.VirtualWorker(id="alice") bill = sy.VirtualWorker(id="bill") sue = sy.VirtualWorker(id="sue") tara = sy.VirtualWorker(id="tara") db = DecentralizedDB(bob, alice, bill, sue, tara, max_key_len=3) db.add_entry("Bob","(123) 456 7890") db...
_____no_output_____
Apache-2.0
examples/tutorials/Part 6 - Build an Encrypted, Decentralized Database.ipynb
andreas-hjortgaard/PySyft
_by Max Schröder$^{1,2}$ and Frank Krüger$^1$_$^1$ Institute of Communications Engineering, University of Rostock, Rostock $^2$ University Library, University of Rostock, Rostock **Abstract**:This introduction to the Python programming language is based on [this NLP course program](https://github.com/stefanluedtke/N...
x = 34 - 23 # A comment. y = "Hello" # Another one. z = 3.45 if z == 3.45 or y == "Hello": x = x + 1 y = y + " World" print(x) print(y)
_____no_output_____
CC-BY-4.0
02 Python Introduction.ipynb
m6121/Jupyter-Workshop
IndentationPython handles blocks in a different way than other programming languages you might know, like Java or C: The first line with less indentation is outside of the block, the first line with more indentation starts a nested block. A colon often starts a new block. For example, in the code below, the fourth lin...
if 17<16: print("executed conditionally") print("also conditionally") print("always executed, because not part of the block above")
_____no_output_____
CC-BY-4.0
02 Python Introduction.ipynb
m6121/Jupyter-Workshop
Reference SemanticsAssignments behave as you might know from Java: For atomic data types, assignments work "by value", for all other data types (e.g. lists), assignments work "by reference": If we manipulate an object, this influences all references.
a=17 b=a #assign the *value* of a to b a=12 print(b) #still 17, because assinment by value x=[1,2,3] #this is what lists look like y=x #assign reference to the list to y x.append(4) #manipulate the list by adding a value print(y) #y also changed, because of assingment by reference
_____no_output_____
CC-BY-4.0
02 Python Introduction.ipynb
m6121/Jupyter-Workshop
ListsLists are written in square brackets, as you have seen above. Lists can contain values of mixed types. List indices start with 0, as you can see here:
li = [17,"Hello",4.1,"Bar",5,6] li[2]
_____no_output_____
CC-BY-4.0
02 Python Introduction.ipynb
m6121/Jupyter-Workshop
You can also use negative indices, which means that we start counting from the right:
li[-2]
_____no_output_____
CC-BY-4.0
02 Python Introduction.ipynb
m6121/Jupyter-Workshop
You can also select subsets of lists ("slicing"), like this:
li[-4:-2]
_____no_output_____
CC-BY-4.0
02 Python Introduction.ipynb
m6121/Jupyter-Workshop
Note that slicing returns a copy of the sub-list. Some more list operatorsHere are some more operators you might find useful.
# Boolean test whether a value is in a list: the in operator t = [1,2,3,4] 2 in t # Concatenate lists: the + operator a = [1,2,3,4] b = [5,6,7] c = a + b c # Repeat a list n times: the * operator a=[1,2,3] 3*a # Append lists a=[1,2,3] a.append(4) # Index of first occurence a.index(2) # Number of occurences a = [1...
_____no_output_____
CC-BY-4.0
02 Python Introduction.ipynb
m6121/Jupyter-Workshop
Dictionaries: A mapping typeDictionaries are known as maps in other languages: They store a mapping between a set of keys and a set of values. Below is an example on how to use dictionaries:
# Create a new dictionary d = {'user':'bozo', 'pswd':1234} # Access the values via a key d['user'] d['pswd'] # Add key-value pairs d['id']=17 # List of keys d.keys() # List of values d.values()
_____no_output_____
CC-BY-4.0
02 Python Introduction.ipynb
m6121/Jupyter-Workshop
FunctionsFunctions in Python work as you would expect: Arguments to functions are passed by assignment, that means passed arguments are assigned to local names. Assignments to arguments cannot affect the caller, but changing mutable arguments might. Here is an example of defining and calling a function:
def myfun(x,y): print("The function is executed.") y[0]=8 # This changes the list that y points to return(y[1]+x) mylist = [1,2,3] result=myfun(17,mylist) print("Function returned: ",result) print("List is now: ",mylist)
_____no_output_____
CC-BY-4.0
02 Python Introduction.ipynb
m6121/Jupyter-Workshop
Optional ArgumentsWe can define defaults for arguments that do not need to be passed:
def func(a, b, c=10, d=100): print(a, b, c, d) func(1,2) func(1,2,3,4)
_____no_output_____
CC-BY-4.0
02 Python Introduction.ipynb
m6121/Jupyter-Workshop
Some more facts about functions:* All functions in Python have a return value, functions without a return statement have the special return value None* There is no function overloading in Python* Functions can be used as any other data types: They can be arguments to functions, return values of functions, assigned to v...
x = 3 while x < 10: if x > 7: x += 2 continue x = x + 1 print("Still in the loop.") if x == 8: break print("Outside of the loop.") for x in [0,1,2,3,4,5,6,7,8,9]: if x > 7: x += 2 continue x = x + 1 print("Still in the loop.") if x == 8: br...
_____no_output_____
CC-BY-4.0
02 Python Introduction.ipynb
m6121/Jupyter-Workshop
**Task 2:** Implement a function that tests whether a given number is prime.
for i in range(-1, 15): print('%i is %s' % (i, is_prime(i)))
_____no_output_____
CC-BY-4.0
02 Python Introduction.ipynb
m6121/Jupyter-Workshop
List ComprehensionsThere is a special syntax for list comprehensions (which you might know from Haskell).
# List of all multiples of 3 that are <100: evens = [x for x in range(3,100) if x%3==0] print(evens)
_____no_output_____
CC-BY-4.0
02 Python Introduction.ipynb
m6121/Jupyter-Workshop
**Task 3:** Use a list comprehension to make a list of all primes < 1000. Importing Modules/PackagesIn order to work with numeric arrays, we import the [NumPy](http://www.numpy.org) package.Numpy is a very popular Python package that allows to work more easily with numeric arrays. It is the basis for much of what you ...
import numpy as np
_____no_output_____
CC-BY-4.0
02 Python Introduction.ipynb
m6121/Jupyter-Workshop
Now we can use all NumPy functions (by prefixing "`np.`").
np.zeros(10000)
_____no_output_____
CC-BY-4.0
02 Python Introduction.ipynb
m6121/Jupyter-Workshop
Tab Completion**Task 4:** Type "`np.ze`" (without the quotes) and then hit the *Tab* key ... Getting HelpIf you want to know details about the usage of `np.zeros()` and all its supported arguments, have a look at its help text.Just append a question mark to the function name (without parentheses!):
np.arange?
_____no_output_____
CC-BY-4.0
02 Python Introduction.ipynb
m6121/Jupyter-Workshop
A help window should open in the lower part of the browser window.This window can be closed by hitting the *q* key (like "quit").You can also get help for the whole NumPy package:
np?
_____no_output_____
CC-BY-4.0
02 Python Introduction.ipynb
m6121/Jupyter-Workshop
You can get help for any object by appending (or prepending) a question mark to the name of the object.Let's check what the help system can tell us about our variable `a`:
a?
_____no_output_____
CC-BY-4.0
02 Python Introduction.ipynb
m6121/Jupyter-Workshop
Useful Jupyter Notebook CommandsIn addition to the general python programming, there are some very useful Jupyter Notebook specific commands starting with '%'.Let's first look at the variables, we have already defined including their type and the current value by the following command:
%whos
_____no_output_____
CC-BY-4.0
02 Python Introduction.ipynb
m6121/Jupyter-Workshop
Other commands for timing python expressions might also be helpful, e.g. `%time` and `%timeit`**%%time in first line of cell for timing the entire cell, %time before comment for a single line**
%time?
_____no_output_____
CC-BY-4.0
02 Python Introduction.ipynb
m6121/Jupyter-Workshop
Query and explore data included in WALIS This notebook contains scripts that allow querying and extracting data from the "World Atlas of Last Interglacial Shorelines" (WALIS) database. The notebook calls scripts contained in the /scripts folder. After downloading the database (internet connection required), field head...
#Main packages import pandas as pd import pandas.io.sql as psql import geopandas import pygeos import numpy as np import mysql.connector from datetime import date import xlsxwriter as writer import math from scipy import optimize from scipy import stats #Plots import seaborn as sns import matplotlib.pyplot as plt from...
_____no_output_____
MIT
Code/Query_and_Explore_data.ipynb
Alerovere/WALIS
Import databaseConnect to the online MySQL database containing WALIS data and download data into a series of pandas data frames.
## Connect to the WALIS database server %run -i scripts/connection.py ## Import data tables and show progress bar with tqdm_notebook(total=len(SQLtables),desc='Importing tables from WALIS') as pbar: for i in range(len(SQLtables)): query = "SELECT * FROM {}".format(SQLtables[i]) walis_dict[i] = psql.read_sql(qu...
_____no_output_____
MIT
Code/Query_and_Explore_data.ipynb
Alerovere/WALIS
Query the databaseNow, the data is ready to be queried according to a user input. There are two ways to extact data of interest from WALIS. Run either one and proceed.1. [Select by author](Query-option-1---Select-by-author)2. [Select by geographic coordinates](Query-option-2---Select-by-geographic-extent) Query optio...
%run -i scripts/select_user.py multiUsr
_____no_output_____
MIT
Code/Query_and_Explore_data.ipynb
Alerovere/WALIS
Once the selection is done, run the following cell to query the database and extract only the data inserted by the selected user(s)
%run -i scripts/multi_author_query.py
Extracting values for: WALIS Admin The database you are exporting contains: 4006 RSL datapoints from stratigraphy 463 RSL datapoints from single corals 76 RSL datapoints from single speleothems 30 RSL indicators 19 Elevation measurement techniques 11 Geographic positioning techniques 28 Sea level datums 2717 U-Series ...
MIT
Code/Query_and_Explore_data.ipynb
Alerovere/WALIS
Query option 2 - Select by geographic extentThis option allows the download of data by geographic extent, defined as maximum-minimum bounds on Latitude and Longitude. Use this website to quickly find bounding coordinates: http://bboxfinder.com.
# bounding box coordinates in decimal degrees (x=Lon, y=Lat) xmin=-69.292145 xmax=-68.616486 ymin=12.009771 ymax=12.435235 # Curacao: -69.292145,12.009771,-68.616486,12.435235 #2.103882,39.219487,3.630981,39.993956 # From the dictionary in connection.py, extract the dataframes %run -i scripts/geoextent_query.py
Extracting values for the coordinates you specified The database you are exporting contains: 11 RSL datapoints from stratigraphy 15 RSL datapoints from single corals 0 RSL datapoints from single speleothems 2 RSL indicators 3 Elevation measurement techniques 3 Geographic positioning techniques 4 Sea level datums 30 U-S...
MIT
Code/Query_and_Explore_data.ipynb
Alerovere/WALIS
Substitute data codes The following code makes joins between the data, substituting numerical or comma-separated codes with the corresponding text values.**WARNING - MODIFICATIONS TO THE ORIGINAL DATA**The following adjustments to the data are made:1. If there is an age in ka, but the uncertainty field is empty, the a...
%run -i scripts/substitutions.py %run -i scripts/make_summary.py
We are substituting values in your dataframes.... querying by user Putting nice names to the database columns.... Done!! making summary table.... Done!
MIT
Code/Query_and_Explore_data.ipynb
Alerovere/WALIS
Write outputThe following scripts save the data in Xlsx, CSV, and geoJSON format (for use in GIS software).
%run -i scripts/write_spreadsheets.py %run -i scripts/write_geojson.py print ('Done!')
Your file will be created in /Users/alessiorovere/Dropbox/Mac/Documents/GitHub/WALIS/Code/Output/Data/ Done!
MIT
Code/Query_and_Explore_data.ipynb
Alerovere/WALIS
Explore queried data through graphsThe following scrips produce a series of images representing different aspects of the data included in the database. Each graph is saved in the "Output/Images" folder in svg format.The following graphs can be plotted:1. [Monthly data insertion/update](Monthly-data-insertion/update)2....
%run -i scripts/Database_contributions.py
_____no_output_____
MIT
Code/Query_and_Explore_data.ipynb
Alerovere/WALIS
References by year of publicationThis graph shows the year of publication of the manuscripts included in the WALIS "References" table. Note that these might not all be used in further data compilations.
References_query=References_query[References_query['Year'] != 0] #to eliminate works that are marked as "in prep" from the graph %run -i scripts/References_hist.py
_____no_output_____
MIT
Code/Query_and_Explore_data.ipynb
Alerovere/WALIS
Elevation errorsThese two graphs show the measured elevation errors (plotted as Kernel Density Estimate) reported for sea-level data within WALIS. These include "RSL from statigraphy" data points and single coral or speleothems indicating former RSL positions. The difference in the two plots resides in the treatment o...
%run -i scripts/Elevation_error.py
_____no_output_____
MIT
Code/Query_and_Explore_data.ipynb
Alerovere/WALIS
Sea level index points This graph shows the frequency of sea-level indicators within the query, including the grouping in indicator types.
%run -i scripts/SL_Ind_Hist.py
_____no_output_____
MIT
Code/Query_and_Explore_data.ipynb
Alerovere/WALIS
Elevation and positioning histogramsThese graphs show the distributions of the elevation metadata (Elevation measurement technique and sea-level datum) used to describe sea-level datapoints in WALIS.
%run -i scripts/Vrt_meas_hist.py %run -i scripts/SL_datum_hist.py
_____no_output_____
MIT
Code/Query_and_Explore_data.ipynb
Alerovere/WALIS
Quality plotsThe RSL datapoints from stratigraphy contain two "data quality" fields, one for age and one for RSL information. Database compilers scored each site following standard guidelines (as per database documentation). This plot shows these quality scores plotted against each other. As the quality scores of one ...
%run -i scripts/Quality_plot.py
_____no_output_____
MIT
Code/Query_and_Explore_data.ipynb
Alerovere/WALIS
Compare two nations
%run -i scripts/select_nation_quality.py box %run -i scripts/Quality_nations.py
_____no_output_____
MIT
Code/Query_and_Explore_data.ipynb
Alerovere/WALIS
Compare two regions
%run -i scripts/select_region_quality.py box %run -i scripts/Quality_regions.py
_____no_output_____
MIT
Code/Query_and_Explore_data.ipynb
Alerovere/WALIS
MapsIn this section, the data is organized in a series of maps. Some styling choices are available.
%run -i scripts/select_map_options.py %run -i scripts/Static_maps.py
_____no_output_____
MIT
Code/Query_and_Explore_data.ipynb
Alerovere/WALIS
Global map of RSL datapoints. The following cell works only if the previous one is run choosing "RSL Datapoints" as Map Choice.
%run -i scripts/global_maps.py
_____no_output_____
MIT
Code/Query_and_Explore_data.ipynb
Alerovere/WALIS
Radiometric ages distributionThe code below plots the age distribution of radiometric ages within the query. The data is run through a Monte-Carlo sampling of the gaussian distribution of each radiometric age, and Kernel density estimate (KDE) plots are derived.
#Insert age limits to be plotted min_age=0 max_age=150 %run -i scripts/age_kde.py
_____no_output_____
MIT
Code/Query_and_Explore_data.ipynb
Alerovere/WALIS
Create ZIP archiveCreate a ZIP archive of the entire "Output" folder.
shutil.make_archive('Output', 'zip', Output_path)
_____no_output_____
MIT
Code/Query_and_Explore_data.ipynb
Alerovere/WALIS
Predicting Heart DiseaseThis dataset contains 76 features, but all published experiments refer to using a subset of 14 of them. The "goal" feature refers to the presence of heart disease in the patient. It is integer valued from 0 (no presence) to 4 (values 1,2,3,4) from absence (value 0). It is therefore a multiclass...
import pandas as pd import numpy as np from functions import cls as packt_classes # read the raw csv X = pd.read_csv('data/heart-disease-2.csv', header=None) # rename the columns cols = ['age', 'sex', 'cp', 'trestbps', 'chol', 'cigperday', 'fbs', 'famhist', 'restecg', 'thalach', 'exang', 'oldpeak', 'slope', ...
_____no_output_____
MIT
code/Heart Disease.ipynb
PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn
Pre-split: any major imbalance?If there are any categorical features with rare factor levels that need to be considered before splitting, we'll find out here.
def examine_cats(frame): for catcol in frame.columns[frame.dtypes == 'object'].tolist(): print(catcol) print(frame[catcol].value_counts()) print("") examine_cats(X)
sex male 206 female 97 Name: sex, dtype: int64 cp asymptomatic 144 non-anginal 86 atypical anginal 50 typical anginal 23 Name: cp, dtype: int64 restecg normal 151 vent 148 st-t 4 Name: restecg, dtype: int64 slope upsloping 142 flat 140 downsloping 2...
MIT
code/Heart Disease.ipynb
PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn
Perform train/test splitRemember, we always need to split! We will also stratify on the '`restecg`' variable since it's the most likely to be poorly split.
from sklearn.model_selection import train_test_split seed = 42 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=seed, stratify=X['restecg']) print("Train size: %i" % X_train.shape[0]) print("Test size: %i" % X_test.shape[0]) X_...
sex male 153 female 74 Name: sex, dtype: int64 cp asymptomatic 105 non-anginal 66 atypical anginal 37 typical anginal 19 Name: cp, dtype: int64 restecg normal 113 vent 111 st-t 3 Name: restecg, dtype: int64 slope flat 110 upsloping 102 downsloping 1...
MIT
code/Heart Disease.ipynb
PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn
Custom TransformersThere are several custom transformers that will be useful for this data:- Custom one-hot encoding that drops one level to avoid the [dummy variable trap](http://www.algosome.com/articles/dummy-variable-trap-regression.html)- Model-based imputation of continuous variables, since mean/median centering...
from sklearn.base import BaseEstimator, TransformerMixin from sklearn.utils.validation import check_is_fitted class CustomPandasTransformer(BaseEstimator, TransformerMixin): def _validate_input(self, X): if not isinstance(X, pd.DataFrame): raise TypeError("X must be a DataFrame, but got type=%s...
_____no_output_____
MIT
code/Heart Disease.ipynb
PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn
Explanation of LabelEncoder
from sklearn.preprocessing import LabelEncoder labels = ['banana', 'apple', 'orange', 'apple', 'orange'] le = LabelEncoder() le.fit(labels) le.transform(labels)
_____no_output_____
MIT
code/Heart Disease.ipynb
PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn
One-hot encode categorical dataIt is probably (hopefully) obvious why we need to handle data that is in string format. There is not much we can do numerically with data that resembles the following: [flat, upsloping, downsloping, ..., flat, flat, downsloping] There is a natural procedure to force numericism amon...
from sklearn.preprocessing import OneHotEncoder, LabelEncoder class DummyEncoder(CustomPandasTransformer): """A custom one-hot encoding class that handles previously unseen levels and automatically drops one level from each categorical feature to avoid the dummy variable trap. Parameters -----...
_____no_output_____
MIT
code/Heart Disease.ipynb
PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn
ImputationWe can either use a built-in scikit-learn `Imputer`, which will require mean/median as a statistic, or we can build a model. Statistic-based imputation
from sklearn.preprocessing import Imputer imputer = Imputer(strategy='median') imputer.fit(X_train_dummied) imputer.transform(X_train_dummied)[:5]
_____no_output_____
MIT
code/Heart Disease.ipynb
PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn
Model-based imputationAs discussed in the iris notebook, there are many pitfalls to using mean or median for scaling. In instances where our data is too large to examine all features graphically, many times we cannot discern whether all features are normally distributed (a pre-requisite for mean-scaling). If we want t...
from sklearn.ensemble import BaggingRegressor from sklearn.externals import six class BaggedRegressorImputer(CustomPandasTransformer): """Fit bagged regressor models for each of the impute columns in order to impute the missing values. Parameters ---------- impute_cols : list The colum...
_____no_output_____
MIT
code/Heart Disease.ipynb
PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn
Feature selection/dimensionality reductionOften times, when there is very high-dimensional data (100s or 1000s of features), it's useful to perform feature selection techniques to create more simple models that can be understood by analysts. A common one is [principal components analysis](http://scikit-learn.org/stabl...
from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler scaler = StandardScaler() scaler.fit(X_train_imputed) # fit PCA, get explained variance of ALL features pca_all = PCA(n_components=None) pca_all.fit(scaler.transform(X_train_imputed)) explained_var = np.cumsum(pca_all.explained_var...
_____no_output_____
MIT
code/Heart Disease.ipynb
PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn
At 15 (of 25) features, we finally explain >90% cumulative variance in our components. This is not a significant enough feature reduction to warrant use of PCA, so we'll skip it. Setup our CV
from sklearn.model_selection import StratifiedKFold # set up our CV cv = StratifiedKFold(n_splits=3, shuffle=True, random_state=seed)
_____no_output_____
MIT
code/Heart Disease.ipynb
PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn
Examine folds
folds = cv.split(X_train, y_train) for i, fold in enumerate(folds): tr, te = fold print("Fold %i:" % i) print("Training sample indices:\n%r" % tr) print("Testing sample indices:\n%r" % te) print("\n")
Fold 0: Training sample indices: array([ 1, 3, 4, 5, 6, 8, 9, 10, 12, 13, 15, 17, 18, 21, 23, 24, 25, 26, 27, 28, 30, 31, 32, 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 45, 47, 49, 51, 53, 54, 55, 56, 58, 59, 62, 65, 66, 69, 70, 71, 73, 74, 75,...
MIT
code/Heart Disease.ipynb
PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn
Baseline several modelsWe will build three models with default parameters and look at how the cross validation scores perform across folds, then we'll select the two better models to take into the model tuning stage.__NOTE__ we could theoretically go straight to tuning all three models to select the best, but it is of...
from sklearn.pipeline import Pipeline import numpy as np # these are the pre-processing stages stages = [ ('dummy', packt_classes.DummyEncoder(columns=['sex', 'cp', 'restecg', 'slope', 'thal'])), ('impute', packt_classes.BaggedRegressorImputer(impute_cols=['cigperday', 'ca'], ...
CV scores: array([-1.09616462, -2.26438127, -1.94406386]) Average CV score: -1.7682 CV score standard deviation: 0.4929
MIT
code/Heart Disease.ipynb
PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn
Initial thoughts* Our GBM and logistic regression perform similarly* Random forest did not perform very well and showed high variability across training folds* Let's move forward with LR & GBM Tuning hyper-paramsNow that we've baselined several models, let's choose a couple of the better-performing models to tune.
from scipy.stats import randint, uniform from sklearn.model_selection import RandomizedSearchCV gbm_pipe = Pipeline([ ('dummy', packt_classes.DummyEncoder(columns=['sex', 'cp', 'restecg', 'slope', 'thal'])), ('impute', packt_classes.BaggedRegressorImputer(impute_cols=['cigperday', 'ca'], ...
Fitting 3 folds for each of 100 candidates, totalling 300 fits
MIT
code/Heart Disease.ipynb
PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn
Examine the resultsRight away we can tell that the logistic regression model was *much* faster than the gradient boosting model. However, does the extra time spent fitting end up giving us a performance boost? Let's introduce our test set to the optimized models and select the one that performs better. We are using [_...
from sklearn.utils import gen_batches def grid_report(search, n_splits, key='mean_test_score'): res = search.cv_results_ arr = res[key] slices = gen_batches(arr.shape[0], n_splits) return pd.Series({ '%s_MEAN' % key: arr.mean(), '%s_STD' % key: arr.std(), ...
_____no_output_____
MIT
code/Heart Disease.ipynb
PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn
If the CV scores meet business requirements, move on to model selection
from sklearn.metrics import log_loss gbm_preds = gbm_search.predict_proba(X_test) lgr_preds = lgr_search.predict_proba(X_test) print("GBM test LOSS: %.5f" % log_loss(y_true=y_test, y_pred=gbm_preds)) print("Logistic regression test LOSS: %.5f" % log_loss(y_true=y_test, y_pred=lgr_preds))
GBM test LOSS: 0.96101 Logistic regression test LOSS: 0.97445
MIT
code/Heart Disease.ipynb
PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn
Note that in log loss, greater is WORSE. Therefore, the logistic regression was out-performed by the GBM. If the greater time to fit is not an issue for you, then this would be the better model to select. Likewise, you may favor model transparency over the extra few decimal points of accuracy, in which case the logisti...
# feed data through the pipe stages to get the transformed feature names X_trans = X_train for step in gbm_search.best_estimator_.steps[:-1]: X_trans = step[1].transform(X_trans) transformed_feature_names = X_trans.columns transformed_feature_names best_gbm = gbm_search.best_estimator_.steps[-1][1] importances...
_____no_output_____
MIT
code/Heart Disease.ipynb
PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn
Partial dependencyIn the following section, we'll break our GBM into a piecewise linear functions to gauge how different variables impact the target, and create [partial dependency plots](http://scikit-learn.org/stable/auto_examples/ensemble/plot_partial_dependence.html)
from sklearn.ensemble.partial_dependence import plot_partial_dependence from sklearn.ensemble.partial_dependence import partial_dependence def plot_partial(est, which_features, X, names, label): fig, axs = plot_partial_dependence(est, X, which_features, feature_names=names, ...
_____no_output_____
MIT
code/Heart Disease.ipynb
PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn
Post-processingSuppose our board of surgeons only cares if the prediction is class "3" with a probability of >=0.3. In this segment we'll write and test a piece of code that we'll use as post-processing in our Flask API.
def is_certain_class(predictions, cls=3, proba=0.3): # find the row arg maxes (ones that are predicted 'cls') argmaxes = predictions.argmax(axis=1) # get the probas for the cls of interest probas = predictions[:, cls] # boolean mask that becomes our prediction vector return ((argmaxes ...
_____no_output_____
MIT
code/Heart Disease.ipynb
PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn
This means we'll need to use "`predict_proba`" rather than "`predict`":
P = lgr_search.predict_proba(X_test) P[:5] is_certain_class(P)
_____no_output_____
MIT
code/Heart Disease.ipynb
PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn