text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
# Convex polyhedron
```
import fresnel
import itertools
import math
import numpy as np
device = fresnel.Device()
scene = fresnel.Scene(device)
```
The **convex polyhedron geometry** defines a set of *N* convex polyhedra. The shape of all *N* polyhedra is identical and defined by *P* planes. Each polyhedron has its own *position*, *orientation*, and *color*. You must also specify the circumsphere radius *r*. Note that the information used to draw a convex polyhedron is easily obtained from it's vertices via the `util.convex_polyhedron_from_vertices()` utility function.
To construct a truncated cube:
```
# first get cube verts
pm = [-1, 1]
cube_verts = list(itertools.product(pm, repeat=3))
trunc_cube_verts = []
# truncate by removing corners and adding vertices to edges
for p1, p2 in itertools.combinations(cube_verts, 2):
# don't add points along any diagonals
match = (p1[0]==p2[0], p1[1]==p2[1], p1[2]==p2[2])
if match.count(False) == 1: # only 1 coordinate changes, not a diagonal
p1, p2 = np.array(p1), np.array(p2)
vec = p2 - p1
trunc_cube_verts.append(p1 + vec/3)
trunc_cube_verts.append(p1 + 2*vec/3)
c1 = fresnel.color.linear([0.70, 0.87, 0.54])*0.8
c2 = fresnel.color.linear([0.65,0.81,0.89])*0.8
colors = {8: c1, 3: c2}
poly_info = fresnel.util.convex_polyhedron_from_vertices(trunc_cube_verts)
for idx, fs in enumerate(poly_info['face_sides']):
poly_info['face_color'][idx] = colors[fs]
geometry = fresnel.geometry.ConvexPolyhedron(scene,
poly_info,
N=3
)
geometry.material = fresnel.material.Material(color=fresnel.color.linear([0.25,0.5,0.9]),
roughness=0.8)
```
## Geometric properties
**position** defines the position of the center of each convex polyhedron.
```
geometry.position[:] = [[-3,0,0], [0, 0, 0], [3, 0, 0]]
```
**orientation** sets the orientation of each convex polyhedron as a quaternion
```
geometry.orientation[:] = [[1, 0, 0, 0],
[0.80777943, 0.41672122, 0.00255412, 0.41692838],
[0.0347298, 0.0801457, 0.98045, 0.176321]]
scene.camera = fresnel.camera.Orthographic.fit(scene, view='front', margin=0.8)
fresnel.preview(scene)
```
## Color
**color** sets the color of each individual convex polyhedron (when *primitive_color_mix > 0* and *color_by_face < 1* )
```
geometry.color[:] = fresnel.color.linear([[0.9,0,0], [0, 0.9, 0], [0, 0, 0.9]])
geometry.material.primitive_color_mix = 1.0
fresnel.preview(scene)
```
Set **color_by_face** > 0 to color the faces of the polyhedra independently. `poly_info['face_colors']` (i.e., the output of convex_polyhedron_from_vertices, which we modified above) sets the color of each face. Above, we set the color of the each face based on number of sides it has.
```
geometry.color_by_face = 1.0
fresnel.preview(scene)
```
## Outlines
Outlines are applied at the outer edge of each face.
```
geometry.outline_width = 0.02
fresnel.preview(scene)
```
This page was generated from a [jupyter](https://jupyter.org/) notebook. You can download and run the notebook locally from the [fresnel-examples](https://github.com/glotzerlab/fresnel-examples) repository.
| github_jupyter |
<a href="https://colab.research.google.com/github/Tessellate-Imaging/monk_v1/blob/master/study_roadmaps/1_getting_started_roadmap/5_update_hyperparams/2_data_params/1)%20Change%20batch%20sizes%20from%20default%20state.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Goals
### Learn how to change batch size
# Table of Contents
## [Install](#0)
## [Train with a preset batch size of 4](#1)
## [Train with an updated batch size of 8](#2)
## [Compare both the experiments](#3)
<a id='0'></a>
# Install Monk
## Using pip (Recommended)
- colab (gpu)
- All bakcends: `pip install -U monk-colab`
- kaggle (gpu)
- All backends: `pip install -U monk-kaggle`
- cuda 10.2
- All backends: `pip install -U monk-cuda102`
- Gluon bakcned: `pip install -U monk-gluon-cuda102`
- Pytorch backend: `pip install -U monk-pytorch-cuda102`
- Keras backend: `pip install -U monk-keras-cuda102`
- cuda 10.1
- All backend: `pip install -U monk-cuda101`
- Gluon bakcned: `pip install -U monk-gluon-cuda101`
- Pytorch backend: `pip install -U monk-pytorch-cuda101`
- Keras backend: `pip install -U monk-keras-cuda101`
- cuda 10.0
- All backend: `pip install -U monk-cuda100`
- Gluon bakcned: `pip install -U monk-gluon-cuda100`
- Pytorch backend: `pip install -U monk-pytorch-cuda100`
- Keras backend: `pip install -U monk-keras-cuda100`
- cuda 9.2
- All backend: `pip install -U monk-cuda92`
- Gluon bakcned: `pip install -U monk-gluon-cuda92`
- Pytorch backend: `pip install -U monk-pytorch-cuda92`
- Keras backend: `pip install -U monk-keras-cuda92`
- cuda 9.0
- All backend: `pip install -U monk-cuda90`
- Gluon bakcned: `pip install -U monk-gluon-cuda90`
- Pytorch backend: `pip install -U monk-pytorch-cuda90`
- Keras backend: `pip install -U monk-keras-cuda90`
- cpu
- All backend: `pip install -U monk-cpu`
- Gluon bakcned: `pip install -U monk-gluon-cpu`
- Pytorch backend: `pip install -U monk-pytorch-cpu`
- Keras backend: `pip install -U monk-keras-cpu`
## Install Monk Manually (Not recommended)
### Step 1: Clone the library
- git clone https://github.com/Tessellate-Imaging/monk_v1.git
### Step 2: Install requirements
- Linux
- Cuda 9.0
- `cd monk_v1/installation/Linux && pip install -r requirements_cu90.txt`
- Cuda 9.2
- `cd monk_v1/installation/Linux && pip install -r requirements_cu92.txt`
- Cuda 10.0
- `cd monk_v1/installation/Linux && pip install -r requirements_cu100.txt`
- Cuda 10.1
- `cd monk_v1/installation/Linux && pip install -r requirements_cu101.txt`
- Cuda 10.2
- `cd monk_v1/installation/Linux && pip install -r requirements_cu102.txt`
- CPU (Non gpu system)
- `cd monk_v1/installation/Linux && pip install -r requirements_cpu.txt`
- Windows
- Cuda 9.0 (Experimental support)
- `cd monk_v1/installation/Windows && pip install -r requirements_cu90.txt`
- Cuda 9.2 (Experimental support)
- `cd monk_v1/installation/Windows && pip install -r requirements_cu92.txt`
- Cuda 10.0 (Experimental support)
- `cd monk_v1/installation/Windows && pip install -r requirements_cu100.txt`
- Cuda 10.1 (Experimental support)
- `cd monk_v1/installation/Windows && pip install -r requirements_cu101.txt`
- Cuda 10.2 (Experimental support)
- `cd monk_v1/installation/Windows && pip install -r requirements_cu102.txt`
- CPU (Non gpu system)
- `cd monk_v1/installation/Windows && pip install -r requirements_cpu.txt`
- Mac
- CPU (Non gpu system)
- `cd monk_v1/installation/Mac && pip install -r requirements_cpu.txt`
- Misc
- Colab (GPU)
- `cd monk_v1/installation/Misc && pip install -r requirements_colab.txt`
- Kaggle (GPU)
- `cd monk_v1/installation/Misc && pip install -r requirements_kaggle.txt`
### Step 3: Add to system path (Required for every terminal or kernel run)
- `import sys`
- `sys.path.append("monk_v1/");`
## Dataset -Skin cancer Mnist
- https://www.kaggle.com/kmader/skin-cancer-mnist-ham10000
```
! wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1MRC58-oCdR1agFTWreDFqevjEOIWDnYZ' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1MRC58-oCdR1agFTWreDFqevjEOIWDnYZ" -O skin_cancer_mnist_dataset.zip && rm -rf /tmp/cookies.txt
! unzip -qq skin_cancer_mnist_dataset.zip
```
# Imports
```
#Using gluon backend
# When installed using pip
from monk.gluon_prototype import prototype
# When installed manually (Uncomment the following)
#import os
#import sys
#sys.path.append("monk_v1/");
#sys.path.append("monk_v1/monk/");
#from monk.gluon_prototype import prototype
```
<a id='1'></a>
# Train using batch size of 4
```
gtf = prototype(verbose=1);
gtf.Prototype("change-batch-size", "size_4");
gtf.Default(dataset_path="skin_cancer_mnist_dataset/images",
path_to_csv="skin_cancer_mnist_dataset/train_labels.csv",
model_name="resnet18_v1",
freeze_base_network=False,
num_epochs=5);
#Read the summary generated once you run this cell.
```
## Default is using batch size of 4
```
#Start Training
gtf.Train();
#Read the training summary generated once you run the cell and training is completed
# Lets validate on training data itself
gtf = prototype(verbose=1);
gtf.Prototype("change-batch-size", "size_4", eval_infer=True);
gtf.Dataset_Params(dataset_path="skin_cancer_mnist_dataset/images",
path_to_csv="skin_cancer_mnist_dataset/train_labels.csv");
gtf.Dataset();
accuracy, class_based_accuracy = gtf.Evaluate();
```
<a id='2'></a>
# Train using batch size of 8
```
gtf = prototype(verbose=1);
gtf.Prototype("change-batch-size", "size_8");
gtf.Default(dataset_path="skin_cancer_mnist_dataset/images",
path_to_csv="skin_cancer_mnist_dataset/train_labels.csv",
model_name="resnet18_v1",
freeze_base_network=False,
num_epochs=5);
#Read the summary generated once you run this cell.
```
## Switch batch size to 8
```
gtf.update_batch_size(8);
# Very Important to reload
gtf.Reload();
#Start Training
gtf.Train();
#Read the training summary generated once you run the cell and training is completed
```
## Validate the trained classifier on training data itself
```
gtf = prototype(verbose=1);
gtf.Prototype("change-batch-size", "size_8", eval_infer=True);
gtf.Dataset_Params(dataset_path="skin_cancer_mnist_dataset/images",
path_to_csv="skin_cancer_mnist_dataset/train_labels.csv");
gtf.Dataset();
accuracy, class_based_accuracy = gtf.Evaluate();
```
<a id='3'></a>
# Compare experiments
```
# Invoke the comparison class
from monk.compare_prototype import compare
# Create a project
gtf = compare(verbose=1);
gtf.Comparison("Statistics");
# Add experiment
gtf.Add_Experiment("change-batch-size", "size_4");
gtf.Add_Experiment("change-batch-size", "size_8");
# Generate stats
gtf.Generate_Statistics();
os.listdir("workspace/comparison/Statistics")
# We are interested in training times, validation accuracies and train-test plots
from IPython.display import Image
Image(filename="workspace/comparison/Statistics/stats_best_val_acc.png")
```
## Better accuracy with larger batch size
```
from IPython.display import Image
Image(filename="workspace/comparison/Statistics/stats_training_time.png")
```
## Faster training with larger batch size
```
from IPython.display import Image
Image(filename="workspace/comparison/Statistics/train_accuracy.png")
from IPython.display import Image
Image(filename="workspace/comparison/Statistics/val_accuracy.png")
```
# Goals Completed
### Learn how to change batch size
| github_jupyter |
```
!pip install sense2vec
%reload_ext autoreload
%autoreload 2
import copy
from pprint import pprint
from pathlib import Path
from typing import Any, Dict, List, Set, Tuple
import spacy
import srsly
# import recon
from recon.corpus import Corpus
from recon.constants import NONE
from recon.corrections import fix_annotations
from recon.dataset import Dataset
from recon.loaders import read_jsonl
from recon.types import Correction, Example, PredictionError, HardestExample, NERStats, EntityCoverageStats, EntityCoverage, Transformation, TransformationType, OperationState
from recon.stats import (
get_ner_stats, get_entity_coverage, get_sorted_type_counts, get_probs_from_counts, entropy,
calculate_entity_coverage_entropy, calculate_label_balance_entropy, calculate_label_distribution_similarity,
detect_outliers
)
import recon.tokenization as tokenization
from recon.insights import get_ents_by_label, get_label_disparities, top_prediction_errors, top_label_disparities, get_hardest_examples
from recon.recognizer import SpacyEntityRecognizer
from recon.operations import registry
from recon.store import ExampleStore
# TODO: Fix Dataset loading with different file names
# train = Dataset("train").from_disk("./data/fashion_brands/fashion_brands_training.jsonl")
# dev = Dataset("dev").from_disk("./data/fashion_brands/fashion_brands_eval.jsonl")
corpus = Corpus.from_disk("./data/fashion_brands/", "fashion_brands")
print(corpus.apply(get_ner_stats, serialize=True).train)
print(corpus.apply(get_ner_stats, serialize=True).dev)
print(corpus.apply(get_ner_stats, serialize=True).all)
ec = corpus.apply(get_entity_coverage, case_sensitive=True)
ec.train[:5]
unique_ec = {e.text for e in ec.all}
len(unique_ec)
# source: https://www.apparelsearch.com/wholesale_clothing/popular_brand_names_clothes.htm
extra_brands = ["Adidas", "Aeffe S.P.A", "Agatha", "Agnes B", "", "Anna Osmushkina", "Anna Sui", "Aquascutum", "Armani Exchange", "Austin Reed", "Avirex", "BCBG", "Benetton", "Bisou-Bisou", "Body Glove", "Bogner", "Burton", "Brioni", "Calvin Klein", "Cesarani", "Champion", "Chanel", "Christian Dior", "", "Christian Lacoix", "Claiborne", "Club Monaco", "Columbia", "Converse", "Courrages", "Cutter & ", "Buck", "Diesel", "Dockers", "", "Dolce & Gabbana", "Donna Karan", "Ecco", "Ecko", "Eddie Bauer", "Ellesse", "Eliott & ", "Lucca", "Energie", "Esprit", "Everlast", "Fia Miami", "Fila", "Fiorelli", "", "Fratelli Corneliani", "Fred Perry", "Fruit of the ", "Loom", "Fubu", "", "Gianfranco Ferre", "Gianni Versace", "Giorgio Armani", "Gucci", "Guess", "Helly Hansen", "Hugo Boss", "J. Crew", "Izod", "Jitrois", "Jennifer Lopez", "", "Jenny Yoo", "Jhane Barnes", "Joe Boxer", "", "John Smedley", "Jordache", "Kenneth Cole ", "/ Reaction", "Lacoste", "Land's End", "", "La Perla", "Laura Ashley", "Lee", "Le Tigre", "Levi's", "Liz Claiborne", "L.L Bean", "", "Louis Feraud", "Lucky Brand ", "Jeans", "", "Madeleine Vionnet", "Mango", "Marc Jacobs", "", "Marcia Grachvogel", "", "Marianne Alvoni", "", "Michael Kors", "Moschino", "Mudd", "Munsingwear", "Nancy LordNew Balance", "Nicole Miller", "Nike", "", "Norma Kamali", "Oky-coky", "Oilily", "", "Olivier Strelli", "Oneill", "OP", "", "OshKosh B'Gosh", "Paul Fredrick", "Paul Shark", "Paul Smith", "", "Pelle Pelle", "Pepe Jeans", "Perry Ellis", "", "Perry Landhaus", "Pierre Cardin", "", "Pierre Garroudi", "Prada", "Puma", "Quiksilver", "Ralph Lauren", "Rampage", "Red Monkey", "Red or Dead", "Roberto Angelico", "Rocawear", "Russell", "Savane", "Salvatore J. ", "Cesarani", "Sean John", "Sinequanone", "Sisley", "Southpole", "Speedo", "Steven Alan", "Swatch", "Timberland", "Todd Oldham", "Tommy Hilfiger", "Van Heusen", "Vans", "Versace", "Vokal", "Wrangler", "Yves Saint ", "Laurent", "", "Z. Cavaricci", "Zanetti", "Zero"]
extra_brands = {eb for eb in extra_brands if eb != ""}
len(extra_brands)
unique_ec.update(extra_brands)
len(unique_ec)
from typing import Any, Callable, Dict, List, Optional
from recon.dataset import Dataset
from pydantic import root_validator
from recon.types import Example, Span, Token
import numpy as np
from recon.augmentation import substitute_spans
from recon.operations import operation, registry
from recon.preprocess import SpacyPreProcessor
import names
from snorkel.augmentation import transformation_function, ApplyAllPolicy
from snorkel.preprocess.nlp import SpacyPreprocessor
from recon.preprocess import SpacyPreProcessor
import spacy
nlp = spacy.load("en_core_web_sm")
spacy_pre = SpacyPreProcessor(nlp)
np.random.seed(0)
def augment_example(
example: Example,
span_f: Callable[[Span, Any], Optional[str]],
spans: List[Span] = None,
span_label: str = None,
**kwargs: Any,
) -> List[Example]:
if spans is None:
spans = example.spans
prev_example_hash = hash(example)
example_t = None
if span_label:
spans = [s for s in spans if s.label == span_label]
if spans:
spans_to_sub = [np.random.choice(spans)]
span_subs = {}
for span in spans_to_sub:
res = span_f(span, **kwargs) # type: ignore
if res:
span_subs[span] = res
if any(span_subs.values()):
res = substitute_spans(example, span_subs)
if hash(res) != prev_example_hash:
example_t = res
return example_t
np.random.seed(0)
def ent_label_sub(
example: Example, label: str, subs: List[str]
) -> Optional[Example]:
def augmentation_f(span: Span, subs: List[str]) -> Optional[str]:
subs = [s for s in subs if s != span.text]
sub = None
if len(subs) > 0:
sub = np.random.choice(subs)
return sub
return augment_example(example, span_f=augmentation_f, span_label=label, subs=subs)
# replacement_names = [names.get_full_name() for _ in range(50)]
@transformation_function()
def brand_sub(example: Example):
return ent_label_sub(example.copy(deep=True), label="FASHION_BRAND", subs=list(unique_ec))
# @transformation_function()
# def person_sub(example: Example):
# return ent_label_sub(example.copy(deep=True), label="PERSON", subs=replacement_names)
@transformation_function()
def gpe_sub(example: Example):
return ent_label_sub(example.copy(deep=True), label="GPE", subs=["Russia", "USA", "China"])
def kb_sub(
example: Example, spans_to_aliases_map: Dict[Span, str]
) -> Optional[Example]:
def augmentation_f(span: Span, spans_to_aliases_map: Dict[Span, List[str]]) -> Optional[str]:
sub = None
if span in spans_to_aliases_map:
aliases = spans_to_aliases_map[span]
if len(aliases) > 0:
rand_alias = np.random.choice(aliases)
index = aliases.index(rand_alias)
del spans_to_aliases_map[span][index]
sub = rand_alias
return sub
return augment_example(example, span_f=augmentation_f, span_label=label, subs=subs)
# @transformation_function()
# def skills_sub(example: Example):
import spacy
from sense2vec import Sense2VecComponent
s2v_path = "../../sense2vec/s2v_old/"
nlp = spacy.load("en_core_web_sm")
s2v = Sense2VecComponent(nlp.vocab).from_disk(s2v_path)
nlp.add_pipe(s2v)
doc = nlp(corpus.train[0].text)
for ph in doc._.s2v_phrases:
try:
most_similar = ph._.s2v_most_similar(3)
except:
most_similar = None
print(ph)
print(most_similar)
ms = [(('beard', 'NOUN'), 0.8841), (('curly hair', 'NOUN'), 0.8841), (('stubble', 'NOUN'), 0.8836)]
ms[0][0][0]
import numpy as np
def test_model_most_similar_cache(s2v):
query = "beekeepers|NOUN"
s2v.cache = {"indices": np.empty((2,1)), "scores": np.empty((0,0))}
assert s2v.cache
assert query in s2v
indices = s2v.cache["indices"]
# Modify cache to test that the cache is used and values aren't computed
query_row = s2v.vectors.find(key=s2v.ensure_int_key(query))
scores = np.array(s2v.cache["scores"], copy=True) # otherwise not writable
honey_bees_row = s2v.vectors.find(key="honey_bees|NOUN")
beekeepers_row = s2v.vectors.find(key="Beekeepers|NOUN")
for i in range(indices.shape[0]):
for j in range(indices.shape[1]):
if indices[i, j] == honey_bees_row:
scores[i, j] = 2.0
elif indices[i, j] == beekeepers_row:
scores[i, j] = 3.0
s2v.cache["scores"] = scores
print("CACHE")
print(s2v.cache)
((key1, score1), (key2, score2)) = s2v.most_similar([query], n=2)
assert key1 == "honey_bees|NOUN"
assert score1 == 2.0
assert key2 == "Beekeepers|NOUN"
assert score2 == 3.0
s2v.s2v.cache = None
_s2v = test_model_most_similar_cache(s2v.s2v)
_s2v.cache
s2v.s2v.vectors.find(key="honey_bees|NOUN")
assert s2v.s2v.cache
len(s2v.s2v)
1195261 * 1195261
from nltk.corpus import wordnet as wn
def get_synonym(word, pos=None):
"""Get synonym for word given its part-of-speech (pos)."""
synsets = wn.synsets(word, pos=pos)
# Return None if wordnet has no synsets (synonym sets) for this word and pos.
if synsets:
words = [lemma.name() for lemma in synsets[0].lemmas()]
if words[0].lower() != word.lower(): # Skip if synonym is same as word.
# Multi word synonyms in wordnet use '_' as a separator e.g. reckon_with. Replace it with space.
return words[0].replace("_", " ")
# @operation("recon.v1.augment.replace_pos_with_synonym", pre=[spacy_pre])
def replace_pos_with_synonym(
example: Example,
pos: str,
synonym_f: Callable[[str], str] = get_synonym
):
pos_map = {
"VERB": "v",
"NOUN": "n",
"ADJ": "a"
}
if pos not in pos_map:
raise ValueError(f"Argument `pos` of {pos} not in {''.join(pos_map.keys())}")
doc = example.doc
span_starts = [s.start for s in example.spans]
# Get indices of verb tokens in sentence.
pos_idxs = [i for i, token in enumerate(doc) if token.pos_ == pos and token.idx not in span_starts]
tokens = [doc[idx] for idx in pos_idxs]
spans = [Span(text=token.text, start=token.idx, end=token.idx + len(token.text), label="") for token in tokens]
def augmentation_f(span: Span, synonym_f: Callable[[str], str] = synonym_f) -> Optional[str]:
return synonym_f(span.text)
return augment_example(
example,
augmentation_f,
spans=spans,
)
spacy_pre = SpacyPreprocessor(text_field="text", doc_field="doc")
@transformation_function(pre=[spacy_pre])
def replace_verb_with_synonym(example: Example):
return replace_pos_with_synonym(example, "VERB")
@transformation_function(pre=[spacy_pre])
def replace_noun_with_synonym(example: Example):
return replace_pos_with_synonym(example, "NOUN")
@transformation_function(pre=[spacy_pre])
def replace_adj_with_synonym(example: Example):
return replace_pos_with_synonym(example, "ADJ")
s2v_pre = SpacyPreprocessor(text_field="text", doc_field="doc")
s2v_pre._nlp = nlp
@transformation_function(pre=[s2v_pre])
def replace_s2v(example):
doc = example.doc
span_starts = [s.start for s in example.spans]
most_similar_map = {}
for ph in doc._.s2v_phrases:
try:
most_similar = ph._.s2v_most_similar(5)
except:
most_similar = None
if most_similar:
span = Span(text=ph.text, start=ph.start_char, end=ph.end_char, label="")
if span.start not in span_starts:
most_similar_map[span] = most_similar
def augmentation_f(span: Span, most_similar_map: Dict[Span, List[str]]) -> Optional[str]:
choice = np.random.choice(most_similar_map[span][0][0])
return choice
return augment_example(
example,
augmentation_f,
spans=list(most_similar_map.keys()),
most_similar_map=most_similar_map
)
tfs = [
brand_sub,
replace_s2v
# person_sub,
# gpe_sub
]
np.random.seed(0)
from snorkel.augmentation import ApplyOnePolicy, RandomPolicy
random_policy = RandomPolicy(
len(tfs), sequence_length=2, n_per_original=2, keep_original=True
)
random_policy.generate_for_example()
policy = ApplyAllPolicy(len(tfs))
policy.generate_for_example()
from tqdm import tqdm
from snorkel.augmentation.apply.core import BaseTFApplier
class ReconDatasetTFApplier(BaseTFApplier):
def __init__(self, tfs, policy, span_label: str = None, sub_prob: float = 0.5):
super().__init__(tfs, policy)
self.span_label = span_label
self.sub_prob = sub_prob
def _apply_policy_to_data_point(self, x: Example) -> List[Example]:
x_transformed = set()
for seq in self._policy.generate_for_example():
x_t = x.copy(deep=True)
# Handle empty sequence for `keep_original`
transform_applied = len(seq) == 0
# Apply TFs
for tf_idx in seq:
tf = self._tfs[tf_idx]
x_t_or_none = tf(x_t)
# Update if transformation was applied
if x_t_or_none is not None:
transform_applied = True
x_t = x_t_or_none.copy(deep=True)
# Add example if original or transformations applied
if transform_applied:
x_transformed.add(x_t)
return list(x_transformed)
def apply(self, ds: Dataset, progress_bar: bool = True) -> Dataset:
@operation("recon.v1.augment")
def augment(example: Example):
transformed_examples = self._apply_policy_to_data_point(example)
return transformed_examples
ds.apply_("recon.v1.augment")
return ds
len(corpus.train_ds)
np.random.seed(0)
applier = ReconDatasetTFApplier(tfs, random_policy)
applier.apply(corpus.train_ds)
len(corpus.train_ds)
corpus.train[:3]
print(corpus.apply(get_ner_stats, serialize=True).train)
print(corpus.apply(get_ner_stats, serialize=True).dev)
print(corpus.apply(get_ner_stats, serialize=True).all)
corpus.train[:5]
# corpus.train_ds.to_disk("./fixed_data/fashion_brands_4_augmentations/train", force=True)
raw_data = [e.dict() for e in corpus.train_ds.data]
len(raw_data)
for e in raw_data:
if 'doc' in e:
del e['doc']
srsly.write_jsonl("./fixed_data/fashion_brands_4_augmentations/train.jsonl", raw_data)
corpus.example_store[corpus.train_ds.operations[0].transformations[2].example]
len(corpus.train_ds)
print(corpus.apply(get_ner_stats, serialize=True).train)
print(corpus.apply(get_ner_stats, serialize=True).dev)
print(corpus.apply(get_ner_stats, serialize=True).all)
corpus.to_disk("./fixed_data/fashion_brands_ent_label_augment", force=True)
```
| github_jupyter |
## EVD transmission model from Khan et al 2015 using Python/SciPy
Author: Verity Hill @ViralVerity
Date: 2018-10-03
```
import numpy as np
import pandas as pd
from scipy.integrate import ode, solve_ivp
import matplotlib.pyplot as plt
plt.style.use("ggplot")
def LIB(times, init, paramsLIB):
beta, eta, psi, pi, p, alpha, thetaI, thetaH, tau, mu, deltaI, deltaH = paramsLIB
SL,SH,E,I,H,R = init
#N = ST + E + I + R
N = SL + SH + E + I + H + R
lamb = beta * ((I + (eta*H))/N)
dSL = pi*(1-p) - lamb*SL - mu*SL
dSH = pi*p - lamb*psi*SH - mu*SH
dE = lamb*(SL + psi*SH) - (alpha + mu)*E
dI = alpha*E - (tau + thetaI + deltaI + mu)*I
dH = tau*I - (thetaH + deltaH + mu)*H
dR = thetaI*I + thetaH*H - mu*R
return(dSL, dSH, dE, dI, dH, dR)
def SL(times, init, paramsSL):
beta, eta, psi, pi, p, alpha, thetaI, thetaH, tau, mu, deltaI, deltaH = paramsSL
SL,SH,E,I,H,R = init
#N = ST + E + I + R
N = SL + SH + E + I + H + R
lamb = beta * (I + (eta*H))/N
dSL = pi*(1-p) - lamb*SL - mu*SL
dSH = pi*p - lamb*psi*SH - mu*SH
dE = lamb*(SL + psi*SH) - (alpha + mu)*E
dI = alpha*E - (tau + thetaI + deltaI + mu)*I
dH = tau*I - (thetaH + deltaH + mu)*H
dR = thetaI*I + thetaH*H - mu*R
return(dSL, dSH, dE, dI, dH, dR)
#For Liberia
paramsLIB = [0.371, 0.7, 1.6, 1.7, 0.2, 0.1, 0.1, 0.2, 0.16, (1/63)/365, 0.1, 0.5]
#For Sierra Leone
paramsSL = [0.361, 0.7, 1.6, 1.7, 0.2, 0.1, 0.1, 0.2, 0.16, (1/63)/365, 0.1, 0.5]
#For both
init = [1000000, 20000, 15, 10, 0, 0]
times = np.linspace(0, 200, 200)
sol_LIB = solve_ivp(fun=lambda t, y: LIB(t, y, paramsLIB), t_span=[min(times),max(times)], y0=init, t_eval=times)
output_LIB = pd.DataFrame({"t":sol_LIB["t"],"SL":sol_LIB["y"][0],"SH": sol_LIB["y"][1],"E":sol_LIB["y"][2],"I":sol_LIB["y"][3], "H":sol_LIB["y"][4], "R":sol_LIB["y"][5]})
sol_SL = solve_ivp(fun=lambda t, y: SL(t, y, paramsSL), t_span=[min(times),max(times)], y0=init, t_eval=times)
output_SL = pd.DataFrame({"t":sol_SL["t"],"SL":sol_SL["y"][0],"SH": sol_SL["y"][1],"E":sol_SL["y"][2],"I":sol_SL["y"][3], "H":sol_SL["y"][4], "R":sol_SL["y"][5]})
#sLline = plt.plot("t","SL","",data=output_SL,color="red",linewidth=2)
#sHline = plt.plot("t", "SH", "", data = output_SL, color = "red", linewidth = 2)
iline = plt.plot("t","I","",data=output_SL,color="green",linewidth=2)
#rline = plt.plot("t","R","",data=output_SL,color="blue",linewidth=2)
plt.xlabel("Time",fontweight="bold")
plt.ylabel("Number",fontweight="bold")
legend = plt.legend(title="Population",loc=5,bbox_to_anchor=(1.25,0.5))
frame = legend.get_frame()
frame.set_facecolor("white")
frame.set_linewidth(0)
#sLline = plt.plot("t","SL","",data=output_SL,color="red",linewidth=2)
#sHline = plt.plot("t", "SH", "", data = output_SL, color = "red", linewidth = 2)
iline = plt.plot("t","I","",data=output_LIB,color="green",linewidth=2)
#rline = plt.plot("t","R","",data=output_SL,color="blue",linewidth=2)
plt.xlabel("Time",fontweight="bold")
plt.ylabel("Number",fontweight="bold")
legend = plt.legend(title="Population",loc=5,bbox_to_anchor=(1.25,0.5))
frame = legend.get_frame()
frame.set_facecolor("white")
frame.set_linewidth(0)
```
| github_jupyter |
# Sea Surface Altimetry Data Analysis
For this example we will use gridded sea-surface altimetry data from The Copernicus Marine Environment:
http://marine.copernicus.eu/services-portfolio/access-to-products/?option=com_csw&view=details&product_id=SEALEVEL_GLO_PHY_L4_REP_OBSERVATIONS_008_047
This is a widely used dataset in physical oceanography and climate.

The dataset has already been extracted from copernicus and stored in google cloud storage in [xarray-zarr](http://xarray.pydata.org/en/latest/io.html#zarr) format.
```
import numpy as np
import xarray as xr
import matplotlib.pyplot as plt
import gcsfs
plt.rcParams['figure.figsize'] = (15,10)
%matplotlib inline
```
### Initialize Dataset
Here we load the dataset from the zarr store. Note that this very large dataset initializes nearly instantly, and we can see the full list of variables and coordinates.
```
import intake
cat = intake.Catalog("https://raw.githubusercontent.com/pangeo-data/pangeo-datastore/master/intake-catalogs/ocean.yaml")
ds = cat["sea_surface_height"].to_dask()
ds
```
### Examine Metadata
For those unfamiliar with this dataset, the variable metadata is very helpful for understanding what the variables actually represent
```
for v in ds.data_vars:
print('{:>10}: {}'.format(v, ds[v].attrs['long_name']))
```
## Visually Examine Some of the Data
Let's do a sanity check that the data looks reasonable:
```
plt.rcParams['figure.figsize'] = (15, 8)
ds.sla.sel(time='2000-01-01', method='nearest').plot()
```
### Same thing using interactive graphics
```
import holoviews as hv
from holoviews.operation.datashader import regrid
hv.extension('bokeh')
dataset = hv.Dataset(ds.sla)
hv_im = (dataset.to(hv.Image, ['longitude', 'latitude'], dynamic=True)
.redim.range(sla=(-0.5, 0.5))
.options(cmap='RdBu_r', width=800, height=450, colorbar=True))
%output holomap='scrubber' fps=2
regrid(hv_im, precompute=True)
```
### Create and Connect to Dask Distributed Cluster
```
from dask.distributed import Client, progress
from dask_kubernetes import KubeCluster
cluster = KubeCluster()
cluster.adapt(minimum=1, maximum=20)
cluster
```
** ☝️ Don't forget to click the link above to view the scheduler dashboard! **
```
client = Client(cluster)
client
```
## Timeseries of Global Mean Sea Level
Here we make a simple yet fundamental calculation: the rate of increase of global mean sea level over the observational period.
```
# the number of GB involved in the reduction
ds.sla.nbytes/1e9
# the computationally intensive step
sla_timeseries = ds.sla.mean(dim=('latitude', 'longitude')).load()
sla_timeseries.plot(label='full data')
sla_timeseries.rolling(time=365, center=True).mean().plot(label='rolling annual mean')
plt.ylabel('Sea Level Anomaly [m]')
plt.title('Global Mean Sea Level')
plt.legend()
plt.grid()
```
In order to understand how the sea level rise is distributed in latitude, we can make a sort of [Hovmöller diagram](https://en.wikipedia.org/wiki/Hovm%C3%B6ller_diagram).
```
sla_hov = ds.sla.mean(dim='longitude').load()
fig, ax = plt.subplots(figsize=(12, 4))
sla_hov.name = 'Sea Level Anomaly [m]'
sla_hov.transpose().plot(vmax=0.2, ax=ax)
```
We can see that most sea level rise is actually in the Southern Hemisphere.
## Sea Level Variability
We can examine the natural variability in sea level by looking at its standard deviation in time.
```
sla_std = ds.sla.std(dim='time').load()
sla_std.name = 'Sea Level Variability [m]'
ax = sla_std.plot()
_ = plt.title('Sea Level Variability')
```
| github_jupyter |
# Encoders: Binary Convolutional Example
We've seen how we can do classifiers on single and on series data and we've seen how we can build classifiers on series. The next logical step is to try and do some encoders on series data.
Much like the encoder examples on single transactions, we'll have an `Encoder` encoding/compressing the data and a `Decoder` decoding/decompressing the data. But rather than using linear layers, like for the single transactions, we'll be using some of the layers we saw in the series classifiers. We'll start with a __Convolutional__ example as that is the more straight-forward case.
Remember that __Convolutional__ layers slide a filter over the data, reconstructing the original input. (See the series/stacked/classifiers/*convolutional* classifier example for more information). The convolutions sort of compressed the data, each patch of data over which the filter slides gets reduced to a single number, we used *Torch* `Conv1d` layers.
That operation has an inverse, `ConvTranspose1d`. It gets its name because it is the transpose of the __convolutional matrix__ as used by `Conv1d` layers. We won't go into the technical details of this, but; the conv-filters do not actually slide over the data, that would be too slow, the 'sliding and multiplying' logic is implemented as matrix multiplication with a __convolutional matrix__. And by transposing that matrix we get an operation that does more or less the same but rather than shrinking the data, it 'expands' the data back out.

A Convolutional Encoder will take a series as input and will apply various __convolutional layers__ to condense that input into a latent representation. Other than with the *'single'* transaction encoders, this latent shape is a __2-D tensor__ like the input record. It's feature axis (depth/height) will be reduced. But note that the *time dimension (width)* will also be condensed.
The time is reduced according to formula; $Time Dimension = \frac {inputlength - kernelsize + 2 * padding} {stride} + 1$ applied in __each filter__; it is potentially applied multiple times.
The Convolutional Decoder does the exact opposite and reconstructs the latent dimension back to the size of the original input. It reconstructed the entire series, rather than a single transaction in the previous 'single' auto-encoder examples.
----
#### Note on the data set
The data set used here is not particularly complex and/or big. It's not really all that challenging to find the fraud. In an ideal world we'd be using more complex data sets to show the real power of Deep Learning. There are a bunch of PCA'ed data sets available, but the PCA obfuscates some of the elements that are useful.
*These examples are meant to show the possibilities, it's not so useful to interpret their performance on this data set*
# Imports
```
import torch
import numpy as np
import gc
import datetime as dt
import d373c7.features as ft
import d373c7.engines as en
import d373c7.pytorch as pt
import d373c7.pytorch.models as pm
import d373c7.plot as pl
```
## Set a random seed for Numpy and Torch
> Will make sure we always sample in the same way. Makes it easier to compare results. At some point it should been removed to test the model stability.
```
# Numpy
np.random.seed(42)
# Torch
torch.manual_seed(42)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
```
## Define base feature and read the File
The base features are features found in the input file. They need to be defined after which the file can be read using the `EnginePandasNumpy`. Using the `from_csv` method.
The `from_csv` method will read the file and return a Pandas DataFrame object
```
# Change this to read from another location
file = '../../../../data/bs140513_032310.csv'
step = ft.FeatureSource('step', ft.FEATURE_TYPE_INT_16)
customer = ft.FeatureSource('customer', ft.FEATURE_TYPE_STRING)
age = ft.FeatureSource('age', ft.FEATURE_TYPE_CATEGORICAL)
gender = ft.FeatureSource('gender', ft.FEATURE_TYPE_CATEGORICAL)
merchant = ft.FeatureSource('merchant', ft.FEATURE_TYPE_CATEGORICAL)
category = ft.FeatureSource('category', ft.FEATURE_TYPE_CATEGORICAL)
amount = ft.FeatureSource('amount', ft.FEATURE_TYPE_FLOAT)
fraud = ft.FeatureSource('fraud', ft.FEATURE_TYPE_INT_8)
base_features = ft.TensorDefinition(
'base',
[
step,
customer,
age,
gender,
merchant,
category,
amount,
fraud
])
amount_binned = ft.FeatureBin('amount_bin', ft.FEATURE_TYPE_INT_16, amount, 30)
# Function to calculate the date and time from the step
def step_to_date(step_count: int):
return dt.datetime(2020, 1, 1) + dt.timedelta(days=int(step_count))
date_time = ft.FeatureExpression('date', ft.FEATURE_TYPE_DATE_TIME, step_to_date, [step])
intermediate_features = ft.TensorDefinition(
'intermediate',
[
customer,
step,
age,
gender,
merchant,
category,
amount_binned,
fraud
])
amount_oh = ft.FeatureOneHot('amount_one_hot', amount_binned)
age_oh = ft.FeatureOneHot('age_one_hot', age)
gender_oh = ft.FeatureOneHot('gender_one_hot', gender)
merchant_oh = ft.FeatureOneHot('merchant_one_hot', merchant)
category_oh = ft.FeatureOneHot('category_one_hot', category)
fraud_label = ft.FeatureLabelBinary('fraud_label', fraud)
learning_features = ft.TensorDefinition(
'learning',
[
customer,
date_time,
age_oh,
gender_oh,
merchant_oh,
category_oh,
amount_oh
])
label = ft.TensorDefinition('label', [fraud_label])
model_features = ft.TensorDefinitionMulti([learning_features, label])
with en.EnginePandasNumpy(num_threads=8) as e:
df = e.from_csv(base_features, file, inference=False)
df = e.from_df(intermediate_features, df, inference=False)
trx_df = e.from_df(learning_features, df, inference=False)
lb_df = e.from_df(label, df, inference=False)
ser_np = e.to_series_stacked(
trx_df, learning_features, key_field=customer, time_field=date_time, length=5
)
lb_np = e.to_numpy_list(label, lb_df)
data_list = en.NumpyList(ser_np.lists + lb_np.lists)
learning_features.remove(customer)
learning_features.remove(date_time)
print('Data Shapes')
print(data_list.shapes)
print(data_list.dtype_names)
```
## Wrangle the data
Time to split the data. For time series data it is very important to keep the order of the data. Below split will start from the end and work it's way to the front of the data. Doing so the training, validation and test data are nicely colocated in time. You almost *never* want to plain shuffle time based data.
> 1. Split out a test-set of size `test_records`. This is used for model testing.
> 2. Split out a validation-set of size `validation_records`. It will be used to monitor overfitting during training
> 3. All the rest is considered training data.
For time-series we'll perform an additional action.
> 1. The series at the beginning of the data set will all be more or less empty as there is no history, that is not so useful during training, ideally we have records with history and complete series, sometimes named 'mature' series. We'll throw away the first couple of entries.
__Important__; please make sure the data is ordered in ascending fashion on a date(time) field. The split function does not order the data, it assumes the data is in the correct order.
For auto-encoders we perform a 5th step, all fraud records will be removed from the training and validation data. The auto-encoder will only see *non-fraud* records during training.
> 1. Remove fraud records from training and validation
```
test_records = 100000
val_records = 30000
maturation = 30000
train_data, val_data, test_data = data_list.split_time(val_records, test_records)
train_data = train_data[maturation:]
# Filter. Only keep non-fraud records with label 0.
train_data = train_data.filter_label(model_features, 0)
val_data = val_data.filter_label(model_features, 0)
print(f'Training Data shapes {train_data.shapes}')
print(f'Validation Data shapes {val_data.shapes}')
print(f'Test Data shapes {test_data.shapes}')
del df, trx_df, lb_df, ser_np, lb_np, data_list
gc.collect()
print('Done')
```
## Set-up Devices
```
device, cpu = pt.init_devices()
```
## Build the model
> In this example we use a `GeneratedAutoEncoder` model, the same model as we used in the 'single' encoder examples. But as we now have series, we can ask it to use the specialised +3-D tensor layers. We're asking it to use 2 convolutional layers. The encoder layer reduces to __32 features/channels with a kernel_size of 2__, the second layer further reduces to __6 features/channels with a kernel_size of 1__. The decoder layer uses the exact same layers but reversed.
```
# Setup Pytorch Datasets for the training and validation
batch_size = 128
train_ds = pt.NumpyListDataSetMulti(model_features, train_data)
val_ds = pt.NumpyListDataSetMulti(model_features, val_data)
# Wrap them in a Pytorch Dataloader
train_dl = train_ds.data_loader(cpu, batch_size, num_workers=2)
val_dl = val_ds.data_loader(cpu, batch_size, num_workers=2)
m = pm.GeneratedAutoEncoder(model_features, convolutional_layers=[(32, 2), (6, 1)])
print(m)
```
Grapically this model looks more or less like below. The 107 binary intput features are squeeze into a 6 x 4 block in 2 steps/layers. __6 for the number of features__ in the latent dimension and __4 because the time dimension__ gets squeezed in the first layer as we use a filter size of 2.
That latent 2D tensor gets expanded back to the 107 binary input features x 5 time series. This model will then use Binary Crossentropy loss to assess the difference between input and reconstructed output.

In order to get some intuition on how the reduction is done, we'll work out the math.
Our input layer has shape (5,107)
- 5 Timesteps
- 107 features
#### First layer
The __first__ convolutional layer is defined as having;
- 2 Kernel size
- 0 Padding, we're not doing padding obviously.
- 1 as default stride.
- 32 channels.
Therefore the output will be (4,32)
- __4__ because $(\frac {5 - 2 + 2 * 0} {1} + 1) = 4$
- __32__ because those are the stacked filter outputs
#### Second layer
Which is then processed through a __second__ convolutional layer having
- 1 Kernel size
- 0 Padding
- 1 as default stride
- 6 channels
Which will have output shape (4,6).
- __4__ because $(\frac {4 - 1 + 2 * 0} {1} + 1) = 4$
- __6__ because of the channels which are the stacked filter outputs.
# Start Training
### First find a decent Learning Rate.
> Create a trainer and run the find_lr function and plot. This functions iterates over the batches gradually increasing the learning rate from a minimum to a maximum learning rate.
```
t = pt.Trainer(m, device, train_dl, val_dl)
r = t.find_lr(1e-4, 1e-1, 200)
pl.TrainPlot().plot_lr(r)
```
## Start Training and plot the results
> We train for __5 epochs__ and __learning rate 2e-2__. That means we run over the total training data set a total of 5 times/epochs where the model learns, after each epoch we use the trained model and perform a test run on the validation set.
One thing we can observe is that there is quite a 'systematic' difference in the loss for training and validation. Intuitively we'd expect these to be closer together. There are only non-fraud records, so the loss should in the same ball-park. It's normal that in the beginning the training loss is bigger, the first steps will incur a lot of loss, but we'd expect them to converge in this case. We might go back and look at the data to see if we can spot a reason for this.
```
t = pt.Trainer(m, device, train_dl, val_dl)
h = t.train_one_cycle(5, 2e-2)
pl.TrainPlot().plot_history(h, fig_size=(10,10))
```
## Test the model on the test data
> Our first 'series' auto-encoder does not seem to do a bad job. As was the case with the 'single' transaction encoders it turn out that the fraud series (where the last payment is the fraud) are more difficult to reconstruct, thus tend to have higher scores.
```
test_ds = pt.NumpyListDataSetMulti(model_features, test_data)
test_dl = test_ds.data_loader(cpu, 128, num_workers=2)
ts = pt.Tester(m, device, test_dl)
tp = pl.TestPlot()
r = ts.score_plot()
tp.plot_scores(r, 50, fig_size=(6,6))
tp.plot_score_metrics(r, 20, fig_size=(6,6))
tp.print_classification_report(r, threshold=0.020)
tp.plot_confusion_matrix(r, fig_size=(6,6), threshold=0.020)
tp.plot_roc_curve(r, fig_size=(6,6))
tp.plot_precision_recall_curve(r, fig_size=(6,6))
```
# Conclusion
Being very careful about the data, as usual, but we see that asking the model to reconstruct the payments leading up to the fraud might have given the model more to work with. It's not really fair to compare this model (having much more parameters) to the models of single encoders. But these results might confirm our intuition that the transactions leading up to the fraud allow us to better asses abnormality.
Again, note this model __was not shown what fraud looks like__ during training, it only ever saw non-fraud transactions which is was asked to reconstruct.
And these models could probably be improved.
- We have not included information about the time difference between the transactions.
- We could make the series longer.
- And can use more complex convolutional blocks like 'inception' or 'resnet' style blocks.
- During testing on this data it seems the repetition of referential customer attributes like age and gender have a slight negative impact on the model performance.
| github_jupyter |
# Single Transmon - Floating
We'll be creating a 2D design and adding a single transmon qcomponent.
Create a standard pocket transmon qubit for a ground plane,
with two pads connected by a junction.
```
# So, let us dive right in. For convenience, let's begin by enabling
# automatic reloading of modules when they change.
%load_ext autoreload
%autoreload 2
import qiskit_metal as metal
from qiskit_metal import designs, draw
from qiskit_metal import MetalGUI, Dict, open_docs
# Each time you create a new quantum circuit design,
# you start by instantiating a QDesign class.
# The design class `DesignPlanar` is best for 2D circuit designs.
design = designs.DesignPlanar()
#Launch Qiskit Metal GUI to interactively view, edit, and simulate QDesign: Metal GUI
gui = MetalGUI(design)
# To force overwrite a QComponent with an existing name.
# This is useful when re-running cells in a notebook.
design.overwrite_enabled = True
```
### A transmon qubit
You can create a ready-made transmon qubit from the QComponent Library, `qiskit_metal.qlibrary.qubits`.
`transmon_pocket.py` is the file containing our qubit so `transmon_pocket` is the module we import.
The `TransmonPocket` class is our transmon qubit. Like all quantum components, `TransmonPocket` inherits from `QComponent`.
Connector lines can be added using the `connection_pads` dictionary.
Each connector pad has a name and a list of default properties.
```
from qiskit_metal.qlibrary.qubits.transmon_pocket import TransmonPocket
# Be aware of the default_options that can be overridden by user.
TransmonPocket.get_template_options(design)
transmon_options = dict(
pos_x = '1mm',
pos_y = '2mm',
orientation = '90',
connection_pads=dict(
a = dict(loc_W=+1, loc_H=-1, pad_width='70um', cpw_extend = '50um'),
b = dict(loc_W=-1, loc_H=-1, pad_width='125um', cpw_extend = '50um', pad_height='60um'),
c = dict(loc_W=+1, loc_H=+1, pad_width='110um', cpw_extend = '50um')
),
gds_cell_name='FakeJunction_01',
)
# Create a new Transmon Pocket object with name 'Q1'
q1 = TransmonPocket(design, 'Q1', options=transmon_options)
gui.rebuild() # rebuild the design and plot
gui.autoscale() # resize GUI to see QComponent
gui.zoom_on_components(['Q1']) #Can also gui.zoom_on_components([q1.name])
```
Let's see what the Q1 object looks like
```
q1 #print Q1 information
```
Save screenshot as a .png formatted file.
```
gui.screenshot()
# Screenshot the canvas only as a .png formatted file.
gui.figure.savefig('shot.png')
from IPython.display import Image, display
_disp_ops = dict(width=500)
display(Image('shot.png', **_disp_ops))
```
## Closing the Qiskit Metal GUI
```
gui.main_window.close()
```
| github_jupyter |
Copyright (c) Microsoft Corporation. All rights reserved.
# Tutorial: Use automated machine learning to build your regression model
This tutorial is **part two of a two-part tutorial series**. In the previous tutorial, you [prepared the NYC taxi data for regression modeling](regression-part1-data-prep.ipynb).
Now you're ready to start building your model with Azure Machine Learning service. In this part of the tutorial, you use the prepared data and automatically generate a regression model to predict taxi fare prices. By using the automated machine learning capabilities of the service, you define your machine learning goals and constraints. You launch the automated machine learning process. Then allow the algorithm selection and hyperparameter tuning to happen for you. The automated machine learning technique iterates over many combinations of algorithms and hyperparameters until it finds the best model based on your criterion.
In this tutorial, you learn the following tasks:
> * Set up a Python environment and import the SDK packages
> * Configure an Azure Machine Learning service workspace
> * Auto-train a regression model
> * Run the model locally with custom parameters
> * Explore the results
If you do not have an Azure subscription, create a [free account](https://aka.ms/AMLfree) before you begin.
> Code in this article was tested with Azure Machine Learning SDK version 1.0.0
## Prerequisites
To run the notebook you will need:
* [Run the data preparation tutorial](regression-part1-data-prep.ipynb).
* A Python 3.6 notebook server with the following installed:
* The Azure Machine Learning SDK for Python with `automl` and `notebooks` extras
* `matplotlib`
* The tutorial notebook
* A machine learning workspace
* The configuration file for the workspace in the same directory as the notebook
Navigate back to the [tutorial page](https://docs.microsoft.com/azure/machine-learning/service/tutorial-auto-train-models) for specific environment setup instructions.
## <a name="start"></a>Set up your development environment
All the setup for your development work can be accomplished in a Python notebook. Setup includes the following actions:
* Install the SDK
* Import Python packages
* Configure your workspace
### Install and import packages
If you are following the tutorial in your own Python environment, use the following to install necessary packages.
```shell
pip install azureml-sdk[automl,notebooks] matplotlib
```
Import the Python packages you need in this tutorial:
```
import azureml.core
import pandas as pd
from azureml.core.workspace import Workspace
import logging
import os
```
### Configure workspace
Create a workspace object from the existing workspace. A `Workspace` is a class that accepts your Azure subscription and resource information. It also creates a cloud resource to monitor and track your model runs.
`Workspace.from_config()` reads the file **aml_config/config.json** and loads the details into an object named `ws`. `ws` is used throughout the rest of the code in this tutorial.
After you have a workspace object, specify a name for the experiment. Create and register a local directory with the workspace. The history of all runs is recorded under the specified experiment and in the [Azure portal](https://portal.azure.com).
```
ws = Workspace.from_config()
# choose a name for the run history container in the workspace
experiment_name = 'automated-ml-regression'
# project folder
project_folder = './automated-ml-regression'
output = {}
output['SDK version'] = azureml.core.VERSION
output['Subscription ID'] = ws.subscription_id
output['Workspace'] = ws.name
output['Resource Group'] = ws.resource_group
output['Location'] = ws.location
output['Project Directory'] = project_folder
pd.set_option('display.max_colwidth', -1)
outputDf = pd.DataFrame(data = output, index = [''])
outputDf.T
```
## Explore data
Use the data flow object created in the previous tutorial. To summarize, part 1 of this tutorial cleaned the NYC Taxi data so it could be used in a machine learning model. Now, you use various features from the data set and allow an automated model to build relationships between the features and the price of a taxi trip. Open and run the data flow and review the results:
```
import azureml.dataprep as dprep
file_path = os.path.join(os.getcwd(), "dflows.dprep")
dflow_prepared = dprep.Dataflow.open(file_path)
dflow_prepared.get_profile()
```
You prepare the data for the experiment by adding columns to `dflow_x` to be features for our model creation. You define `dflow_y` to be our prediction value, **cost**:
```
dflow_X = dflow_prepared.keep_columns(['pickup_weekday','pickup_hour', 'distance','passengers', 'vendor'])
dflow_y = dflow_prepared.keep_columns('cost')
```
### Split data into train and test sets
Now you split the data into training and test sets by using the `train_test_split` function in the `sklearn` library. This function segregates the data into the x, **features**, dataset for model training and the y, **values to predict**, dataset for testing. The `test_size` parameter determines the percentage of data to allocate to testing. The `random_state` parameter sets a seed to the random generator, so that your train-test splits are always deterministic:
```
from sklearn.model_selection import train_test_split
x_df = dflow_X.to_pandas_dataframe()
y_df = dflow_y.to_pandas_dataframe()
x_train, x_test, y_train, y_test = train_test_split(x_df, y_df, test_size=0.2, random_state=223)
# flatten y_train to 1d array
y_train.values.flatten()
```
The purpose of this step is to have data points to test the finished model that haven't been used to train the model, in order to measure true accuracy. In other words, a well-trained model should be able to accurately make predictions from data it hasn't already seen. You now have the necessary packages and data ready for autotraining your model.
## Automatically train a model
To automatically train a model, take the following steps:
1. Define settings for the experiment run. Attach your training data to the configuration, and modify settings that control the training process.
1. Submit the experiment for model tuning. After submitting the experiment, the process iterates through different machine learning algorithms and hyperparameter settings, adhering to your defined constraints. It chooses the best-fit model by optimizing an accuracy metric.
### Define settings for autogeneration and tuning
Define the experiment parameters and models settings for autogeneration and tuning. View the full list of [settings](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train). Submitting the experiment with these default settings will take approximately 10-15 min, but if you want a shorter run time, reduce either `iterations` or `iteration_timeout_minutes`.
|Property| Value in this tutorial |Description|
|----|----|---|
|**iteration_timeout_minutes**|10|Time limit in minutes for each iteration. Reduce this value to decrease total runtime.|
|**iterations**|30|Number of iterations. In each iteration, a new machine learning model is trained with your data. This is the primary value that affects total run time.|
|**primary_metric**|spearman_correlation | Metric that you want to optimize. The best-fit model will be chosen based on this metric.|
|**preprocess**| True | By using **True**, the experiment can preprocess the input data (handling missing data, converting text to numeric, etc.)|
|**verbosity**| logging.INFO | Controls the level of logging.|
|**n_cross_validationss**|5| Number of cross-validation splits to perform when validation data is not specified.
```
automl_settings = {
"iteration_timeout_minutes" : 10,
"iterations" : 30,
"primary_metric" : 'spearman_correlation',
"preprocess" : True,
"verbosity" : logging.INFO,
"n_cross_validations": 5
}
```
Use your defined training settings as a parameter to an `AutoMLConfig` object. Additionally, specify your training data and the type of model, which is `regression` in this case.
```
from azureml.train.automl import AutoMLConfig
# local compute
automated_ml_config = AutoMLConfig(task = 'regression',
debug_log = 'automated_ml_errors.log',
path = project_folder,
X = x_train.values,
y = y_train.values.flatten(),
**automl_settings)
```
### Train the automatic regression model
Start the experiment to run locally. Pass the defined `automated_ml_config` object to the experiment. Set the output to `True` to view progress during the experiment:
```
from azureml.core.experiment import Experiment
experiment=Experiment(ws, experiment_name)
local_run = experiment.submit(automated_ml_config, show_output=True)
```
The output shown updates live as the experiment runs. For each iteration, you see the model type, the run duration, and the training accuracy. The field `BEST` tracks the best running training score based on your metric type.
## Explore the results
Explore the results of automatic training with a Jupyter widget or by examining the experiment history.
### Option 1: Add a Jupyter widget to see results
If you use a Jupyter notebook, use this Jupyter notebook widget to see a graph and a table of all results:
```
from azureml.widgets import RunDetails
RunDetails(local_run).show()
```
### Option 2: Get and examine all run iterations in Python
You can also retrieve the history of each experiment and explore the individual metrics for each iteration run. By examining RMSE (root_mean_squared_error) for each individual model run, you see that most iterations are predicting the taxi fair cost within a reasonable margin ($3-4).
```
children = list(local_run.get_children())
metricslist = {}
for run in children:
properties = run.get_properties()
metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}
metricslist[int(properties['iteration'])] = metrics
rundata = pd.DataFrame(metricslist).sort_index(1)
rundata
```
## Retrieve the best model
Select the best pipeline from our iterations. The `get_output` method on `automl_classifier` returns the best run and the fitted model for the last fit invocation. By using the overloads on `get_output`, you can retrieve the best run and fitted model for any logged metric or a particular iteration:
```
best_run, fitted_model = local_run.get_output()
print(best_run)
print(fitted_model)
```
## Test the best model accuracy
Use the best model to run predictions on the test dataset to predict taxi fares. The function `predict` uses the best model and predicts the values of y, **trip cost**, from the `x_test` dataset. Print the first 10 predicted cost values from `y_predict`:
```
y_predict = fitted_model.predict(x_test.values)
print(y_predict[:10])
```
Create a scatter plot to visualize the predicted cost values compared to the actual cost values. The following code uses the `distance` feature as the x-axis and trip `cost` as the y-axis. To compare the variance of predicted cost at each trip distance value, the first 100 predicted and actual cost values are created as separate series. Examining the plot shows that the distance/cost relationship is nearly linear, and the predicted cost values are in most cases very close to the actual cost values for the same trip distance.
```
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(14, 10))
ax1 = fig.add_subplot(111)
distance_vals = [x[4] for x in x_test.values]
y_actual = y_test.values.flatten().tolist()
ax1.scatter(distance_vals[:100], y_predict[:100], s=18, c='b', marker="s", label='Predicted')
ax1.scatter(distance_vals[:100], y_actual[:100], s=18, c='r', marker="o", label='Actual')
ax1.set_xlabel('distance (mi)')
ax1.set_title('Predicted and Actual Cost/Distance')
ax1.set_ylabel('Cost ($)')
plt.legend(loc='upper left', prop={'size': 12})
plt.rcParams.update({'font.size': 14})
plt.show()
```
Calculate the `root mean squared error` of the results. Use the `y_test` dataframe. Convert it to a list to compare to the predicted values. The function `mean_squared_error` takes two arrays of values and calculates the average squared error between them. Taking the square root of the result gives an error in the same units as the y variable, **cost**. It indicates roughly how far the taxi fare predictions are from the actual fares:
```
from sklearn.metrics import mean_squared_error
from math import sqrt
rmse = sqrt(mean_squared_error(y_actual, y_predict))
rmse
```
Run the following code to calculate mean absolute percent error (MAPE) by using the full `y_actual` and `y_predict` datasets. This metric calculates an absolute difference between each predicted and actual value and sums all the differences. Then it expresses that sum as a percent of the total of the actual values:
```
sum_actuals = sum_errors = 0
for actual_val, predict_val in zip(y_actual, y_predict):
abs_error = actual_val - predict_val
if abs_error < 0:
abs_error = abs_error * -1
sum_errors = sum_errors + abs_error
sum_actuals = sum_actuals + actual_val
mean_abs_percent_error = sum_errors / sum_actuals
print("Model MAPE:")
print(mean_abs_percent_error)
print()
print("Model Accuracy:")
print(1 - mean_abs_percent_error)
```
From the final prediction accuracy metrics, you see that the model is fairly good at predicting taxi fares from the data set's features, typically within +- $3.00. The traditional machine learning model development process is highly resource-intensive, and requires significant domain knowledge and time investment to run and compare the results of dozens of models. Using automated machine learning is a great way to rapidly test many different models for your scenario.
## Clean up resources
>The resources you created can be used as prerequisites to other Azure Machine Learning service tutorials and how-to articles.
If you do not plan to use the resources you created, delete them, so you do not incur any charges:
1. In the Azure portal, select **Resource groups** on the far left.
1. From the list, select the resource group you created.
1. Select **Delete resource group**.
1. Enter the resource group name. Then select **Delete**.
## Next steps
In this automated machine learning tutorial, you did the following tasks:
* Configured a workspace and prepared data for an experiment.
* Trained by using an automated regression model locally with custom parameters.
* Explored and reviewed training results.
[Deploy your model](https://docs.microsoft.com/azure/machine-learning/service/tutorial-deploy-models-with-aml) with Azure Machine Learning.

| github_jupyter |
```
# default_exp misc_splitters
#hide
#ci
!pip install -Uqq fastai --upgrade
#hide
#local
%cd ..
# from my_timesaver_utils.profiling import *
%cd nbs
```
# Misc Splitters
> splitters for reducing dataset sizes
```
#hide
#local
%reload_ext autoreload
%autoreload 2
%matplotlib inline
#export
# from my_timesaver_utils.profiling import *
#export
import warnings
FASTAI_AVAILABLE = True
try:
from fastcore.foundation import L
except ImportError as e:
FASTAI_AVAILABLE = False
warnings.warn('fastai package not installed, callback simulated')
#export
if not FASTAI_AVAILABLE:
def L(*args,**kwargs):
return list(*args)
#export
def DumbFixedSplitter(train_pct):
'A splitter that takes the 1st `train_pct` as the train elements'
assert 0 < train_pct < 1
def _inner(o):
o_len = len(o)
train_len = int(o_len*train_pct)
idxs = L(list(range(o_len)))
return idxs[:train_len], idxs[train_len:]
return _inner
#export
def SubsetPercentageSplitter(main_splitter, train_pct=0.5, valid_pct=None, randomize=False, seed=None):
"Take fixed pct of `splits` with `train_pct` and `valid_pct` from main splitter"
assert main_splitter is not None
assert 0 <= train_pct <= 1
valid_pct = train_pct if valid_pct is None else valid_pct
assert 0 <= valid_pct <= 1
if randomize:
if seed is not None:
rng = random.Random(seed)
else:
rng = random.Random(random.randint(0,2**32-1))
def _inner(o):
train_idxs, valid_idxs = main_splitter(o)
train_len = int(len(train_idxs)*train_pct)
valid_len = int(len(valid_idxs)*valid_pct)
if randomize:
train_idxs = rng.sample(train_idxs, train_len)
valid_idxs = rng.sample(valid_idxs, valid_len)
return train_idxs[:train_len],valid_idxs[:valid_len]
return _inner
```
### Example Usage
```
from fastai.vision.all import *
mlist = list(range(20)); mlist
df_splitter = DumbFixedSplitter(0.8)
t1_train, t2_valid = df_splitter(mlist); t1_train
t2_valid
fs_splitter = SubsetPercentageSplitter(df_splitter, randomize=True, seed=42)
ft1_train, ft2_valid = fs_splitter(mlist)
ft1_train
ft2_valid
path = untar_data(URLs.MNIST_TINY)
data = DataBlock(
blocks=(ImageBlock,CategoryBlock),
get_items=get_image_files,
get_y=parent_label,
splitter=SubsetPercentageSplitter(
GrandparentSplitter(),
train_pct=0.02,randomize=True, seed=42
),
item_tfms=Resize(28),
batch_tfms=[]
)
data.summary(path)
dls = data.dataloaders(path, bs=4)
dls.show_batch()
dls.c
len(dls.train), len(dls.valid)
len(dls.train.items)
len(dls.valid.items)
learner = cnn_learner(dls, resnet18, metrics=accuracy)
learner.fit(5)
```
| github_jupyter |
```
%load_ext autoreload
%autoreload 2
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import torch
device = 'cuda' if torch.cuda.is_available() else 'cpu'
import os,sys
opj = os.path.join
from copy import deepcopy
import pickle as pkl
import pandas as pd
import random
sys.path.append('../../src')
sys.path.append('../../src/dsets/cosmology')
from dset import get_dataloader
from viz import viz_im_r, cshow, viz_filters
from sim_cosmology import p, load_dataloader_and_pretrained_model
from losses import get_loss_f
from train import Trainer, Validator
# wt modules
from wavelet_transform import Wavelet_Transform, Attributer, get_2dfilts, initialize_filters
from utils import tuple_L1Loss, tuple_L2Loss, thresh_attrs, viz_list
```
# load results
```
dirs = ["vary_lamL1attr_seeds_initialized"]
results = []
models = []
for i in range(len(dirs)):
# load results
out_dir = opj("/home/ubuntu/local-vae/notebooks/ex_cosmology/results", dirs[i])
fnames = sorted(os.listdir(out_dir))
results_list = []
models_list = []
for fname in fnames:
if fname[-3:] == 'pkl':
results_list.append(pkl.load(open(opj(out_dir, fname), 'rb')))
if fname[-3:] == 'pth':
wt = Wavelet_Transform(wt_type='DWT', wave='db3', mode='symmetric', device='cuda', J=5)
wt.load_state_dict(torch.load(opj(out_dir, fname)))
models_list.append(wt)
results.append(pd.DataFrame(results_list))
models.append(models_list)
```
## load data and model
```
# get dataloader and model
(train_loader, test_loader), model = load_dataloader_and_pretrained_model(p, img_size=256)
torch.manual_seed(p.seed)
im = iter(test_loader).next()[0][0:64].to(device)
```
## initialize filter
```
# wavelet transform with initialization
wt_orig = Wavelet_Transform(wt_type='DWT', wave='db3', mode='symmetric', device='cuda', J=5)
seed = 100
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
wt = initialize_filters(wt_orig, init_level=1, noise_level=0.1)
filt = get_2dfilts(wt)
viz_im_r(im[0], wt.inverse(wt(im))[0])
print("Recon={:.5f}".format(torch.norm(wt.inverse(wt(im)) - im)**2/im.size(0)))
viz_list(filt, figsize=(4,4))
```
# Plotting
```
index = 18
wt = models[0][index]
res = results[0]
filt = get_2dfilts(wt)
viz_list(filt, figsize=(4,4))
viz_im_r(im[0], wt.inverse(wt(im))[0])
print("Recon={:.5f}".format(torch.norm(wt.inverse(wt(im)) - im)**2/im.size(0)))
plt.plot(np.log(res['train_losses'][index]))
plt.xlabel("epochs")
plt.ylabel("log train loss")
plt.title('Log-train loss vs epochs')
plt.show()
lamb_seq = np.round(np.geomspace(1, 100, 20), 5)
print('Original filter: Test recon-error={:.6f} Test L1-penalty={:.6f}'.format(0, 93.83803))
for i in range(len(models[0])):
print('Lambda={:.6f} Test recon-error={:.6f} Test L1-penalty={:.6f}'.format(lamb_seq[i], res['val_rec_loss'][i], res['val_L1attr_loss'][i]))
```
| github_jupyter |
```
#Use this command to run it on floydhub: floyd run --gpu --env tensorflow-1.4 --data emilwallner/datasets/imagetocode/2:data --data emilwallner/datasets/html_models/1:weights --mode jupyter
from os import listdir
from numpy import array
from keras.preprocessing.text import Tokenizer, one_hot
from keras.preprocessing.sequence import pad_sequences
from keras.models import Model
from keras.utils import to_categorical
from keras.layers import Embedding, TimeDistributed, RepeatVector, LSTM, concatenate , Input, Reshape, Dense, Flatten
from keras.preprocessing.image import array_to_img, img_to_array, load_img
from keras.applications.inception_resnet_v2 import InceptionResNetV2, preprocess_input
import numpy as np
# Load the images and preprocess them for inception-resnet
images = []
all_filenames = listdir('resources/images/')
all_filenames.sort()
for filename in all_filenames:
images.append(img_to_array(load_img('resources/images/'+filename, target_size=(299, 299))))
images = np.array(images, dtype=float)
images = preprocess_input(images)
# Run the images through inception-resnet and extract the features without the classification layer
IR2 = InceptionResNetV2(weights=None, include_top=False, pooling='avg')
IR2.load_weights('/data/models/inception_resnet_v2_weights_tf_dim_ordering_tf_kernels_notop.h5')
features = IR2.predict(images)
# We will cap each input sequence to 100 tokens
max_caption_len = 100
# Initialize the function that will create our vocabulary
tokenizer = Tokenizer(filters='', split=" ", lower=False)
# Read a document and return a string
def load_doc(filename):
file = open(filename, 'r')
text = file.read()
file.close()
return text
# Load all the HTML files
X = []
all_filenames = listdir('resources/html/')
all_filenames.sort()
for filename in all_filenames:
X.append(load_doc('resources/html/'+filename))
# Create the vocabulary from the html files
tokenizer.fit_on_texts(X)
# Add +1 to leave space for empty words
vocab_size = len(tokenizer.word_index) + 1
# Translate each word in text file to the matching vocabulary index
sequences = tokenizer.texts_to_sequences(X)
# The longest HTML file
max_length = max(len(s) for s in sequences)
# Intialize our final input to the model
X, y, image_data = list(), list(), list()
for img_no, seq in enumerate(sequences):
for i in range(1, len(seq)):
# Add the entire sequence to the input and only keep the next word for the output
in_seq, out_seq = seq[:i], seq[i]
# If the sentence is shorter than max_length, fill it up with empty words
in_seq = pad_sequences([in_seq], maxlen=max_length)[0]
# Map the output to one-hot encoding
out_seq = to_categorical([out_seq], num_classes=vocab_size)[0]
# Add and image corresponding to the HTML file
image_data.append(features[img_no])
# Cut the input sentence to 100 tokens, and add it to the input data
X.append(in_seq[-100:])
y.append(out_seq)
X, y, image_data = np.array(X), np.array(y), np.array(image_data)
# Create the encoder
image_features = Input(shape=(1536,))
image_flat = Dense(128, activation='relu')(image_features)
ir2_out = RepeatVector(max_caption_len)(image_flat)
# Create the decoder
language_input = Input(shape=(max_caption_len,))
language_model = Embedding(vocab_size, 200, input_length=max_caption_len)(language_input)
language_model = LSTM(256, return_sequences=True)(language_model)
language_model = LSTM(256, return_sequences=True)(language_model)
language_model = TimeDistributed(Dense(128, activation='relu'))(language_model)
# Create the decoder
decoder = concatenate([ir2_out, language_model])
decoder = LSTM(512, return_sequences=True)(decoder)
decoder = LSTM(512, return_sequences=False)(decoder)
decoder_output = Dense(vocab_size, activation='softmax')(decoder)
# Compile the model
model = Model(inputs=[image_features, language_input], outputs=decoder_output)
#model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
model.load_weights("/weights/org-weights-epoch-0900---loss-0.0000.hdf5")
# Train the neural network
#model.fit([image_data, X], y, batch_size=64, shuffle=False, epochs=2)
# map an integer to a word
def word_for_id(integer, tokenizer):
for word, index in tokenizer.word_index.items():
if index == integer:
return word
return None
# generate a description for an image
def generate_desc(model, tokenizer, photo, max_length):
# seed the generation process
in_text = 'START'
# iterate over the whole length of the sequence
for i in range(900):
# integer encode input sequence
sequence = tokenizer.texts_to_sequences([in_text])[0][-100:]
# pad input
sequence = pad_sequences([sequence], maxlen=max_length)
# predict next word
yhat = model.predict([photo,sequence], verbose=0)
# convert probability to integer
yhat = np.argmax(yhat)
# map integer to word
word = word_for_id(yhat, tokenizer)
# stop if we cannot map the word
if word is None:
break
# append as input for generating the next word
in_text += ' ' + word
# Print the prediction
print(' ' + word, end='')
# stop if we predict the end of the sequence
if word == 'END':
break
return
# Load and image, preprocess it for IR2, extract features and generate the HTML
test_image = img_to_array(load_img('resources/images/86.jpg', target_size=(299, 299)))
test_image = np.array(test_image, dtype=float)
test_image = preprocess_input(test_image)
test_features = IR2.predict(np.array([test_image]))
generate_desc(model, tokenizer, np.array(test_features), 100)
```
| github_jupyter |
```
import codecs
import csv
import time
import os
import re
import gzip
import pandas as pd
import numpy as np
PATH_TO_DATA = 'Data/'
PATH_TO_DATA_UK = PATH_TO_DATA+"ukwiki/"
UKWIKI_ART_FNMS = []
for file in os.listdir(PATH_TO_DATA_UK):
if re.match(r"ukwiki-20180620-pages-meta-current\d{2}-p\d+p\d+.xml_art.csv.gz", file):
UKWIKI_ART_FNMS.append(file)
def unpack(file_name):
file_name_new = file_name.replace(".gz","")
with gzip.open(file_name, 'rb') as f_in, open(file_name_new, 'wb') as f_out:
f_out.writelines(f_in)
return file_name_new
def pack_and_remove(file_name):
file_name_new = file_name+'.gz'
with open(file_name, 'rb') as f_in, gzip.open(file_name_new, 'wb') as f_out:
f_out.writelines(f_in)
os.remove(file_name)
return file_name_new
total_links_count = 0
total_red_links_count = 0
df_title_count = None
for fn in UKWIKI_ART_FNMS:
fn = PATH_TO_DATA_UK+fn
print(fn)
fn_new = unpack(fn)
df_articles = pd.read_csv(fn_new, encoding='UTF-8', quotechar="\"")
total_links_count += df_articles.shape[0]
df_red_links = df_articles[df_articles['is_red_link'] == True]
total_red_links_count += df_red_links.shape[0]
df_title_count_tmp = pd.DataFrame(df_red_links.groupby('link_val').link_val.count())
df_title_count_tmp.columns = ['link']
df_title_count_tmp = df_title_count_tmp.reset_index(col_level=1)
df_title_count_tmp.columns = ['link_title', 'in_count']
if df_title_count is not None:
df_title_count = df_title_count.append(df_title_count_tmp)
#print("append")
else:
df_title_count = df_title_count_tmp
#print("assign")
df_title_count = df_title_count.groupby('link_title').in_count.sum().copy()
df_title_count.columns = ['link']
df_title_count = df_title_count.reset_index()
df_title_count.columns = ['link_title', 'in_count']
print("total_links_count : {}".format(total_links_count))
print("total_red_links_count : {}".format(total_red_links_count))
print("df_title_count size: {}".format(df_title_count.shape))
os.remove(fn_new)
df_title_count = df_title_count.sort_values(['in_count'], ascending=[0])
df_title_count.to_csv(PATH_TO_DATA_UK+'ukwiki-20180620-red_name_count.csv', index = False, encoding='UTF-8', quotechar="\"")
df_title_count
df_title_count.describe()
df_count_by_count = pd.DataFrame(df_title_count.groupby('in_count').in_count.count())
df_count_by_count.columns = ['link']
df_count_by_count = df_count_by_count.reset_index()
df_count_by_count.columns = ['count', 'in_count']
df_count_by_count = df_count_by_count.sort_values(['count'], ascending=[1])
df_count_by_count.head()
df_count_by_count.describe()
df_count_by_count.to_csv(PATH_TO_DATA_UK+'ukwiki-20180620-red_count_by_count.csv', index = False, encoding='UTF-8', quotechar="\"")
```
| github_jupyter |
# Introduction
The goal of this analysis is to understand the Discord [66DaysofData](https://www.66daysofdata.com/) community created by [Ken Jee](https://www.youtube.com/channel/UCiT9RITQ9PW6BhXK0y2jaeg).
Where are they coming from?
What are the common question?
How many people give up during the challenge progress?
What are the most used programming language?
Once we identify the most common question we could create a bot to answer these questions automatically.
Some quick ideas are
* (1) visualizing data over time
* (2) Sentiment
* (3) Wordcloud
* (4) Chat bot?
* (5) Common questions
#Method
The discords messages were obtained using a bot developed by Thiago Rodrigues and described in this [article](https://levelup.gitconnected.com/how-to-gather-message-data-using-a-discord-bot-from-scratch-with-python-2fe239da3bcd).
The analysis was performed with Python using Google Colaboratory.
# Initialize
```
# Load libraries
from google.colab import drive # to load data from google drive
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt # ploting the data
import seaborn as sns # ploting the data
import base64 # for hashing
import hashlib # for hasing
import os # For files operations
import datetime # For time serie analysis
import spacy # For NLP analysis
spacy.prefer_gpu()
nlp = spacy.load("en_core_web_sm")
import re
# Mount the drive folder
drive.mount("/content/drive")
# Load the data
introduction = pd.read_csv('/content/drive/MyDrive/Data_science/66DaysofData/Discord_server/Data/Introduction_20211117.csv')
progress = pd.read_csv('/content/drive/MyDrive/Data_science/66DaysofData/Discord_server/Data/Progress_20211117.csv')
```
# Data Cleaning
```
# Anomymize the dataset
# Create a hash function to remove name fo the people posting
# See https://towardsdatascience.com/anonymizing-data-sets-c4602e581a35
# The other challenge is waht to do is people give their full name in the text of the post?
# We could use Spacy NER to detect names and remove them from the text
# See https://stackoverflow.com/questions/51178961/hash-each-row-of-pandas-dataframe-column-using-apply
introduction['author'] = introduction['author'].astype(str).str.encode('UTF-8')\
.apply(lambda x: base64.b64encode(hashlib.sha1(x).digest()))
progress['author'] = progress['author'].astype(str).str.encode('UTF-8')\
.apply(lambda x: base64.b64encode(hashlib.sha1(x).digest()))
introduction = introduction.drop('Unnamed: 0', 1)
progress = progress.drop('Unnamed: 0', 1)
```
# What is the average number of post by author?
```
# See https://www.datasciencemadesimple.com/group-by-count-in-pandas-dataframe-python-2/
# See https://gist.github.com/conormm/fd8b1980c28dd21cfaf6975c86c74d07
count = introduction.groupby(['author'])['content'].count().reset_index()
title = 'Average number of post by author in the Introduction channel'
plt.figure(figsize=(8,8))
sns.set(font_scale=1.25)
sns.set_style("white")
sns.histplot(data=count, x='content', binwidth=1, color = "#654874")
plt.title(title)
plt.ioff()
```
In the introduction channel, a majority of user post one message as you would expect. Some users post multiple messages and up to 40. Those are likely from the admins.
```
count = progress.groupby(['author'])['content'].count().reset_index()
title = 'Number of post by author in the Progress channel'
plt.figure(figsize=(8,8))
sns.set(font_scale=1.25)
sns.set_style("white")
sns.histplot(data=count, x='content', binwidth=10, color = "#654874")
plt.title(title)
plt.ioff()
```
The histogram shows that most users have posted between 1 and 10 messages in the progress channel. One user had published more than 400 posts. After checking this corresponded to the level bot and I removed it from the analysis.
```
# Remove entries from the bot: b'vUObaU0Rsq0TCsDL1e9X0BY8oi0='
# see https://heads0rtai1s.github.io/2020/11/05/r-python-dplyr-pandas/
# see https://www.statology.org/pandas-to-string/
title = 'Number of post by author in the Progress channel'
progress['author'] = progress['author'].astype(str) # convert author so string. necessary because hashing caused an issue there.
progress['content'] = progress['content'].astype(str)
progress = progress.loc[progress.author != "b'QEb9TFHb5gXlkxkvrvwaHZRMS/w='"]
# Print the cout to confirm bot removal from the dataset
count = progress.groupby(['author'])['content'].count().reset_index()
plt.figure(figsize=(8,8))
sns.set(font_scale=1.25)
sns.set_style("white")
sns.histplot(data=count, x='content', binwidth=10, color = "#654874");
plt.title(title)
plt.ioff()
```
This updated histogram shows that most users were likely between day 1 and day 40 of the challenge. Some users appeared to have been already at day 140 of the challenge. It also possible that those users are responding to other people progress.
# How is the number of messages evolving with time?
```
title = 'Number of post by author over time in the Introduction channel'
introduction['author'] = introduction['author'].astype(str) # convert author to string. necessary because hashing caused an issue there.
introduction['content'] = introduction['content'].astype(str)
# see https://www.marsja.se/pandas-convert-column-to-datetime/
# convert column to datetime pandas
introduction['time'] = pd.to_datetime(introduction['time'])
introduction["time_YMD"] = introduction["time"].apply( lambda introduction :
datetime.datetime(year=introduction.year, month=introduction.month, day=introduction.day))
# Count post by Days, Weeks, Months...
# See http://blog.josephmisiti.com/group-by-datetimes-in-pandas
count = introduction.groupby(['time_YMD'])['content'].count().reset_index()
# Plot the number of pots by day
# Goup the dataframe by day
# Print number of post each day
# See recent work on Google Analytic with time serie
# See recent work DSGO https://github.com/wguesdon/66DaysOfData/blob/master/DGSO/DGSO_v01_03.ipynb
# See https://stackoverflow.com/questions/56150437/how-to-plot-a-time-series-graph-using-seaborn-or-plotly
# See https://www.earthdatascience.org/courses/use-data-open-source-python/use-time-series-data-in-python/date-time-types-in-pandas-python/customize-dates-matplotlib-plots-python/
x='time_YMD'
y='content'
plt.figure(figsize=(40,20))
sns.lineplot(x=x, y=y, data=count, color="#654874");
plt.xticks(rotation=30);
plt.title(title, fontsize = 24)
plt.ioff()
```
We can see here that there was a massing number of posts at the beginning of the server, followed by a sharp decline. There is a second pic that I suppose coincide with the announcement of the 66 Days round2.
```
title = 'Number of post by author over time in the Progress channel'
progress['author'] = progress['author'].astype(str) # convert author to string. necessary because hashing caused an issue there.
progress['content'] = progress['content'].astype(str)
# see https://www.marsja.se/pandas-convert-column-to-datetime/
# convert column to datetime pandas
progress['time'] = pd.to_datetime(progress['time'])
progress["time_YMD"] = progress["time"].apply( lambda progress :
datetime.datetime(year=progress.year, month=progress.month, day=progress.day))
# Count post by Days, Weeks, Months...
# See http://blog.josephmisiti.com/group-by-datetimes-in-pandas
count = progress.groupby(['time_YMD'])['content'].count().reset_index()
x='time_YMD'
y='content'
plt.figure(figsize=(40,20))
sns.lineplot(x=x, y=y, data=count, color="#654874");
plt.xticks(rotation=30);
plt.title(title, fontsize = 24)
plt.ioff()
```
The progress distribution shows two pics. I suppose that the second pic happened after Ken started round 2 of the 66DaysofData challenge.
# What are the most common locations from users?
```
# Create a function to extract the first location and add to a column
# See https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html
# see https://thispointer.com/pandas-apply-a-function-to-single-or-selected-columns-or-rows-in-dataframe/
def add_country(x):
doc = nlp(x)
gpe = [] # countries, cities, states
for ent in doc.ents:
if (ent.label_ == 'GPE'):
gpe.append(ent.text)
if (len(gpe) >= 1):
return (gpe[0])
else:
return ('none')
introduction['country'] = introduction['content'].apply(add_country)
# https://datatofish.com/lowercase-pandas-dataframe/
introduction['country'] = introduction['country'].str.lower()
df = introduction.loc[introduction['country'] != "none"]
# Count post by Days, Weeks, Months...
# See http://blog.josephmisiti.com/group-by-datetimes-in-pandas
count = df.groupby(['country'])['content'].count().reset_index()
count = count.sort_values('content', ascending=False)
count = count.loc[count['country'] != "python"]
count = count.loc[count['country'] != "ds"]
count = count.loc[count['country'] != "tableau"]
count = count.loc[count['content'] > 2]
count = count.sort_values('content', ascending=False)
data = count
x="content"
y="country"
title = ''
plt.figure(figsize=(10, 10))
sns.set(font_scale=1.25)
sns.set_style("white")
sns.barplot(x=x, y=y, data=data, color = "#654874")
plt.title(title)
plt.ioff()
```
At the time, the function does not differentiate between country and town. Countries can be spelt differently like UK or United Kingdom.
From the extracted locations, India, Nigeria, Brazil, Indonesia and Canada are the most common.
# How are the days distributed in the challenge channel?
```
# from kennn in #python
# See https://docs.python.org/3/howto/regex.html
def extract_day(text):
days = []
text = text.lower()
# Remove special characters
text = re.sub('[^A-Za-z0-9]+', '', text)
# Identify Days
days = re.findall(r'day[\s]+[\d]+|day[\d]+', text)
if (len(days) >= 1):
# If day is identified extract the number
days = re.findall(r'[\d]+', days[0])
return (days[0])
else:
return ('none')
# Apply extract day the content column to extract the day.
# next step is to exract numbers from this column
progress['Day'] = progress['content'].apply(extract_day)
progress = progress.loc[progress['Day'] != 'none']
count = progress.groupby(['Day'])['content'].count().reset_index()
count = count.sort_values('Day', ascending=False)
# See https://stackoverflow.com/questions/53654080/remove-the-leading-zero-before-a-number-in-python
# See https://datatofish.com/string-to-integer-dataframe/
count['Day'] = count['Day'].astype(str)
count = count.loc[count['Day'] != 'none']
count['Day'] = count['Day'].astype(int)
# At the time the data. was collected noone could have done more than 3 months of the challenge
count = count.loc[(count['content'] > 1) & (count['Day'] < 100)]
# see https://stackoverflow.com/questions/22005911/convert-columns-to-string-in-pandas
# Add a count group.by step
count = count.groupby(by=["Day"], dropna=False).count().reset_index()
data = count
y="content"
x="Day"
plt.figure(figsize=(8, 8))
sns.set(font_scale=1.25)
sns.set_style("white")
sns.histplot(data=data, x=x, color = "#654874")
plt.title(title)
plt.ioff()
```
The distributions of the different days in the progress channel seem equally distributed. This seems to indicate that there is no drop off during the challenge.
# References
* [How to Gather Message Data Using a Discord Bot From Scratch With Python](https://levelup.gitconnected.com/how-to-gather-message-data-using-a-discord-bot-from-scratch-with-python-2fe239da3bcd)
| github_jupyter |
```
import tensorflow as tf
from tensorflow import keras
import basecaller
import numpy as np
import csv
print(tf.__version__)
"""
this function provides information about the array
"""
def array_inspect(x):
print ("Shape is",(x.shape))
print(("Length is",len(x)))
print(("Dimension is",x.ndim))
print(("Total Size is",x.size))
print(("Type is",x.dtype))
print(("Type Name is",x.dtype.name))
#print(("Mean is",(x).mean))
tensor=[]
reads=[]
sig=[]
for x in range(10):
with open('concat_{}.csv'.format(x)) as csvfile:
concat = csv.reader(csvfile, delimiter=' ')
for row in concat:
r=(''.join(row))
tensor.append(r)
for x in range(len(tensor)):
#print(tensor[0])
b=(tensor[x][:100:25])
reads.append(b)
c=(tensor[x][100:])
#print(c)
sig.append(c)
print(reads) # this changes the array to a set and removes all the duplicate calls
print("Training entries: {}, labels: {}".format(len(tensor), len(tensor)))
class Reader:
num_of_reads=0
def __init__(self, first, second, third, fourth):
self.first = first
self.second = second
self.third = third
self.fourth = fourth
self.fourmer = first + second + third + fourth
Reader.num_of_reads+=1 # only do this where there is no case when you want to change a single instance
def fourmerstring(self):
return '{}{}{}{}'.format(self.first, self.second, self.third, self.fourth)
ID=[]
for x in range (10):
for y in range(len(reads[x])):
a = Reader(reads[y][0], reads[y][1],reads[y][2], reads[y][3])
ID.append(a)
class Employee:
num_of_emps = 0
raise_amount = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first +last+ '@company.com'
Employee.num_of_emps+=1 # only do this where there is no case when you want to change a single instance
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)
emp_1 = Employee('Corey', 'Schafer', 5000)
emp_2 = Employee ('Michael', 'Jochum', 6000)
Employee.fullname(emp_1)
emp_1.apply_raise()
#Employee.raise_amount = 1.05 #This changes the raise amount to the class and all the instances!
emp_1.raise_amount = 1.05
# this returns a new raise amount for a single instance one only (instead of the classes raise amount)
print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)
print(emp_1.__dict__) #This will print out everything possible attribute we can call from the class
print(Employee.num_of_emps)
# input shape is the vocabulary count used for the movie reviews (10,000 words)
vocab_size = 10000
model = keras.Sequential()
model.add(keras.layers.Embedding(vocab_size, 16))
model.add(keras.layers.GlobalAveragePooling1D())
model.add(keras.layers.Dense(16, activation=tf.nn.relu))
model.add(keras.layers.Dense(1, activation=tf.nn.sigmoid))
model.summary()
model.compile(optimizer=tf.train.AdamOptimizer(),
loss='binary_crossentropy',
metrics=['accuracy'])
x_val =np.int64((sig[:10])) #I'm trying to convert my reads and sig to tensor here and its not working
partial_x_train = list(sig[10:])
y_val =list(reads[:10])
partial_y_train = list(reads[10:])
print(x_val[0])
array_inspect(x_val)
history = model.fit(partial_x_train,
partial_y_train,
epochs=40,
batch_size=512,
validation_data=(x_val, y_val),
verbose=1)
```
| github_jupyter |
# Tutorial 6
**CS3481 Fundamentals of Data Science**
*Semester B 2019/20*
___
**Instructions:**
- same as [Tutorial 1](http://bit.ly/CS3481T1).
- submit your answers through [uReply](https://cityu.ed2.mobi/student/mobile_index.php) section number **LM963**.
___
## Exercise 1 (submit via Canvas discussion page)
Complete the following exercises slightly modified from [[Witten11]](https://ebookcentral.proquest.com/lib/cityuhk/reader.action?docID=634862&ppg=606) **Section 17.3 Visualizing 1R** from **Ex 17.3.1** to **17.3.4**.
**Exercise 17.3.1.** Explain the plot based on what you know about 1R. ( Hint: Use the Explorer interface to look at the rule set that 1R generates for this data.)
___
**Answer**
___
**Exercise 17.3.2.** Study the effect of the minBucketSize parameter on the classifier by regenerating the plot with values of 1, and then ~20~ **60**, and then some critical values in between. ~Describe what you see, and explain it.~ **Look for the smallest critical value of the `minBucketSize` where the decision boundaries begin to change as `minBucketSize` increases. The critical value should be larger than 20.**
[*Hint: You could speed things up by using the Explorer interface to look at the rule sets. To do so, you will need to set the Test options to use training set and observe the relevant numbers in the confusion matrix.*]
___
**Answer**
___
Now answer the following questions by thinking about the internal workings of 1R.
[*Hint: It will probably be fastest to use the Explorer interface to look at the rule sets.* ***Make a reasonable guess on how the algorithm should work. Confirm your guess by looking up the algorithm for 1R from the original paper. (In WEKA, choose OneR as the classifier, open the Generic Object Editor window, and click `More` to find the title of the original paper by Holte. You can then search for the paper online. Appendix~A of the paper contains the pseudocode.)***]
**Exercise 17.3.3.** You saw earlier that when visualizing 1R the plot always has three regions. But why aren’t there more for small bucket sizes (e.g., 1)? Use what you know about 1R to explain this apparent anomaly.
___
**Answer**
___
**Exercise 17.3.4.** Can you set minBucketSize to a value that results in less than three regions? What is the smallest possible number of regions? What is the smallest value for minBucketSize that gives this number of regions? Explain the result based on what you know about the iris data.
___
**Answer**
___
## Exercise 2 (no submission required)
For this question, construct the optimal decision list using RIPPER without prunning for the following dataset:
|$X_1$|$X_2$|$Y$|
|-----|-----|---|
|0 |0 |0 |
|0 |1 |0 |
|1 |0 |1 |
|1 |1 |0 |
|1 |1 |1 |
|0 |2 |0 |
where $X_1$ and $X_2$ are input attributes and $Y$ is a binary class.
___
**Answer**
___
## Exercise 3 (Optional)
Install and load the package [`wittgenstein`](https://github.com/imoscovitz/wittgenstein) for rule-based classification algorithms.
```
!pip install wittgenstein
import wittgenstein as lw
```
Load a binary classification dataset (`breast cancer`) and convert it to Pandas dataframe, as required by the RIPPER algorithm in `wittgenstein`.
```
from sklearn import datasets
import pandas as pd
import numpy as np
bc = datasets.load_breast_cancer()
bc
bc_pd = pd.DataFrame(data = bc['data'], columns = bc['feature_names'])
bc_pd.insert(len(bc_pd.columns), 'target', [bc.target_names[i] for i in bc['target']])
bc_pd
```
Build the rule-set using RIPPER algorithm
```
clf_ripper = lw.RIPPER()
clf_ripper.fit(bc_pd, class_feat='target', pos_class='malignant')
clf_ripper.out_model()
```
**Exercise:** Apply RIPPER to the iris dataset instead. (How to extend RIPPER algorithm to multi-class classification?)
```
```
| github_jupyter |
# pomegranate / hmmlearn comparison
<a href="https://github.com/hmmlearn/hmmlearn">hmmlearn</a> is a Python module for hidden markov models with a scikit-learn like API. It was originally present in scikit-learn until its removal due to structural learning not meshing well with the API of many other classical machine learning algorithms. Here is a table highlighting some of the similarities and differences between the two packages.
<table>
<tr>
<th>Feature</th>
<th>pomegranate</th>
<th>hmmlearn</th>
</tr>
<tr>
<th>Graph Structure</th>
<th></th>
<th></th>
</tr>
<tr>
<td>Silent States</td>
<td>✓</td>
<td></td>
</tr>
<tr>
<td>Optional Explicit End State</td>
<td>✓</td>
<td></td>
</tr>
<tr>
<td>Sparse Implementation</td>
<td>✓</td>
<td></td>
</tr>
<tr>
<td>Arbitrary Emissions Allowed on States</td>
<td>✓</td>
<td></td>
</tr>
<tr>
<td>Discrete/Gaussian/GMM Emissions</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td>Large Library of Other Emissions</td>
<td>✓</td>
<td></td>
</tr>
<tr>
<td>Build Model from Matrices</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td>Build Model Node-by-Node</td>
<td>✓</td>
<td></td>
</tr>
<tr>
<td>Serialize to JSON</td>
<td>✓</td>
<td></td>
</tr>
<tr>
<td>Serialize using Pickle/Joblib</td>
<td></td>
<td>✓</td>
</tr>
<tr>
<th>Algorithms</th>
<th></th>
<th></th>
</tr>
<tr>
<td>Priors</td>
<td></td>
<td>✓</td>
</tr>
<tr>
<td>Sampling</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td>Log Probability Scoring</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td>Forward-Backward Emissions</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td>Forward-Backward Transitions</td>
<td>✓</td>
<td></td>
</tr>
<tr>
<td>Viterbi Decoding</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td>MAP Decoding</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td>Baum-Welch Training</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td>Viterbi Training</td>
<td>✓</td>
<td></td>
</tr>
<tr>
<td>Labeled Training</td>
<td>✓</td>
<td></td>
</tr>
<tr>
<td>Tied Emissions</td>
<td>✓</td>
<td></td>
</tr>
<tr>
<td>Tied Transitions</td>
<td>✓</td>
<td></td>
</tr>
<tr>
<td>Emission Inertia</td>
<td>✓</td>
<td></td>
</tr>
<tr>
<td>Transition Inertia</td>
<td>✓</td>
<td></td>
</tr>
<tr>
<td>Emission Freezing</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td>Transition Freezing</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td>Multi-threaded Training</td>
<td>✓</td>
<td>Coming Soon</td>
</tr>
</table>
</p>
Just because the two features are implemented doesn't speak to how fast they are. Below we investigate how fast the two packages are in different settings the two have implemented.
## Fully Connected Graphs with Multivariate Gaussian Emissions
Lets look at the sample scoring method, viterbi, and Baum-Welch training for fully connected graphs with multivariate Gaussian emisisons. A fully connected graph is one where all states have connections to all other states. This is a case which pomegranate is expected to do poorly due to its sparse implementation, and hmmlearn should shine due to its vectorized implementations.
```
%pylab inline
import hmmlearn, pomegranate, time, seaborn
from hmmlearn.hmm import *
from pomegranate import *
seaborn.set_style('whitegrid')
```
Both hmmlearn and pomegranate are under active development. Here are the current versions of the two packages.
```
print "hmmlearn version {}".format(hmmlearn.__version__)
print "pomegranate version {}".format(pomegranate.__version__)
```
We first should have a function which will randomly generate transition matrices and emissions for the hidden markov model, and randomly generate sequences which fit the model.
```
def initialize_components(n_components, n_dims, n_seqs):
"""
Initialize a transition matrix for a model with a fixed number of components,
for Gaussian emissions with a certain number of dimensions, and a data set
with a certain number of sequences.
"""
transmat = numpy.abs(numpy.random.randn(n_components, n_components))
transmat = (transmat.T / transmat.sum( axis=1 )).T
start_probs = numpy.abs( numpy.random.randn(n_components) )
start_probs /= start_probs.sum()
means = numpy.random.randn(n_components, n_dims)
covars = numpy.ones((n_components, n_dims))
seqs = numpy.zeros((n_seqs, n_components, n_dims))
for i in range(n_seqs):
seqs[i] = means + numpy.random.randn(n_components, n_dims)
return transmat, start_probs, means, covars, seqs
```
Lets create the model in hmmlearn. It's fairly straight forward, only some attributes need to be overridden with the known structure and emissions.
```
def hmmlearn_model(transmat, start_probs, means, covars):
"""Return a hmmlearn model."""
model = GaussianHMM(n_components=transmat.shape[0], covariance_type='diag', n_iter=1, tol=1e-8)
model.startprob_ = start_probs
model.transmat_ = transmat
model.means_ = means
model._covars_ = covars
return model
```
Now lets create the model in pomegranate. Also fairly straightforward. The biggest difference is creating explicit distribution objects rather than passing in vectors, and passing everything into a function instead of overriding attributes. This is done because each state in the graph can be a different distribution and many distributions are supported.
```
def pomegranate_model(transmat, start_probs, means, covars):
"""Return a pomegranate model."""
states = [ MultivariateGaussianDistribution( means[i], numpy.eye(means.shape[1]) ) for i in range(transmat.shape[0]) ]
model = HiddenMarkovModel.from_matrix(transmat, states, start_probs, merge='None')
return model
```
Lets now compare some algorithm times.
```
def evaluate_models(n_dims, n_seqs):
hllp, plp = [], []
hlv, pv = [], []
hlm, pm = [], []
hls, ps = [], []
hlt, pt = [], []
for i in range(10, 112, 10):
transmat, start_probs, means, covars, seqs = initialize_components(i, n_dims, n_seqs)
model = hmmlearn_model(transmat, start_probs, means, covars)
tic = time.time()
for seq in seqs:
model.score(seq)
hllp.append( time.time() - tic )
tic = time.time()
for seq in seqs:
model.predict(seq)
hlv.append( time.time() - tic )
tic = time.time()
for seq in seqs:
model.predict_proba(seq)
hlm.append( time.time() - tic )
tic = time.time()
model.fit(seqs.reshape(n_seqs*i, n_dims), lengths=[i]*n_seqs)
hlt.append( time.time() - tic )
model = pomegranate_model(transmat, start_probs, means, covars)
tic = time.time()
for seq in seqs:
model.log_probability(seq)
plp.append( time.time() - tic )
tic = time.time()
for seq in seqs:
model.predict(seq)
pv.append( time.time() - tic )
tic = time.time()
for seq in seqs:
model.predict_proba(seq)
pm.append( time.time() - tic )
tic = time.time()
model.fit(seqs, max_iterations=1, verbose=False)
pt.append( time.time() - tic )
plt.figure( figsize=(12, 8))
plt.xlabel("# Components", fontsize=12 )
plt.ylabel("pomegranate is x times faster", fontsize=12 )
plt.plot( numpy.array(hllp) / numpy.array(plp), label="Log Probability")
plt.plot( numpy.array(hlv) / numpy.array(pv), label="Viterbi")
plt.plot( numpy.array(hlm) / numpy.array(pm), label="Maximum A Posteriori")
plt.plot( numpy.array(hlt) / numpy.array(pt), label="Training")
plt.xticks( xrange(11), xrange(10, 112, 10), fontsize=12 )
plt.yticks( fontsize=12 )
plt.legend( fontsize=12 )
evaluate_models(10, 50)
```
It looks like in this case pomegranate and hmmlearn are approximately the same for large (>30 components) dense graphs for the forward algorithm (log probability), MAP, and training. However, hmmlearn is significantly faster in terms of calculating the Viterbi path, while pomegranate is faster for smaller (<30 components) graphs.
## Sparse Graphs with Multivariate Gaussian Emissions
pomegranate is based off of a sparse implementations and so excels in graphs which are sparse. Lets try a model architecture where each hidden state only has transitions to itself and the next state, but running the same algorithms as last time.
```
def initialize_components(n_components, n_dims, n_seqs):
"""
Initialize a transition matrix for a model with a fixed number of components,
for Gaussian emissions with a certain number of dimensions, and a data set
with a certain number of sequences.
"""
transmat = numpy.zeros((n_components, n_components))
transmat[-1, -1] = 1
for i in range(n_components-1):
transmat[i, i] = 1
transmat[i, i+1] = 1
transmat[ transmat < 0 ] = 0
transmat = (transmat.T / transmat.sum( axis=1 )).T
start_probs = numpy.abs( numpy.random.randn(n_components) )
start_probs /= start_probs.sum()
means = numpy.random.randn(n_components, n_dims)
covars = numpy.ones((n_components, n_dims))
seqs = numpy.zeros((n_seqs, n_components, n_dims))
for i in range(n_seqs):
seqs[i] = means + numpy.random.randn(n_components, n_dims)
return transmat, start_probs, means, covars, seqs
evaluate_models(10, 50)
```
## Sparse Graph with Discrete Emissions
Lets also compare MultinomialHMM to a pomegranate HMM with discrete emisisons for completeness.
```
def initialize_components(n_components, n_seqs):
"""
Initialize a transition matrix for a model with a fixed number of components,
for Gaussian emissions with a certain number of dimensions, and a data set
with a certain number of sequences.
"""
transmat = numpy.zeros((n_components, n_components))
transmat[-1, -1] = 1
for i in range(n_components-1):
transmat[i, i] = 1
transmat[i, i+1] = 1
transmat[ transmat < 0 ] = 0
transmat = (transmat.T / transmat.sum( axis=1 )).T
start_probs = numpy.abs( numpy.random.randn(n_components) )
start_probs /= start_probs.sum()
dists = numpy.abs(numpy.random.randn(n_components, 4))
dists = (dists.T / dists.T.sum(axis=0)).T
seqs = numpy.random.randint(0, 4, (n_seqs, n_components*2, 1))
return transmat, start_probs, dists, seqs
def hmmlearn_model(transmat, start_probs, dists):
"""Return a hmmlearn model."""
model = MultinomialHMM(n_components=transmat.shape[0], n_iter=1, tol=1e-8)
model.startprob_ = start_probs
model.transmat_ = transmat
model.emissionprob_ = dists
return model
def pomegranate_model(transmat, start_probs, dists):
"""Return a pomegranate model."""
states = [ DiscreteDistribution({ 'A': d[0],
'C': d[1],
'G': d[2],
'T': d[3] }) for d in dists ]
model = HiddenMarkovModel.from_matrix(transmat, states, start_probs, merge='None')
return model
def evaluate_models(n_seqs):
hllp, plp = [], []
hlv, pv = [], []
hlm, pm = [], []
hls, ps = [], []
hlt, pt = [], []
dna = 'ACGT'
for i in range(10, 112, 10):
transmat, start_probs, dists, seqs = initialize_components(i, n_seqs)
model = hmmlearn_model(transmat, start_probs, dists)
tic = time.time()
for seq in seqs:
model.score(seq)
hllp.append( time.time() - tic )
tic = time.time()
for seq in seqs:
model.predict(seq)
hlv.append( time.time() - tic )
tic = time.time()
for seq in seqs:
model.predict_proba(seq)
hlm.append( time.time() - tic )
tic = time.time()
model.fit(seqs.reshape(n_seqs*i*2, 1), lengths=[i*2]*n_seqs)
hlt.append( time.time() - tic )
model = pomegranate_model(transmat, start_probs, dists)
seqs = [[dna[i] for i in seq] for seq in seqs]
tic = time.time()
for seq in seqs:
model.log_probability(seq)
plp.append( time.time() - tic )
tic = time.time()
for seq in seqs:
model.predict(seq)
pv.append( time.time() - tic )
tic = time.time()
for seq in seqs:
model.predict_proba(seq)
pm.append( time.time() - tic )
tic = time.time()
model.fit(seqs, max_iterations=1, verbose=False)
pt.append( time.time() - tic )
plt.figure( figsize=(12, 8))
plt.xlabel("# Components", fontsize=12 )
plt.ylabel("pomegranate is x times faster", fontsize=12 )
plt.plot( numpy.array(hllp) / numpy.array(plp), label="Log Probability")
plt.plot( numpy.array(hlv) / numpy.array(pv), label="Viterbi")
plt.plot( numpy.array(hlm) / numpy.array(pm), label="Maximum A Posteriori")
plt.plot( numpy.array(hlt) / numpy.array(pt), label="Training")
plt.xticks( xrange(11), xrange(10, 112, 10), fontsize=12 )
plt.yticks( fontsize=12 )
plt.legend( fontsize=12 )
evaluate_models(50)
```
| github_jupyter |
```
import numpy as np
import pandas as pd
import scipy as stats
import seaborn as sns
import pandas_profiling
import matplotlib.pyplot as plt
data=pd.read_csv('https://raw.githubusercontent.com/reddyprasade/Machine-Learning-Problems-DataSets/master/Classification/pima-indians-diabetes.csv')
data.head(2)
sns.heatmap(data.isnull(),cbar=False,cmap='viridis')
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split,cross_val_score
from sklearn.metrics import accuracy_score
import time
data.columns
x=data[['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin',
'BMI', 'DiabetesPedigreeFunction', 'Age']]
y=data['Outcome']
#model
x_trine,x_test,y_trine,y_test=train_test_split(x,y,test_size=0.15,random_state=25)
x_trine.shape
y_trine.shape
x_test.shape
y_test.shape
model=LogisticRegression(solver='lbfgs',max_iter=400)
model.fit(x_trine,y_trine)
y_predict=model.predict(x_test)
trine_score=model.score(x_trine,y_trine)
trine_score
test_score=model.score(x_test,y_test)
test_score
pd.DataFrame({'actual':y_test,'new_predict':y_predict})
from sklearn.feature_selection import RFE
model=LogisticRegression(solver='lbfgs',max_iter=500)
rfe=RFE(model,5,verbose=1)
rfe=rfe.fit(x,y)
rfe.support_
XX = x[x.columns[rfe.support_]]
XX
x_train, x_test, y_train, y_test = train_test_split(XX, y, test_size = 0.30, random_state = 8, stratify = y)
model = LogisticRegression(solver= 'lbfgs', max_iter = 500)
model.fit(x_train, y_train)
y_predict = model.predict(x_test)
trine_score=model.score(x_train, y_train)
trine_score
test_score=model.score(x_test,y_test)
test_score
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import accuracy_score, classification_report, precision_score, recall_score
from sklearn.metrics import confusion_matrix, precision_recall_curve, roc_auc_score, roc_curve, auc, log_loss
model = LogisticRegression(solver= 'lbfgs', max_iter = 500)
model.fit(x_train, y_train)
y_predict = model.predict(x_test)
y_predict_prob = model.predict_proba(x_test)[:, 1]
[fpr, tpr, thr] = roc_curve(y_test, y_predict_prob)
print('Accuracy: ', accuracy_score(y_test, y_predict))
print('log loss: ', log_loss(y_test, y_predict_prob))
print('auc: ', auc(fpr, tpr))
idx = np.min(np.where(tpr>0.95))
idx
plt.figure(figsize=(20,10))
plt.plot(fpr, tpr, color = 'coral', label = "ROC curve area: " + str(auc(fpr, tpr)))
plt.plot([0, 1], [0, 1], 'k--')
plt.plot([0, fpr[idx]], [tpr[idx], tpr[idx]], 'k--', color = 'blue')
plt.plot([fpr[idx],fpr[idx]], [0,tpr[idx]], 'k--', color='blue')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate (1 - specificity)', fontsize=14)
plt.ylabel('True Positive Rate (recall)', fontsize=14)
plt.title('Receiver operating characteristic (ROC) curve')
plt.legend(loc="lower right")
plt.show()
print("Using a threshold of %.3f " % thr[idx] + "guarantees a sensitivity of %.3f " % tpr[idx] +
"and a specificity of %.3f" % (1-fpr[idx]) +
", i.e. a false positive rate of %.2f%%." % (np.array(fpr[idx])*100))
```
| github_jupyter |
# We're going to add a background to our previous simple model
```
import numpy as np
import matplotlib.pyplot as plt
import theano.tensor as tt
import lightkurve as lk
from astropy.units import cds
from astropy import units as u
import seaborn as sns
import corner
import pystan
import pandas as pd
import pickle
import glob
from astropy.io import ascii
import os
import sys
import pymc3 as pm
from pymc3.gp.util import plot_gp_dist
import arviz
import warnings
warnings.filterwarnings('ignore')
cpu = 'bear'
```
## Build the model
```
class model():
def __init__(self, f, n0_, n1_, n2_, deltanu_):
self.f = f
self.n0 = n0_
self.n1 = n1_
self.n2 = n2_
self.npts = len(f)
self.M = [len(n0_), len(n1_), len(n2_)]
self.deltanu = deltanu_
def epsilon(self, i):
eps = tt.zeros((3,3))
eps0 = tt.set_subtensor(eps[0][0], 1.)
eps1 = tt.set_subtensor(eps[1][0], tt.sqr(tt.cos(i)))
eps1 = tt.set_subtensor(eps1[1], 0.5 * tt.sqr(tt.sin(i)))
eps2 = tt.set_subtensor(eps[2][0], 0.25 * tt.sqr((3. * tt.sqr(tt.cos(i)) - 1.)))
eps2 = tt.set_subtensor(eps2[1], (3./8.) * tt.sqr(tt.sin(2*i)))
eps2 = tt.set_subtensor(eps2[2], (3./8.) * tt.sin(i)**4)
eps = tt.set_subtensor(eps[0], eps0)
eps = tt.set_subtensor(eps[1], eps1)
eps = tt.set_subtensor(eps[2], eps2)
return eps
def lor(self, freq, h, w):
return h / (1.0 + 4.0/tt.sqr(w)*tt.sqr((self.f - freq)))
def mode(self, l, freqs, hs, ws, eps, split=0):
for idx in range(self.M[l]):
for m in range(-l, l+1, 1):
self.modes += self.lor(freqs[idx] + (m*split),
hs[idx] * eps[l,abs(m)],
ws[idx])
def model(self, p, theano=True):
f0, f1, f2, g0, g1, g2, h0, h1, h2, split, i, phi = p
# Unpack background parameters
loga = phi[0]
logb = phi[1]
logc = phi[2]
logd = phi[3]
logj = phi[4]
logk = phi[5]
white = phi[6]
scale = phi[7]
nyq = phi[8]
# Calculate the modes
eps = self.epsilon(i)
self.modes = np.zeros(self.npts)
self.mode(0, f0, h0, g0, eps)
self.mode(1, f1, h1, g1, eps, split)
self.mode(2, f2, h2, g2, eps, split)
self.modes *= self.get_apodization(nyq)
#Calculate the background
self.back = self.get_background(loga, logb, logc, logd, logj, logk,
white, scale, nyq)
#Create the model
self.mod = self.modes + self.back
if theano:
return self.mod
else:
return self.mod.eval()
# Small separations are fractional
def asymptotic(self, n, numax, alpha, epsilon, d=0.):
nmax = (numax / self.deltanu) - epsilon
curve = (alpha/2.)*(n-nmax)*(n-nmax)
return (n + epsilon + d + curve) * self.deltanu
def f0(self, p):
numax, alpha, epsilon, d01, d02 = p
return self.asymptotic(self.n0, numax, alpha, epsilon, 0.)
def f1(self, p):
numax, alpha, epsilon, d01, d02 = p
return self.asymptotic(self.n1, numax, alpha, epsilon, d01)
def f2(self, p):
numax, alpha, epsilon, d01, d02 = p
return self.asymptotic(self.n2+1, numax, alpha, epsilon, -d02)
def gaussian(self, freq, numax, w, A):
return A * tt.exp(-0.5 * tt.sqr((freq - numax)) / tt.sqr(w))
def A0(self, f, p, theano=True):
numax, w, A, V1, V2 = p
height = self.gaussian(f, numax, w, A)
if theano:
return height
else:
return height.eval()
def A1(self, f, p, theano=True):
numax, w, A, V1, V2 = p
height = self.gaussian(f, numax, w, A)*V1
if theano:
return height
else:
return height.eval()
def A2(self, f, p, theano=True):
numax, w, A, V1, V2 = p
height = self.gaussian(f, numax, w, A)*V2
if theano:
return height
else:
return height.eval()
def harvey(self, a, b, c):
harvey = 0.9*tt.sqr(a)/b/(1.0 + tt.pow((self.f/b), c))
return harvey
def get_apodization(self, nyquist):
x = (np.pi * self.f) / (2 * nyquist)
return tt.sqr((tt.sin(x)/x))
def get_background(self, loga, logb, logc, logd, logj, logk, white, scale, nyq):
background = np.zeros(len(self.f))
background += self.get_apodization(nyq) * scale \
* (self.harvey(tt.pow(10, loga), tt.pow(10, logb), 4.) \
+ self.harvey(tt.pow(10, logc), tt.pow(10, logd), 4.) \
+ self.harvey(tt.pow(10, logj), tt.pow(10, logk), 2.))\
+ white
return background
```
### Build the range
```
nmodes = 10
nbase = 13
n0_ = np.arange(nmodes)+nbase
n1_ = np.copy(n0_)
n2_ = np.copy(n0_) - 1.
fs = .1
nyq = (0.5 * (1./58.6) * u.hertz).to(u.microhertz).value
ff = np.arange(fs, nyq, fs)
```
### Build the frequencies
```
deltanu_ = 60.
numax_= 1150.
alpha_ = 0.01
epsilon_ = 1.1
d01_ = deltanu_/2. / deltanu_
d02_ = 6. / deltanu_
mod = model(ff, n0_, n1_, n2_, deltanu_)
init_f = [numax_, alpha_, epsilon_, d01_, d02_]
f0_true = mod.f0(init_f)
f1_true = mod.f1(init_f)
f2_true = mod.f2(init_f)
sigma0_ = 1.5
sigma1_ = 2.0
sigma2_ = .5
f0_ = mod.f0(init_f) + np.random.randn(len(f0_true)) * sigma0_
f1_ = mod.f1(init_f) + np.random.randn(len(f1_true)) * sigma1_
f2_ = mod.f2(init_f) + np.random.randn(len(f2_true)) * sigma2_
lo = f2_.min() - .25*deltanu_
hi = f1_.max() + .25*deltanu_
sel = (ff > lo) & (ff < hi)
f = ff[sel]
```
### Reset model for new frequency range
```
mod = model(f, n0_, n1_, n2_, deltanu_)
```
### Build the linewidths
```
def kernel(n, rho, L):
return rho**2 * np.exp(-0.5 * np.subtract.outer(n,n)**2 / L**2)
m_ = .5
c_ = .5
rho_ = 0.1
L_ = 0.3
fs = np.concatenate((f0_, f1_, f2_))
fs -= fs.min()
nf = fs/fs.max()
mu_ = m_ * nf + c_
Sigma_ = kernel(nf, rho_, L_)
lng0_ = np.random.multivariate_normal(mu_, Sigma_)
widths = [np.exp(lng0_)[0:len(f0_)],
np.exp(lng0_)[len(f0_):len(f0_)+len(f1_)],
np.exp(lng0_)[len(f0_)+len(f1_):]]
nf_ = nf[:,None]
```
### Build the mode amplitudes
```
w_ = (0.25 * numax_)/2.355
V1_ = 1.2
V2_ = 0.7
A_ = 10.
init_h =[numax_, #numax
w_, #envelope width
A_, #envelope amplitude
V1_, #dipole visibility
V2_ #ocotopole visibility
]
sigmaA_ = .2
amps = [np.abs(mod.A0(f0_, init_h, theano=False) + np.random.randn(len(f0_)) * sigmaA_),
np.abs(mod.A1(f1_, init_h, theano=False) + np.random.randn(len(f0_)) * sigmaA_),
np.abs(mod.A2(f2_, init_h, theano=False) + np.random.randn(len(f0_)) * sigmaA_)]
```
### Build the background
```
labels=['loga','logb','logc','logd','logj','logk','white','scale','nyq']
phi_ = [ 1.6, 2.6, 1.6, 3.0, 1.7, 0.5, 0.4, 1., nyq]
phi_sigma = np.genfromtxt('phi_sigma.txt')
phi_cholesky = np.linalg.cholesky(phi_sigma)
```
### Construct the model
```
split_ = 1.
incl_ = np.pi/4.
init =[f0_, # l0 modes
f1_, # l1 modes
f2_, # l2 modes
widths[0], # l0 widths
widths[1], # l1 widths
widths[2], # l2 widths
amps[0]**2 * 2.0 / np.pi / widths[0] ,# l0 heights
amps[1]**2 * 2.0 / np.pi / widths[1] ,# l1 heights
amps[2]**2 * 2.0 / np.pi / widths[2] ,# l2 heights
split_, # splitting
incl_, # inclination angle
phi_ # background parameters
]
p = mod.model(init, theano=False)*np.random.chisquare(2., size=len(f))/2
with plt.style.context(lk.MPLSTYLE):
plt.plot(f, p)
plt.plot(f, mod.model(init, theano=False), lw=3)
plt.yscale('log')
plt.xscale('log')
if cpu == 'bear':
plt.savefig('data.png')
else: plt.show()
```
# Now lets try and fit this
```
pm_model = pm.Model()
with pm_model:
# Mode locations
f0 = pm.Normal('f0', mu = f0_, sigma = sigma0_*10., testval = f0_, shape = len(f0_))
f1 = pm.Normal('f1', mu = f1_, sigma = sigma1_*10., testval = f1_, shape = len(f1_))
f2 = pm.Normal('f2', mu = f2_, sigma = sigma2_*10., testval = f2_, shape = len(f2_))
# Mode linewidths
g0 = pm.HalfNormal('g0', sigma=2.0, testval=init[3], shape=len(init[3]))
g1 = pm.HalfNormal('g1', sigma=2.0, testval=init[4], shape=len(init[4]))
g2 = pm.HalfNormal('g2', sigma=2.0, testval=init[5], shape=len(init[5]))
# Mode amplitudes
a0 = pm.HalfNormal('a0', sigma=20., testval=amps[0], shape=len(amps[0]))
a1 = pm.HalfNormal('a1', sigma=20., testval=amps[1], shape=len(amps[1]))
a2 = pm.HalfNormal('a2', sigma=20., testval=amps[2], shape=len(amps[2]))
h0 = pm.Deterministic('h0', 2*tt.sqr(a0)/np.pi/g0)
h1 = pm.Deterministic('h1', 2*tt.sqr(a1)/np.pi/g1)
h2 = pm.Deterministic('h2', 2*tt.sqr(a2)/np.pi/g2)
# Mode splitting
xsplit = pm.HalfNormal('xsplit', sigma=2.0, testval=init[9] * np.sin(init[10]))
cosi = pm.Uniform('cosi', 0., 1., testval=np.cos(init[10]))
i = pm.Deterministic('i', tt.arccos(cosi))
split = pm.Deterministic('split', xsplit/tt.sin(i))
# Background treatment
phi = pm.MvNormal('phi', mu=phi_, chol=phi_cholesky, testval=phi_, shape=len(phi_))
# Construct model
fit = mod.model([f0, f1, f2, g0, g1, g2, h0, h1, h2, split, i, phi])
like = pm.Gamma('like', alpha=1., beta=1./fit, observed=p)
for RV in pm_model.basic_RVs:
print(RV.name, RV.logp(pm_model.test_point))
start = {'f0' : f0_, 'f1' : f1_, 'f2' : f2_,
'xsplit' : split_ * incl_, 'cosi' : np.cos(incl_), 'phi' : phi_,
'g0' : widths[0], 'g1' : widths[1], 'g2' : widths[2],
'a0' : amps[0], 'a1' : amps[1], 'a2' : amps[2]}
with pm_model:
trace = pm.sample(chains=4,
target_accept=.99,
start = start,
init = 'advi+adapt_diag',
progressbar=True)
pm.summary(trace)
labels = ['xsplit','cosi','split','i']
chain = np.array([trace[label] for label in labels])
truths = [init[9] * np.sin(init[10]), np.cos(init[10]), init[9], init[10]]
corner.corner(chain.T, labels=labels, truths=truths, quantiles=[.16, .5, .84], truth_color='r',show_titles=True)
if cpu == 'bear':
plt.savefig('corner.png')
else: plt.show()
with plt.style.context(lk.MPLSTYLE):
res_m = [np.median(trace[label], axis=0) for label in ['f0','f1','f2','g0','g1','g2',
'h0','h1','h2','split','i','phi']]
plt.plot(f, p)
plt.plot(f, mod.model(res_m, theano=False), lw=3)
if cpu == 'bear':
plt.savefig('modelfit.png')
else: plt.show()
labels=['loga','logb','logc','logd','logj','logk',
'white','scale','nyq']
verbose=[r'$\log_{10}a$',r'$\log_{10}b$',
r'$\log_{10}c$',r'$\log_{10}d$',
r'$\log_{10}j$',r'$\log_{10}k$',
'white','scale',r'$\nu_{\rm nyq}$']
phichain = np.array([trace['phi'][:,idx] for idx in range(len(phi_))]).T
truth = phi_
corner.corner(phichain, truths=truth, show_titles=True, labels=verbose)
if cpu == 'bear':
plt.savefig('backcorner.png')
else: plt.show()
residual = p/mod.model(res_m, theano=False)
sns.distplot(residual, label='Model')
sns.distplot(np.random.chisquare(2, size=10000)/2, label=r'Chi22')
plt.legend()
sys.exit()
```
| github_jupyter |
```
%%markdown
# Exploration
!ls -laFh /data/use-cases/service-vehicle-tracking/2018-03-trips
import pandas as pd
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
df_trips = pd.read_csv ('/data/use-cases/service-vehicle-tracking/2018-03-trips/vehicle_trip_data.csv.bz2')
df_cap = pd.read_csv ('/data/use-cases/service-vehicle-tracking/2018-03-trips/vehicle_trip_data_valset.csv.bz2')
# The epochs are counted from the 01-JAN-2000,
# whereas the standard Unix dates are counted from the 01-JAN-1970.
# There is a difference of 10,957 days
df_trips['tst_abs'] = pd.to_datetime(df_trips['tst'], unit='s') + pd.DateOffset(days = 10957)
df_trips.head()
df_trips.head()
df_trips.describe()
device_list = df_trips['dev_id'].unique()
len(device_list)
fuel_cap_list = df_trips['cns_rmg'].unique()
fuel_cap_list
speed_list = df_trips['spd'].unique()
speed_list
df_cap.head()
df_cap.describe()
device_cap_list = df_cap['dev_id'].unique()
len(device_cap_list)
cap_list = df_cap['cap'].unique()
cap_list
df_full = df_trips.merge(df_cap, how='left')
df_full.head()
cap_full_list = df_full['cap'].unique()
cap_full_list
# List of vehicles for which no capacity is known
df_full[df_full['cap'].isnull()]['dev_id'].unique()
def plot_specific(dev_id):
"""Plot the time-series for a specific ID"""
df_specific = df_full[df_full['dev_id'] == dev_id]
plt.figure()
fig, subaxes = plt.subplots(1, 3, figsize=(32, 10))
df_specific.plot.scatter(x='tst', y='dst', color='Blue', label='Distance', title='Distance', ax = subaxes[0])
df_specific.plot.scatter(x='tst', y='cns_tot', color='Green', label='Consumption', title='Consumption', ax = subaxes[1])
df_specific.plot.scatter(x='tst', y='cns_rmg', color='Red', label='Remaining', title='Remaining', ax = subaxes[2])
plt.show()
plot_specific(6741)
def get_min_max_index_lists(data):
"""Lists of indices of the minima and of the maxima.
The values of the series always decrease, from 100 down to some minima.
The indices are not necessarily contiguous (they correspond to
time-stamps in seconds)"""
last_idx = data.index[0]
last_x = data.iloc[0]
min_idx_list = []
max_idx_list = [last_idx]
first_iteration = True
for idx, x in data.iteritems():
if (x > 90 and x > last_x+20 and first_iteration == False):
min_idx_list.append(last_idx)
max_idx_list.append(idx)
last_idx = idx
last_x = x
first_iteration = False
min_idx_list.append(last_idx)
return (min_idx_list, max_idx_list)
df_specific = df_full[df_full['dev_id'] == 6741]
df_cns = df_specific.drop_duplicates().set_index('tst')['cns_rmg']
df_cns.head()
(min_idx_list, max_idx_list) = get_min_max_index_lists(df_cns)
min_idx_list
df_cns[min_idx_list]
max_idx_list
df_cns[max_idx_list]
plt.figure()
ax = df_specific.plot.scatter(x='tst', y='cns_rmg', color='Red')
ax.scatter(x=min_idx_list, y=df_cns[min_idx_list], color='Blue', s=50)
ax.scatter(x=max_idx_list, y=df_cns[max_idx_list], color='Green', s=50)
plt.show()
df_all = df_specific.drop_duplicates().set_index('tst')
df_dst_list = df_all['dst'][min_idx_list].reset_index() - df_all['dst'][max_idx_list].reset_index()
df_dst_list
df_cnstot_list = df_all['cns_tot'][min_idx_list].reset_index() - df_all['cns_tot'][max_idx_list].reset_index()
df_cnstot_list
df_cnsrmg_list = df_all['cns_rmg'][max_idx_list].reset_index() - df_all['cns_rmg'][min_idx_list].reset_index()
df_cnsrmg_list['tst'] = -df_cnsrmg_list['tst']
df_cnsrmg_list
df_merged = pd.concat([df_cnstot_list, df_cnsrmg_list], axis=1)
df_merged
df_all.head()
%%markdown
# Variations
def get_peak_index_lists(data):
max_peakind = signal.find_peaks_cwt(df_cns, np.arange(1, 1000))
inv_df = 1./df_cns
min_peakind = signal.find_peaks_cwt(inv_df, np.arange(1, 1000))
return (min_peakind, max_peakind)
df_cns_rawidx = df_specific['cns_rmg']
(min_peakind, max_peakind) = get_peak_index_lists(df_cns_rawidx)
df_cns_rawidx[max_peakind]
df_cns_rawidx[min_peakind]
```
| github_jupyter |
# library
```
import math
from scipy import signal
from numpy import *
from pylab import *
import cv2
import random
from random import randrange
from random import randrange
from numpy import linalg
from scipy import signal
from pylab import *
from PIL import Image
from skimage.transform import warp
## full matrix
import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)
## imshow problem
#import tkinter
#import matplotlib
#matplotlib.use('TkAgg')
```
# input
```
import SimpleITK as sitk
#directory='/home/mahdi/python codes/final version/SP_S05_D1_RND.nii'
directory='/home/mahdi/python codes/final version/crop.nii'
I = sitk.ReadImage(directory)
I = sitk.GetArrayFromImage(I)
I=I.astype(np.float32)
```
# mask
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
## t.shape[0] ## for volume
def mask(I,volume, layer):
if volume<10:
name=str(0)+str(0)+str(volume)
if 9<volume<100:
name=str(0)+str(volume)
if 99<volume<1000:
name=str(volume)
g=I[volume,layer,:,:]
g=g.astype(np.float32)
df = pd.read_csv('/home/mahdi/python codes/centerline_case2/centerline_volume'+name+'.csv', header=None)
df.columns=['x','y','delete']
df=df[['x','y']]
c=df.loc[layer]
x=int(c['x'])
y=int(c['y'])
f=g[y-15:y+15,x-15:x+15]
return f
```
# pyramid optical flow
```
# function defines the gaussian function used for convolution which returns the
def GaussianFunction(x, sigma):
if sigma == 0:
return 0
else:
g = (1/math.sqrt(2*math.pi*sigma*sigma))*math.exp(-x*x)/(2*sigma*sigma)
return g
# function returns the gaussian kernel using the GaussianFunction of size 3x3
def GaussianMask(sigma):
g = []
for i in range(-2, 3):#creating a gaussian kernel of size 3x3
g1 = GaussianFunction(i,sigma)
g2 = GaussianFunction(i-0.5, sigma)
g3 = GaussianFunction(i+0.5, sigma)
gaussian = (g1+g2+g3)/3
g.append(gaussian)
return g
sigma = 1.5
G = [] # Gaussian Kernel
G = GaussianMask(sigma)
def DownSample(I):
Ix = Iy = []
I = np.array(I)
S = np.shape(I) #shape of the image
for i in range(S[0]):
Ix.extend([signal.convolve(I[i,:],G,'same')])#convolution of the I[i] with G
Ix = np.array(np.matrix(Ix))
Iy = Ix[::2, ::2]#selects the alternate column and row
return Iy
def UpSample(I):
I = np.array(I)
S = np.shape(I)
Ix = np.zeros((S[0], 2*S[1]))#inserting alternate rows of zeros
Ix[:, ::2] = I
S1 = np.shape(Ix)
Iy = np.zeros((2*S1[0], S1[1]))#inserting alternate columns of zeros
Iy[::2, :] = Ix
Ig = cv2.GaussianBlur(Iy, (5,5), 1.5, 1.5)#instead of using the user-defined gaussian function, I am using the Gaussian Blur functtion for double the size of gaussian kernel size
return Ig
def LucasKanade(I1, I2,x):
I1 = np.array(I1)
I2 = np.array(I2)
S = np.shape(I1)
Ix = signal.convolve2d(I1,[[-x,x],[-x,x]],'same') + signal.convolve2d(I2,[[-x,x],[-x,x]],'same')
Iy = signal.convolve2d(I1,[[-x,-x],[x,x]],'same') + signal.convolve2d(I2,[[-x,-x],[x,x]],'same')
It = signal.convolve2d(I1,[[x,x],[x,x]],'same') + signal.convolve2d(I2,[[-x,-x],[-x,-x]],'same')
features = cv2.goodFeaturesToTrack(I1, 10000, 0.01, 10)
features = np.int0(features)
u = np.ones((S))
v = np.ones((S))
for l in features:
j,i = l.ravel()
IX = ([Ix[i-1,j-1],Ix[i,j-1],Ix[i+1,j+1],Ix[i-1,j],Ix[i,j],Ix[i+1,j],Ix[i-1,j+1],Ix[i,j+1],Ix[i+1,j-1]])
IY = ([Iy[i-1,j-1],Iy[i,j-1],Iy[i+1,j+1],Iy[i-1,j],Iy[i,j],Iy[i+1,j],Iy[i-1,j+1],Iy[i,j+1],Iy[i+1,j-1]])
IT = ([It[i-1,j-1],It[i,j-1],It[i+1,j+1],It[i-1,j],It[i,j],It[i+1,j],It[i-1,j+1],It[i,j+1],It[i+1,j-1]])
#IX = ([Ix[i-1,j-1],Ix[i-1,j],Ix[i-1,j+1],Ix[i,j-1],Ix[i,j],Ix[i,j+1],Ix[i+1,j-1],Ix[i+1,j],Ix[i+1,j+1]])
# IY = ([Ix[i-1,j-1],Ix[i-1,j],Ix[i-1,j+1],Ix[i,j-1],Ix[i,j],Ix[i,j+1],Ix[i+1,j-1],Ix[i+1,j],Ix[i+1,j+1]])
#IT = ([Ix[i-1,j-1],Ix[i-1,j],Ix[i-1,j+1],Ix[i,j-1],Ix[i,j],Ix[i,j+1],Ix[i+1,j-1],Ix[i+1,j],Ix[i+1,j+1]])
# Using the minimum least squares solution approach
LK = (IX,IY)
LK = matrix(LK)
LK = array(matrix(LK))
LK_T = array(np.matrix.transpose(LK))
#Psedudo Inverse
A1 = np.dot(LK_T,LK)
A2 = np.linalg.pinv(A1)
A3 = np.dot(A2,LK_T)
(u[i,j],v[i,j]) = np.dot(A3.T,IT) # we have the vectors with minimized square error
u = np.flipud(u)
v = np.flipud(v)
return u,v
def LucasKanadeIterative(I1, I2, u1, v1,kernel,x):
I1 = np.array(I1)
I2 = np.array(I2)
S = np.shape(I1)
u1 = np.round(u1)
v1 = np.round(v1)
u = np.zeros(S)
v = np.zeros(S)
for i in range(int(kernel/2),S[0]-int(kernel/2)):
for j in range(int(kernel/2),S[0]-int(kernel/2)):
I1new = I1[i-int(kernel/2):i+int(kernel/2)+1,j-int(kernel/2):j+int(kernel/2)+1]# picking 5x5 pixels at a time
lr = (i-int(kernel/2))+v1[i,j]#Low Row Index
hr = (i+int(kernel/2))+v1[i,j]#High Row Index
lc = (j-int(kernel/2))+u1[i,j]#Low Column Index
hc = (j+int(kernel/2))+u1[i,j]#High Column Index
#window search and selecting the last window if it goes out of bounds
if(lr < 0):
lr = 0
hr = kernel-1
if(lc < 0):
lc = 0
hc = kernel-1
if(hr > (len(I1[:,0]))-1):
lr = len(I1[:,0])-kernel
hr = len(I1[:,0])-1
if(hc > (len(I1[0,:]))-1):
lc = len(I1[0,:])-kernel
hc = len(I1[0,:])-1
if(np.isnan(lr)):
lr = i-int(kernel/2)
hr = i+int(kernel/2)
if(np.isnan(lc)):
lc = j-int(kernel/2)
hc = j+int(kernel/2)
#Selecting the same window for the second frame
I2new = I2[int(lr):int((hr+1)),int(lc):int((hc+1))]
# Now applying LK for each window of the 2 images
IX = signal.convolve2d(I1new,[[-x,x],[-x,x]],'same') + signal.convolve2d(I2new,[[-x,x],[-x,x]],'same')
IY = signal.convolve2d(I1new,[[-x,-x],[x,x]],'same') + signal.convolve2d(I2new,[[-x,-x],[x,x]],'same')
IT = signal.convolve2d(I1new,[[x,x],[x,x]],'same') + signal.convolve2d(I2new,[[-x,-x],[-x,-x]],'same')
if kernel>1:
IX = np.transpose(IX[1:kernel,1:kernel])
IY = np.transpose(IY[1:kernel,1:kernel])
IT = np.transpose(IT[1:kernel,1:kernel])
IX = IX.ravel()
IY = IY.ravel()
IT = IT.ravel()
LK = (IX,IY)
LK = np.matrix(LK)
LK_T = np.array(np.matrix(LK))
LK = np.array(np.matrix.transpose(LK))
A1 = np.dot(LK_T,LK)
A2 = np.linalg.pinv(A1)
A3 = np.dot(A2,LK_T)
(u[i,j],v[i,j]) = np.dot(A3,IT)
return u,v
def LK_Pyramid(Im1, Im2, iteration, level,kernel,x):
I1 = np.array(Im1)
I2 = np.array(Im2)
S = np.shape(I1)
pyramid1 = np.empty((S[0],S[1],level))
pyramid2 = np.empty((S[0],S[1],level))
pyramid1[:,:,0] = I1 #since the lowest level is the original imae
pyramid2[:,:,0] = I2 #since the lowest level is the original image
#creating the pyramid by downsampling the original image
for i in range(1, level):
I1 = DownSample(I1)
I2 = DownSample(I2)
pyramid1[0:np.shape(I1)[0], 0:np.shape(I1)[1], i] = I1
pyramid2[0:np.shape(I2)[0], 0:np.shape(I2)[1], i] = I2
level0_I1 = pyramid1[0:round(len(pyramid1[:,0])/4),0:round(len(pyramid1[0,:])/4),2]
level0_I2 = pyramid2[0:round(len(pyramid2[:,0])/4),0:round(len(pyramid2[0,:])/4),2]
(u,v) = LucasKanade(Im1, Im2,x)
for i in range(0, iteration):
(u,v) = LucasKanadeIterative(level0_I1, level0_I2, u, v,kernel,x)
u_l0 = u
v_l0 = v
I_l0 = level0_I1
#u_l0[np.where(u_l0 == 0)] = nan
#v_l0[np.where(v_l0 == 0)] = nan
#for level 1
k = 1
u1 = UpSample(u)
v1 = UpSample(v)
I1new = pyramid1[0:int(len(pyramid1[:,0])/(2**(level-k-1))),0:int(len(pyramid1[0,:])/(2**(level-k-1))),level-k-1]
I2new = pyramid2[0:int(len(pyramid2[:,0])/(2**(level-k-1))),0:int(len(pyramid2[0,:])/(2**(level-k-1))),level-k-1]
(u,v) = LucasKanadeIterative(I1new, I2new, u1, v1,kernel,x)
u_l1 = u
v_l1 = v
I_l1 = I1new
#u_l1[np.where(u_l1 == 0)] = nan
#v_l1[np.where(v_l1 == 0)] = nan
k = 2
u1 = UpSample(u)
v1 = UpSample(v)
I1new = pyramid1[0:int(len(pyramid1[:,0])/(2**(level-k-1))),0:int(len(pyramid1[0,:])/(2**(level-k-1))),level-k-1]
I2new = pyramid2[0:int(len(pyramid2[:,0])/(2**(level-k-1))),0:int(len(pyramid2[0,:])/(2**(level-k-1))),level-k-1]
(u,v) = LucasKanadeIterative(I1new, I2new, u1, v1,kernel,x)
u_l2 = u
v_l2 = v
I_l2 = I1new
#u_l2[np.where(u_l2 == 0)] = nan
#v_l2[np.where(v_l2 == 0)] = nan
colours = "bgrcmykw"
colour_index = random.randrange(0,8)
c=colours[colour_index]
plt.figure()
plt.imshow(I_l0,cmap = cm.gray)
plt.title('Level 0 - Base level')
quiver(u_l0,v_l0,color = c)
c=colours[colour_index]
plt.figure()
plt.imshow(I_l1,cmap = cm.gray)
plt.title('Level 1')
quiver(u_l1,v_l1,color = c)
c=colours[colour_index]
plt.figure()
plt.imshow(I_l2,cmap = cm.gray)
plt.title('Level 2')
plt.quiver(u_l2,v_l2,color = c)
np.array(u_l2)
plt.show
return u,v
def reg(Im1,Im2,u,v):
nr, nc = Im1.shape
row_coords, col_coords = np.meshgrid(np.arange(nr), np.arange(nc), indexing='ij')
im1_warp = warp(Im2, np.array([row_coords + u, col_coords + v]),
order=1)
# build an RGB image with the unregistered sequence
plt.figure()
plt.imshow(im1_warp,cmap = cm.gray)
plt.title('register')
plt.figure()
plt.imshow(Im1,cmap = cm.gray)
plt.title('refrence image')
plt.figure()
plt.imshow(Im2,cmap = cm.gray)
plt.title('second image')
plt.show()
return im1_warp
directory='/home/mahdi/python codes/final version/mean.nii'
I_mean = sitk.ReadImage(directory)
I_mean= sitk.GetArrayFromImage(I_mean)
def mask_mean(I,layer):
m=I_mean[layer,:,:]
m=m.astype(np.float32)
dfm = pd.read_csv('/home/mahdi/python codes/final version/mean_centerline.csv', header=None)
dfm.columns=['x','y','delete']
dfm=dfm[['x','y']]
c=dfm.loc[layer]
x=int(c['x'])
y=int(c['y'])
fm=m[y-15:y+15,x-15:x+15]
return f
plt.imshow(I_mean[5,:,:])
Is=np.delete(I[0,5,:,:], [0, 1,2], 0)
Is=np.delete(Is, 0, 1)
print(Is.shape)
Ir=np.delete(I[1,5,:,:], [0, 1,2], 0)
Ir=np.delete(Ir, 0, 1)
Ir.shape
import random
%matplotlib inline
#ua,vb=LK_Pyramid(mask_mean(I_mean,5), mask(I,150,5), 3, 3,7,0.25)
ua,vb=LK_Pyramid(Is, Ir, 3, 3,5,0.25)
b=reg(Is, Ir,ua,vb)
I[1,5,:,:].shape
```
| github_jupyter |
```
import GPUtil
import nvidia_smi
import platform
from datetime import datetime
import datetime
import time
import psutil
import pandas as pd
from tabulate import tabulate
from random import randint
from psutil._common import bytes2human
import socket
from socket import AF_INET, SOCK_STREAM, SOCK_DGRAM
from __future__ import print_function
import os
import sys
import pandas as pd
```
# Why should we use it?/Neden kullanmalıyız?
* EN:
Most of us do not think about why we tire the system when dealing with data science, machine learning, deep learning. However, if we can use our system at full performance, it will positively affect the work we do. It is also possible to do the same job with less RAM, Core, GPU! All you need to do is to use your system in a more optimized way. So how will this happen?
Example_1: You have a Deep Learning model and big data. As a result, your RAM and VRAM needs will be high. You can see your system's values in each epoch and update your project accordingly. You can use "Swap_Memory" for RAM and functions that allow you to free your VRAM in every for loop for VRAM.
Example_2: Let's say you have a large data set. But you have to work separately. If you have 32 threads, it means you can assign 16 threads to both data groups. By doing this, you will get more stable, efficient and faster results than starting 2 codes at the same time.
Example_3: Observing the system while it is on the job and detecting defective parts.
Examples can be multiplied further. It will be beneficial for you and your system to use the functions here by designing them according to your purpose and imagination.
* TR:
Çoğumuz veri bilimi, makine öğrenmesi,derin öğrenme ile uğraşırken neden kadar sistemi yorduğumuzu düşünmüyoruz. Oysa ki sistemimizi tam performansta kullanabilsek, yaptığımız işi de pozitif etkileyecektir. Ayrıca Daha az RAM,Core,GPU ile aynı işi yapmak mümkün! Tek yapmanız gereken daha optimize bir şekilde sisteminizi kullanabilmek. Peki bu nasıl olacak?
Örnek_1: Bir Derin Öğrenme modeli ve büyük bir veriniz var. Haliyle RAM ve VRAM ihtiyacınız yüksek olacaktır. Her Epoch'da sisteminizin değerlerinizi görmeniz ona göre projenizde güncelleme yapabilirsiniz. RAM için "Swap_Memory", VRAM içinse her for döngüsünde VRAM'inizi boşaltmaya sağlayan fonksiyonları kullanabilirsiniz.Torch kütüphanesinde var ama Tensorflow için hatırlamıyorum maalesef.
Örnek_2: Diyelim ki elinizde büyük bir veri grubu var. Ama ayrı bir şekilde çalışmanız gerekiyor. 32 iş parçacığınız var ise her 2 veri grubuna da 16 iş parçacığı atayabilirsiniz demektir. Böyle yaparak 2 kodu aynı anda başlatmanızdan daha stabil,verimli ve hızlı sonuç alacaksınızdır.
Örnek_3: Sistemi genel olarak iş üzerinde iken gözlemlemek ve kusurlu çalışan parçaları tespit etmek.
Örnekler daha çoğaltılabilir. Buradaki bulunan fonksiyonları amacınıza ve hayal gücünüze göre dizayn ederek kullanmanız size ve sisteminize yararı olacaktır.
## Which Library?/Hangi kütüphane?
* EN:
I can say that "psutil" is ahead in almost every system part except GPU. For GPU, "GPUtil" is a good choice for now. "nvidia_smi","py3nvml","platform" are more restricted libraries. "nvidia_smi" is a bit of an exception. Because "nvidia_smi." If you press the "tab" key after typing, you will see that there are quite a lot of functions. But I couldn't come across a documention that explains them.
* TR:
GPU hariç hemen hemen her sistem parçasında "psutil" daha önde diyebilirim.GPU için şuanlık "GPUtil" güzel bir tercih. "nvidia_smi","py3nvml","platform" ise daha kısıtlı kütüphaneler. "nvidia_smi" biraz istisna sayılabilir. Zira "nvidia_smi." yazdıktan sonra "tab" tuşuna basar iseniz oldukça fazla fonksiyon olduğunu göreceksinizdir. Ama bunları açıklayan bir documention denk gelemedim.
### Note/NOT:
* EN:
Some of the code found here is intentionally commented out. There are 2 reasons for this.
The first reason is that some codes do not work in windows and give an error.
The second reason is that some code contains personal data, so I preferred to share it with a comment line. For example, the IP address.
* TR:
Burada bulunan bazı kodlar bilerek yorum satırı ile verilmiştir. Bunun 2 sebebi vardır.
İlk sebep, bazı kodlar windowsta çalışmamakta ve hata vermektedir.
İkinci sebep, bazı kodlar kişisel veri içerdiğinden yorum satırı ile paylaşmayı tercih ettim. Örneğin, IP adresi.
## CPU
```
import psutil
# instant cpu usage rate/anlık cpu kullanım oranı
psutil.cpu_percent()
```
Warning the first time this function is called with interval = 0.0 or None it will return a meaningless 0.0 value which you are supposed to ignore.
Bu fonksiyon interval = 0.0 veya None ile ilk kez çağrıldığında uyarı, görmezden gelmeniz gereken anlamsız bir 0.0 değeri döndürür.
```
psutil.cpu_count(logical=True) # İş parçacığı dahildir. Ayrıca şu kod ile aynıdır os.cpu_count()
# Thread are included. Also the code is the same as os.cpu_count()
psutil.cpu_count(logical=False) # sadece çekirdekler/ only core
len(psutil.Process().cpu_affinity()) # şuanda kullanılabilir olanların sayısı
psutil.cpu_stats()
```
* ctx_switches: number of context switches (voluntary + involuntary) since boot.
* interrupts: number of interrupts since boot.
* soft_interrupts: number of software interrupts since boot. Always set to 0 on Windows and SunOS.
* syscalls: number of system calls since boot. Always set to 0 on Linux.
* ctx_switches: önyüklemeden bu yana bağlam anahtarlarının sayısı (gönüllü + istemsiz).
* kesintiler: önyüklemeden bu yana yapılan kesintilerin sayısı.
* soft_interrupts: önyüklemeden bu yana yazılım kesintilerinin sayısı. Windows ve SunOS'ta her zaman 0'a ayarlayın.
* sistem çağrıları: önyüklemeden bu yana sistem çağrılarının sayısı. Linux'ta her zaman 0'a ayarlayın.
```
psutil.cpu_freq(percpu=False)
psutil.cpu_freq(percpu=True)
```
* On Linux, Mhz reports the real-time value, on all other platforms it represents the nominal "fixed" value. Since I'm using Windows, it generates a constant value. And since my processor's base speed is 3.4GHz, it produces the result you see.
* Linux'ta Mhz gerçek zamanlı değeri bildirir, diğer tüm platformlarda nominal “sabit” değeri temsil eder. Ben Windows kullandığımdan sabit bir değer üretiyor. Ve işlemcimin base hızı 3.4GHz olduğundan gördüğünüz sonucu üretiyor.
```
psutil.cpu_times(percpu=True) # True ise, tüm iş parçacıkları için dönecektir. False içinse ilki için
# If true, it will return for all threads. For false, for the first
```
* user: time spent by normal processes executing in user mode; on Linux this also includes guest time
* system: time spent by processes executing in kernel mode
* idle: time spent doing nothing
* kullanıcı: kullanıcı modunda yürütülen normal işlemler tarafından harcanan zaman; Linux'ta buna misafir zamanı da dahildir
* sistem: çekirdek modunda yürütülen işlemler tarafından harcanan zaman
* boşta: hiçbir şey yapmadan harcanan zaman
```
psutil.getloadavg()
```
* EN:
Return a tuple containing the average system load over the last 1, 5, and 15 minutes. “Load” represents the processes that are executable using or waiting to use the CPU (for example, waiting for disk I/O).
On Windows, this is emulated using a Windows API that creates a thread that continues to run in the background and updates the results every 5 seconds, emulating UNIX behavior. So on Windows this will return a meaningless tuple the first time it is called and for the next 5 seconds. The numbers returned are meaningful only if they relate to the number of CPU cores installed in the system.
For example, a value of 3.14 means that on a system with 10 logical CPUs, the system load has been 31.4 percent for the last N minutes.
* TR:
Son 1, 5 ve 15 dakikadaki ortalama sistem yükünü içeren bir tuple döndürün.. “Yük”, CPU'yu kullanan veya CPU'yu kullanmayı bekleyen (örneğin, disk G/Ç'sini bekleyen) çalıştırılabilir durumda olan işlemleri temsil eder.
Windows'ta bu, arka planda çalışmaya devam eden ve sonuçları her 5 saniyede bir güncelleyerek UNIX davranışını taklit eden bir iş parçacığı oluşturan bir Windows API'si kullanılarak öykünür. Bu nedenle, Windows'ta bu ilk çağrıldığında ve sonraki 5 saniye boyunca anlamsız bir tanımlama grubu döndürecektir. Döndürülen sayılar, yalnızca sistemde kurulu CPU çekirdeklerinin sayısıyla ilgiliyse anlamlıdır.
Örneğin, 3.14 değeri 10 mantıksal CPU'lu bir sistemde, sistem yükünün son N dakika boyunca yüzde 31,4 olduğu anlamına gelir.
```
[x / psutil.cpu_count() * 100 for x in psutil.getloadavg()]
```
## Memory
```
# It gives information about ram in bytes.
psutil.virtual_memory() # Ram hakkında bilgiler verir Byte olarak.
```
* used: memory used, calculated differently depending on the platform and designed for informational purposes only. total - free does not necessarily match used.
* free: memory not being used at all (zeroed) that is readily available; note that this doesn’t reflect the actual memory available (use available instead). total - used does not necessarily match free.
* active (UNIX): memory currently in use or very recently used, and so it is in RAM.
* inactive (UNIX): memory that is marked as not used.
* buffers (Linux, BSD): cache for things like file system metadata.
* cached (Linux, BSD): cache for various things.
* shared (Linux, BSD): memory that may be simultaneously accessed by multiple processes.
* slab (Linux): in-kernel data structures cache.
* wired (BSD, macOS): memory that is marked to always stay in RAM. It is never moved to disk.
The sum of used and available does not necessarily equal total. On Windows available and free are the same.
* kullanılan: kullanılan bellek, platforma bağlı olarak farklı şekilde hesaplanır ve yalnızca bilgi amaçlı tasarlanmıştır. toplam - ücretsiz, kullanılanla mutlaka eşleşmez.
* boş: hiç kullanılmayan (sıfırlanmış) ve hazır bellek; bunun mevcut gerçek belleği yansıtmadığını unutmayın (bunun yerine kullanılabilir belleği kullanın). toplam - kullanılan mutlaka ücretsiz eşleşmez.
* aktif (UNIX): şu anda kullanımda olan veya çok yakın zamanda kullanılan bellek ve bu nedenle RAM'dedir.
* etkin değil (UNIX): Kullanılmıyor olarak işaretlenmiş bellek.
* arabellekler (Linux, BSD): dosya sistemi meta verileri gibi şeyler için önbellek.
* önbelleğe alınmış (Linux, BSD): çeşitli şeyler için önbellek.
* paylaşılan (Linux, BSD): birden fazla işlem tarafından aynı anda erişilebilen bellek.
* levha (Linux): çekirdek içi veri yapıları önbelleği.
* kablolu (BSD, macOS): Her zaman RAM'de kalacak şekilde işaretlenmiş bellek. Asla diske taşınmaz.
Kullanılan ve kullanılabilir toplamı mutlaka toplam eşit değildir. Windows'ta kullanılabilir ve ücretsiz aynıdır.
```
dict(psutil.virtual_memory()._asdict())
psutil.virtual_memory().percent
```
Let's say you want to control the amount of RAM or limit a task. You can use code like below.
RAM miktarını kontrol etmek veya bir görevi sınırlandırmak istiyorsunuz diyelim. Aşağıda ki gibi bir kod kullanabilirsiniz.
```
mem = psutil.virtual_memory()
mem
THRESHOLD = 100 * 1024 * 1024 * 1024 # 100GB
if mem.available <= THRESHOLD:
print("WARNING!!!")
```
### Swap Memory:
* EN:
Swap Space is a partition on your hard disk that is reserved by the operating system. When the data to be processed does not fit in the cache (RAM), this section is used as "RAM" and thus the data flow and processes continue. Using swap space slows down operations because data read/write speeds on your disk are much slower than RAM. In the Linux operating system, this space is a reserved partition on the disk. However, in Microsoft operating systems, a file named "pagefile.sys" is created, data that does not fit into RAM is written in this area, and the size set in the Windows operating system setup is 1.5 times the average RAM amount and can be changed later. This created area is not normally visible to the user; but it is possible to see it with the programs of third party software manufacturers. In Linux operating systems, this area is determined by the user, it is usually allocated as twice the RAM value.
* TR:
Swap (Takas) Alanı, işletim sistemi tarafından sabit diskinizde ayrılmış bir bölümdür. İşlenecek veriler ön belleğe (RAM) sığmadığı zaman bu bölüm “RAM” gibi kullanılır ve böylelikle veri akışının ve proseslerinin devam etmesi sağlanır. Diskinizdeki veri okuma/yazma hızları RAM biriminden çok daha düşük olduğu için swap alanının kullanılması işlemleri yavaşlatır. Linux işletim sisteminde bu alan disk üzerindeki ayrılan bir bölümdür. Fakat Microsoft’a ait işletim sistemlerinde “pagefile.sys” isminde bir dosya oluşturulur, RAM’e sığmayan veri bu alana yazılır ve Windows işletim sistemi kurulumunda ayarlanan boyut ortalama RAM miktarının 1.5 katıdır ve daha sonradan değiştirilebilir. Bu oluşturulan alanı kullanıcı normal olarak göremez; ancak üçüncü parti yazılım üreticilerinin programları ile görmesi mümkündür. Linux işletim sistemlerinde bu alanı kullanıcı belirler, genelde RAM değerinin iki katı olarak ayrılır.
```
psutil.swap_memory()
```
* EN:
* total: total swap memory in bytes
* used: used swap memory in bytes
* free: free swap memory in bytes
* percent: the percentage usage calculated as (total - available) / total * 100
* sin: the number of bytes the system has swapped in from disk (cumulative)
* sout: the number of bytes the system has swapped out from disk (cumulative)
* TR:
* toplam: bayt cinsinden toplam takas belleği
* kullanılan: bayt olarak kullanılan takas belleği
* ücretsiz: bayt cinsinden ücretsiz takas belleği
* yüzde: (toplam - kullanılabilir) / toplam olarak hesaplanan kullanım yüzdesi * 100
* günah: sistemin diskten takas ettiği bayt sayısı (kümülatif)
* sout: sistemin diskten takas ettiği bayt sayısı (kümülatif)
```
psutil.disk_partitions()
```
* EN:
* device: the device path (e.g. "/dev/hda1"). On Windows this is the drive letter (e.g. "C:\\").
* mountpoint: the mount point path (e.g. "/"). On Windows this is the drive letter (e.g. "C:\\").
* fstype: the partition filesystem (e.g. "ext3" on UNIX or "NTFS" on Windows).
* opts: a comma-separated string indicating different mount options for the drive/partition. Platform-dependent.
* maxfile: the maximum length a file name can have.
* maxpath: the maximum length a path name (directory name + base file name) can have.
* TR:
* cihaz: cihaz yolu (ör. "/dev/hda1"). Windows'ta bu, sürücü harfidir (ör. "C:\\").
* bağlama noktası: bağlama noktası yolu (ör. "/"). Windows'ta bu, sürücü harfidir (ör. "C:\\").
* fstype: bölüm dosya sistemi (örneğin, UNIX'te "ext3" veya Windows'ta "NTFS").
* opts: sürücü/bölüm için farklı bağlama seçeneklerini gösteren virgülle ayrılmış bir dize. Platforma bağlı.
* maxfile: bir dosya adının sahip olabileceği maksimum uzunluk.
* maxpath: bir yol adının (dizin adı + temel dosya adı) sahip olabileceği maksimum uzunluk.
```
psutil.disk_usage('/') # şuanki diskin kullanım oranı/path verip diğer disklere bakabilirsiniz
psutil.disk_io_counters(perdisk=True, nowrap=True)
```
* EN:
* read_count: number of reads
* write_count: number of writes
* read_bytes: number of bytes read
* write_bytes: number of bytes written
Platform-specific fields:
* read_time: (all except NetBSD and OpenBSD) time spent reading from disk (in milliseconds)
* write_time: (all except NetBSD and OpenBSD) time spent writing to disk (in milliseconds)
* busy_time: (Linux, FreeBSD) time spent doing actual I/Os (in milliseconds)
* read_merged_count (Linux): number of merged reads (see iostats doc)
* write_merged_count (Linux): number of merged writes (see iostats doc)
* TR:
* read_count: okuma sayısı
* write_count: yazma sayısı
* read_bytes: okunan bayt sayısı
* write_bytes: yazılan bayt sayısı
Platforma özel alanlar:
* read_time: (NetBSD ve OpenBSD hariç tümü) diskten okumaya harcanan süre (milisaniye olarak)
* write_time: (NetBSD ve OpenBSD hariç tümü) diske yazmak için harcanan süre (milisaniye olarak)
* meşgul_zaman: (Linux, FreeBSD) gerçek G/Ç'leri yapmak için harcanan süre (milisaniye cinsinden)
* read_merged_count (Linux): birleştirilmiş okuma sayısı (bkz. iostats doc)
* write_merged_count (Linux): birleştirilmiş yazma sayısı (bkz. iostats doc)
## Network
```
psutil.net_io_counters(pernic=False, nowrap=True)
```
* EN:
Return system-wide network I/O statistics as a named tuple including the following attributes:
* bytes_sent: number of bytes sent
* bytes_recv: number of bytes received
* packets_sent: number of packets sent
* packets_recv: number of packets received
* errin: total number of errors while receiving
* errout: total number of errors while sending
* dropin: total number of incoming packets which were dropped
* dropout: total number of outgoing packets which were dropped (always 0 on macOS and BSD)
* TR:
Aşağıdaki öznitelikleri içeren adlandırılmış bir demet olarak sistem genelinde ağ G/Ç istatistiklerini döndürün:
* bytes_sent: gönderilen bayt sayısı
* bytes_recv: alınan bayt sayısı
* packages_sent: gönderilen paket sayısı
* packages_recv: alınan paket sayısı
* errin: alınırken oluşan toplam hata sayısı
* errout: gönderirken toplam hata sayısı
* dropin: bırakılan toplam gelen paket sayısı
* bırakma: bırakılan toplam giden paket sayısı (macOS ve BSD'de her zaman 0)
```
#psutil.net_connections(kind='inet')
```
* EN:
* fd: the socket file descriptor. If the connection refers to the current process this may be passed to socket.fromfd to obtain a usable socket object. On Windows and SunOS this is always set to -1.
* family: the address family, either AF_INET, AF_INET6 or AF_UNIX.
* type: the address type, either SOCK_STREAM, SOCK_DGRAM or SOCK_SEQPACKET.
* laddr: the local address as a (ip, port) named tuple or a path in case of AF_UNIX sockets. For UNIX sockets see notes below.
* raddr: the remote address as a (ip, port) named tuple or an absolute path in case of UNIX sockets. When the remote endpoint is not connected you’ll get an empty tuple (AF_INET*) or "" (AF_UNIX). For UNIX sockets see notes below.
* status: represents the status of a TCP connection. The return value is one of the psutil.CONN_* constants (a string). For UDP and UNIX sockets this is always going to be psutil.CONN_NONE.
* pid: the PID of the process which opened the socket, if retrievable, else None. On some platforms (e.g. Linux) the availability of this field changes depending on process privileges (root is needed).
* TR:
* fd: soket dosyası tanımlayıcısı. Bağlantı mevcut sürece atıfta bulunuyorsa, bu, kullanılabilir bir soket nesnesi elde etmek için socket.fromfd'ye iletilebilir. Windows ve SunOS'ta bu her zaman -1'e ayarlıdır.
* ailesi: AF_INET, AF_INET6 veya AF_UNIX adres ailesi.
* tür: adres türü, SOCK_STREAM, SOCK_DGRAM veya SOCK_SEQPACKET.
* laddr: AF_UNIX soketleri olması durumunda, bir (ip, port) olarak adlandırılan demet veya bir yol olarak yerel adres. UNIX soketleri için aşağıdaki notlara bakın.
* raddr: UNIX soketleri durumunda, tuple adında bir (ip, port) veya mutlak yol olarak uzak adres. Uzak uç nokta bağlı olmadığında boş bir demet (AF_INET*) veya "" (AF_UNIX) alırsınız. UNIX soketleri için aşağıdaki notlara bakın.
* durum: bir TCP bağlantısının durumunu temsil eder. Dönüş değeri, psutil.CONN_* sabitlerinden biridir (bir dize). UDP ve UNIX soketleri için bu her zaman psutil.CONN_NONE olacaktır.
* pid: Alınabiliyorsa, soketi açan işlemin PID'si, aksi takdirde Yok. Bazı platformlarda (örneğin Linux) bu alanın kullanılabilirliği işlem ayrıcalıklarına bağlı olarak değişir (kök gereklidir).
```
#psutil.net_if_addrs()
```
* EN:
* family: the address family, either AF_INET or AF_INET6 or psutil.AF_LINK, which refers to a MAC address.
* address: the primary NIC address (always set).
* netmask: the netmask address (may be None).
* broadcast: the broadcast address (may be None).
* ptp: stands for “point to point”; it’s the destination address on a point to point interface (typically a VPN). broadcast and ptp are mutually exclusive. May be None.
* TR:
* aile: bir MAC adresine atıfta bulunan AF_INET veya AF_INET6 veya psutil.AF_LINK adres ailesi.
* adres: birincil NIC adresi (her zaman ayarlanır).
* ağ maskesi: ağ maskesi adresi (Yok olabilir).
* yayın: yayın adresi (Yok olabilir).
* ptp: "noktadan noktaya" anlamına gelir; noktadan noktaya arabirimdeki (genellikle bir VPN) hedef adrestir. yayın ve ptp birbirini dışlar. Hiçbiri olabilir.
```
psutil.net_if_stats()
```
* EN:
* isup: a bool indicating whether the NIC is up and running (meaning ethernet cable or Wi-Fi is connected).
* duplex: the duplex communication type; it can be either NIC_DUPLEX_FULL, NIC_DUPLEX_HALF or NIC_DUPLEX_UNKNOWN.
* speed: the NIC speed expressed in mega bits (MB), if it can’t be determined (e.g. ‘localhost’) it will be set to 0.
* mtu: NIC’s maximum transmission unit expressed in bytes.
* TR:
* isup: NIC'nin çalışır durumda olup olmadığını gösteren bir bool (ethernet kablosu veya Wi-Fi bağlı olduğu anlamına gelir).
* dubleks: dubleks iletişim tipi; NIC_DUPLEX_FULL, NIC_DUPLEX_HALF veya NIC_DUPLEX_UNKNOWN olabilir.
* hız: mega bit (MB) cinsinden ifade edilen NIC hızı, belirlenemezse (ör. "localhost") 0 olarak ayarlanır.
* mtu: NIC'nin bayt cinsinden ifade edilen maksimum aktarım birimi.
## Sensors
* EN:
Get hardware temperatures. Each entry is a named bundle representing a specific hardware temperature sensor (it could be a CPU, a hard disk, or something else, depending on the OS and configuration). All temperatures are expressed in degrees Celsius can also be taken in degrees Fahrenheit. It doesn't apply to most Windows, so it's in the comment line.
* TR:
Donanım sıcaklıklarını alın. Her giriş, belirli bir donanım sıcaklık sensörünü temsil eden adlandırılmış bir demettir (işletim sistemine ve yapılandırmasına bağlı olarak bir CPU, bir sabit disk veya başka bir şey olabilir). Tüm sıcaklıklar santigrat olarak ifade edilmiştir fahrenhayt olarak da alınabilir. Çoğu Windows için geçerli değildir o nedenle yorum satırındadır.
```
#psutil.sensors_temperatures(fahrenheit=False)
#psutil.sensors_fans()
psutil.sensors_battery()
```
* EN:
* percent: battery power left as a percentage.
* secsleft: a rough approximation of how many seconds are left before the battery runs out of power. If the AC power cable is connected this is set to psutil.POWER_TIME_UNLIMITED. If it can’t be determined it is set to psutil.POWER_TIME_UNKNOWN.
* power_plugged: True if the AC power cable is connected, False if not or None if it can’t be determined.
* TR:
* percent: yüzde olarak kalan pil gücü.
* secsleft: pilin bitmesine kaç saniye kaldığının kabaca bir tahmini. AC güç kablosu bağlıysa bu, psutil.POWER_TIME_UNLIMITED olarak ayarlanır. Belirlenemiyorsa psutil.POWER_TIME_UNKNOWN olarak ayarlanır.
* power_plugged: AC güç kablosu bağlıysa Doğru, Değilse Yanlış veya belirlenemezse Hiçbiri.
```
#battery = psutil.sensors_battery()
#print("charge = %s%%, time left = %s" % (battery.percent, secs2hours(battery.secsleft)))
```
## Diğer sistem bilgileri
```
psutil.boot_time()
datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
psutil.users()
```
* EN:
* name: the name of the user.
* terminal: the tty or pseudo-tty associated with the user, if any, else None.
* host: the host name associated with the entry, if any.
* started: the creation time as a floating point number expressed in seconds since the epoch.
* pid: the PID of the login process (like sshd, tmux, gdm-session-worker, …). On Windows and OpenBSD this is always set to None.
* TR:
* name: kullanıcının adı.
* terminal: varsa, kullanıcıyla ilişkili tty veya sözde tty, yoksa Yok.
* ana bilgisayar: varsa, girişle ilişkili ana bilgisayar adı.
* başladı: Çağdan bu yana saniye cinsinden ifade edilen kayan nokta sayısı olarak oluşturma süresi.
* pid: oturum açma işleminin PID'si (sshd, tmux, gdm-session-worker, … gibi). Windows ve OpenBSD'de bu her zaman Yok olarak ayarlanır.
## Processes
### Functions
* EN:
PID: proportional-integral-derivative controller control loop method is a feedback controller method commonly used in industrial control systems. A PID controller continuously calculates an error value, ie the difference between the intended system state and the current system state. The controller tries to minimize the error by adjusting the process control input.
* TR:
PID (İngilizce: Proportional Integral Derivative) oransal-integral-türevsel denetleyici kontrol döngüsü yöntemi, endüstriyel kontrol sistemlerinde yaygın olarak kullanılan bir geri besleme denetleyicisi yöntemidir. Bir PID denetleyici sürekli olarak bir hata değerini, yani amaçlanan sistem durumu ile mevcut sistem durumu arasındaki farkı hesaplar. Denetleyici süreç kontrol girdisini ayarlayarak hatayı en aza indirmeye çalışır.
```
psutil.pids() # Return a sorted list of current running PIDs/Geçerli çalışan PID'lerin sıralanmış bir listesini döndürün.
psutil.process_iter()
# Bir Generator oluşturur ve hayatta olan PID'leri döndürebilirsiniz.
# It creates a Generator and you can return surviving PIDs.
for proc in psutil.process_iter(['pid', 'name', 'username']):
print(proc.info)
procs = {p.pid: p.info for p in psutil.process_iter(['name', 'username'])}
procs
#psutil.pid_exists(pid) # vermiş olduğunuz PID'i sorgular/Queries the PID you have given
def on_terminate(proc):
print("process {} terminated with exit code {}".format(proc, proc.returncode))
procs = psutil.Process().children()
for p in procs:
p.terminate()
gone, alive = psutil.wait_procs(procs, timeout=3, callback=on_terminate)
for p in alive:
p.kill()
#on_terminate(procs)
psutil.wait_procs(procs, timeout=None, callback=None)
```
Oneshot: Utility context manager which considerably speeds up the retrieval of multiple process information at the same time
Oneshot: Aynı anda birden fazla işlem bilgisinin alınmasını önemli ölçüde hızlandıran yardımcı program bağlam yöneticisi
```
p = psutil.Process()
with p.oneshot():
print(p.name())# execute internal routine once collecting multiple info/birden fazla bilgi topladıktan sonra dahili rutini yürütün
print(p.cpu_times())
print(p.cpu_percent())
print(p.create_time())
print(p.ppid())
list(psutil.Process().as_dict().keys())
p.memory_maps()
p.exe() # The environment variables of the process as a dict. Note: this might not reflect changes made after the process started.
#Bir dict olarak sürecin ortam değişkenleri. Not: Bu, işlem başladıktan sonra yapılan değişiklikleri yansıtmayabilir.
p.cmdline() #The command line this process has been called with as a list of strings. The return value is not cached because the cmdline of a process may change.
#Bu işlemin komut satırı, bir dize listesi olarak çağrıldı. Bir işlemin cmdline'ı değişebileceğinden dönüş değeri önbelleğe alınmaz.
#p.environ()
#The environment variables of the process as a dict. Note: this might not reflect changes made after the process started.
# Bir dict olarak sürecin ortam değişkenleri. Not: Bu, işlem başladıktan sonra yapılan değişiklikleri yansıtmayabilir.
#p.as_dict(attrs=None, ad_value=None)
p.parent()
#Utility method which returns the parent process as a Process object, preemptively checking whether PID has been reused. If no parent PID is known return None.
#PID'nin yeniden kullanılıp kullanılmadığını önceden kontrol ederek, üst işlemi bir İşlem nesnesi olarak döndüren yardımcı program yöntemi. Bilinen bir üst PID yoksa, None döndür
p.parents()
p.status()
p.cwd()
p.username()
#p.uids()
#The real, effective and saved user ids of this process as a named tuple.
# Bu işlemin gerçek, etkili ve kaydedilmiş kullanıcı kimlikleri, adlandırılmış bir demet olarak paylaşır.
#p.gids()
#The real, effective and saved group ids of this process as a named tuple
#Bu işlemin gerçek, etkili ve kaydedilmiş kullanıcı kimlikleri, adlandırılmış bir demet olarak paylaşır.
p.nice()# bu parametre önceliği ayarlamayı sağlar ama UNIX'te. Windowsta sadece çıktı verir.
#Get or set process niceness (priority).
if psutil.LINUX:
p.ionice(psutil.IOPRIO_CLASS_RT, value=7)
else:
p.ionice(psutil.IOPRIO_NORMAL)
```
* EN:
Linux (see ioprio_get manual):
* IOPRIO_CLASS_RT: (high) the process gets first access to the disk every time. Use it with care as it can starve the entire system. Additional priority level can be specified and ranges from 0 (highest) to 7 (lowest).
* IOPRIO_CLASS_BE: (normal) the default for any process that hasn’t set a specific I/O priority. Additional priority level ranges from 0 (highest) to 7 (lowest).
* IOPRIO_CLASS_IDLE: (low) get I/O time when no-one else needs the disk. No additional value is accepted.
* IOPRIO_CLASS_NONE: returned when no priority was previously set.
Windows:
* IOPRIO_HIGH: highest priority.
* IOPRIO_NORMAL: default priority.
* IOPRIO_LOW: low priority.
* IOPRIO_VERYLOW: lowest priority.
* TR:
Linux (ioprio_get kılavuzuna bakın):
* IOPRIO_CLASS_RT: (yüksek) işlem her seferinde diske ilk erişim sağlar. Tüm sistemi aç bırakabileceğinden dikkatli kullanın. Ek öncelik seviyesi belirtilebilir ve 0 (en yüksek) ile 7 (en düşük) arasında değişir.
* IOPRIO_CLASS_BE: (normal) belirli bir G/Ç önceliği belirlememiş herhangi bir işlem için varsayılan. Ek öncelik seviyesi 0 (en yüksek) ile 7 (en düşük) arasında değişir.
* IOPRIO_CLASS_IDLE: (düşük) kimsenin diske ihtiyacı olmadığında G/Ç zamanı elde edin. Ek değer kabul edilmez.
* IOPRIO_CLASS_NONE: daha önce hiçbir öncelik ayarlanmadığında döndürülür.
Pencereler:
* IOPRIO_HIGH: en yüksek öncelik.
* IOPRIO_NORMAL: varsayılan öncelik.
* IOPRIO_LOW: düşük öncelik.
* IOPRIO_VERYLOW: en düşük öncelik.
```
p.ionice() # get
#p.rlimit(psutil.RLIMIT_NOFILE, (128, 128)) # process can open max 128 file descriptors/işlem maksimum 128 dosya tanımlayıcı açabilir
#p.rlimit(psutil.RLIMIT_FSIZE, (1024, 1024)) # can create files no bigger than 1024 bytes/1024 bayttan büyük olmayan dosyalar oluşturabilir
#p.rlimit(psutil.RLIMIT_FSIZE) # get/al
```
Get or set process resource limits.
İşlem kaynak sınırlarını alın veya ayarlayın.
```
p.io_counters()
```
* EN:
Return process I/O statistics as a named tuple.
* read_count: the number of read operations performed (cumulative). This is supposed to count the number of read-related syscalls such as read() and pread() on UNIX.
* write_count: the number of write operations performed (cumulative). This is supposed to count the number of write-related syscalls such as write() and pwrite() on UNIX.
* read_bytes: the number of bytes read (cumulative). Always -1 on BSD.
* write_bytes: the number of bytes written (cumulative). Always -1 on BSD.
Linux specific:
* read_chars (Linux): the amount of bytes which this process passed to read() and pread() syscalls (cumulative). Differently from read_bytes it doesn’t care whether or not actual physical disk I/O occurred.
* write_chars (Linux): the amount of bytes which this process passed to write() and pwrite() syscalls (cumulative). Differently from write_bytes it doesn’t care whether or not actual physical disk I/O occurred.
Windows specific:
* other_count (Windows): the number of I/O operations performed other than read and write operations.
* other_bytes (Windows): the number of bytes transferred during operations other than read and write operations.
* TR:
İşlem G/Ç istatistiklerini adlandırılmış bir demet olarak döndürür.
* read_count: gerçekleştirilen okuma işlemlerinin sayısı (kümülatif). Bunun UNIX'te read() ve pread() gibi okuma ile ilgili sistem çağrılarının sayısını sayması beklenir.
* write_count: gerçekleştirilen yazma işlemlerinin sayısı (kümülatif). Bunun UNIX'te write() ve pwrite() gibi yazma ile ilgili sistem çağrılarının sayısını sayması beklenir.
* read_bytes: okunan bayt sayısı (kümülatif). BSD'de her zaman -1.
* write_bytes: yazılan bayt sayısı (kümülatif). BSD'de her zaman -1.
Linux'a özgü:
* read_chars (Linux): Bu işlemin read() ve pread() sistem çağrılarına (kümülatif) ilettiği bayt miktarı. Read_bytes'den farklı olarak, gerçek fiziksel disk G/Ç'sinin oluşup oluşmadığı umurunda değildir.
* write_chars (Linux): bu işlemin write() ve pwrite() sistem çağrılarına (kümülatif) ilettiği bayt miktarı. Write_bytes'den farklı olarak, gerçek fiziksel disk G/Ç'nin oluşup oluşmadığı umurunda değildir.
Windows'a özgü:
* other_count (Windows): okuma ve yazma işlemleri dışında gerçekleştirilen G/Ç işlemlerinin sayısı.
* other_bytes (Windows): okuma ve yazma işlemleri dışındaki işlemler sırasında aktarılan bayt sayısı.
```
p.num_ctx_switches()
# The number voluntary and involuntary context switches performed by this process (cumulative).
# Bu süreç tarafından gerçekleştirilen gönüllü ve gönülsüz bağlam anahtarlarının sayısı (kümülatif).
#p.num_fds()
p.num_handles() # The number of handles currently used by this process (non cumulative).
# Şu anda bu işlem tarafından kullanılan tanıtıcı sayısı (kümülatif olmayan).
p.num_threads()
# Return threads opened by process as a list of named tuples including thread id and thread CPU times (user/system). On OpenBSD this method requires root privileges.
# İşlem tarafından açılan iş parçacıklarını, iş parçacığı kimliği ve iş parçacığı CPU süreleri (kullanıcı/sistem) dahil olmak üzere adlandırılmış kümelerin bir listesi olarak döndürün. OpenBSD'de bu yöntem kök ayrıcalıkları gerektirir.
p.threads()
# Return threads opened by process as a list of named tuples including thread id and thread CPU times (user/system). On OpenBSD this method requires root privileges.
# İşlem tarafından açılan iş parçacıklarını, iş parçacığı kimliği ve iş parçacığı CPU süreleri (kullanıcı/sistem) dahil olmak üzere adlandırılmış kümelerin bir listesi olarak döndürün. OpenBSD'de bu yöntem kök ayrıcalıkları gerektirir.
p.cpu_times()
#Return a named tuple representing the accumulated process times, in seconds
# Saniye cinsinden birikmiş işlem sürelerini temsil eden adlandırılmış bir demet döndür
```
* EN:
* user: time spent in user mode.
* system: time spent in kernel mode.
* children_user: user time of all child processes (always 0 on Windows and macOS).
* children_system: system time of all child processes (always 0 on Windows and macOS).
* iowait: (Linux) time spent waiting for blocking I/O to complete. This value is excluded from user and system times count (because the CPU is not doing any work).
* TR:
* User: kullanıcı modunda geçirilen süre.
* sistem: çekirdek modunda harcanan zaman.
* children_user: tüm alt süreçlerin kullanıcı zamanı (Windows ve macOS'ta her zaman 0).
* Children_system: tüm alt süreçlerin sistem zamanı (Windows ve macOS'ta her zaman 0).
* iowait: (Linux) G/Ç'nin tamamlanmasını engellemek için harcanan süre. Bu değer, kullanıcı ve sistem süreleri sayımından hariç tutulur (çünkü CPU herhangi bir iş yapmıyor).
```
sum(p.cpu_times()[:2]) # cumulative, excluding children and iowait
#kümülatif, Children ve iowait hariç
p.cpu_percent(interval=1)
p.cpu_percent(interval=None)
```
* EN:
Get or set process current CPU affinity. CPU affinity consists in telling the OS to run a process on a limited set of CPUs only (on Linux cmdline, taskset command is typically used). If no argument is passed it returns the current CPU affinity as a list of integers. If passed it must be a list of integers specifying the new CPUs affinity. If an empty list is passed all eligible CPUs are assumed (and set). On some systems such as Linux this may not necessarily mean all available logical CPUs as in list(range(psutil.cpu_count()))).
* TR:
Mevcut CPU benzeşimini alın veya ayarlayın. CPU benzeşimi, işletim sistemine yalnızca sınırlı bir CPU kümesinde bir işlemi çalıştırmasını söylemekten oluşur (Linux cmdline'da genellikle görev kümesi komutu kullanılır). Herhangi bir argüman iletilmezse, mevcut CPU benzeşimini bir tamsayı listesi olarak döndürür. Geçilirse, yeni CPU'ların benzerliğini belirten bir tamsayı listesi olmalıdır. Boş bir listeden geçilirse, tüm uygun CPU'lar varsayılır (ve ayarlanır). Linux gibi bazı sistemlerde bu, list(range(psutil.cpu_count()))'daki gibi tüm kullanılabilir mantıksal CPU'lar anlamına gelmeyebilir.
```
p.cpu_affinity()
# set; from now on, process will run on CPU #0 and #1 only
p.cpu_affinity([0, 1])
# Ayarlama; bundan sonra işlem sadece CPU #0 ve #1 üzerinde çalışacak
p.cpu_affinity()
# reset affinity against all eligible CPUs
p.cpu_affinity([])
# tüm uygun CPU'lara karşı yakınlığı sıfırla
#check
p.cpu_affinity()
#p.cpu_num()
#Return what CPU this process is currently running on.
# Bu işlemin şu anda hangi CPU üzerinde çalıştığını döndürün.
p.memory_full_info()
```
* EN:
* rss: aka “Resident Set Size”, this is the non-swapped physical memory a process has used. On UNIX it matches “top“‘s RES column). On Windows this is an alias for wset field and it matches “Mem Usage” column of taskmgr.exe.
* vms: aka “Virtual Memory Size”, this is the total amount of virtual memory used by the process. On UNIX it matches “top“‘s VIRT column. On Windows this is an alias for pagefile field and it matches “Mem Usage” “VM Size” column of taskmgr.exe.
* shared: (Linux) memory that could be potentially shared with other processes. This matches “top“‘s SHR column).text (Linux, BSD): aka TRS (text resident set) the amount of memory devoted to executable code. This matches “top“‘s CODE column).data (Linux, BSD): aka DRS (data resident set) the amount of physical memory devoted to other than executable code. It matches “top“‘s DATA column).
* lib (Linux): the memory used by shared libraries.
* dirty (Linux): the number of dirty pages.
* pfaults (macOS): number of page faults.
* pageins (macOS): number of actual pageins.
* TR:
* rss: namı diğer "Yerleşik Küme Boyutu", bu, bir işlemin kullandığı takas edilmeyen fiziksel bellektir. UNIX'te "top"un RES sütunuyla eşleşir). Windows'ta bu, wset alanı için bir takma addır ve taskmgr.exe'nin "Mem Kullanımı" sütunuyla eşleşir.
* vms: namı diğer “Sanal Bellek Boyutu”, bu işlem tarafından kullanılan toplam sanal bellek miktarıdır. UNIX'te "top"un VIRT sütunuyla eşleşir. Windows'ta bu, sayfa dosyası alanı için bir takma addır ve taskmgr.exe'nin "Mem Kullanımı" "VM Boyutu" sütunuyla eşleşir.
* paylaşılan: (Linux) diğer işlemlerle potansiyel olarak paylaşılabilen bellek. Bu, "top"un SHR sütunuyla eşleşir.text (Linux, BSD): aka TRS (metin yerleşik seti), yürütülebilir koda ayrılan bellek miktarı. Bu, "top"un KOD sütunu ile eşleşir.data (Linux, BSD): aka DRS (veri yerleşik seti), yürütülebilir kod dışındakilere ayrılmış fiziksel bellek miktarı. "top"un DATA sütunuyla eşleşir).
* lib (Linux): paylaşılan kütüphaneler tarafından kullanılan bellek.
* kirli (Linux): kirli sayfa sayısı.
* pfaults (macOS): sayfa hatası sayısı.
* sayfa girişleri (macOS): gerçek sayfa girişlerinin sayısı.
```
p.memory_percent(memtype="rss")
#Compare process memory to total physical system memory and calculate process memory utilization as a percentage.memtype argument is a string that dictates what type of process memory you want to compare against.
#İşlem belleğini toplam fiziksel sistem belleğiyle karşılaştırın ve işlem belleği kullanımını bir yüzde olarak hesaplayın.memtype bağımsız değişkeni, ne tür işlem belleğiyle karşılaştırmak istediğinizi belirten bir dizedir.
f = open('file.txt', 'w') # bu sırada bulundugunuz dizinde bir txt oluşturun ve bu komutu çalıştırın
# create a txt in your current directory and run this command
p.open_files()
```
* EN:
Return regular files opened by process as a list of named tuples including the following fields:
* path: the absolute file name.
* fd: the file descriptor number; on Windows this is always -1.
Linux only:
* position (Linux): the file (offset) position.
* mode (Linux): a string indicating how the file was opened, similarly to open builtin mode argument. Possible values are 'r', 'w', 'a', 'r+' and 'a+'. There’s no distinction between files opened in binary or text mode ("b" or "t").
* flags (Linux): the flags which were passed to the underlying os.open C call when the file was opened (e.g. os.O_RDONLY, os.O_TRUNC, etc).
* TR:
Aşağıdaki alanları içeren adlandırılmış demetlerin bir listesi olarak işlem tarafından açılan normal dosyaları döndürün:
* yol: mutlak dosya adı.
* fd: dosya tanıtıcı numarası; Windows'ta bu her zaman -1'dir.
Yalnızca Linux:
* konum (Linux): dosya (ofset) konumu.
* modu (Linux): açık yerleşik mod bağımsız değişkenine benzer şekilde dosyanın nasıl açıldığını gösteren bir dize. Olası değerler 'r', 'w', 'a', 'r+' ve 'a+'dır. İkili veya metin modunda ("b" veya "t") açılan dosyalar arasında hiçbir ayrım yoktur.
* bayraklar (Linux): dosya açıldığında temeldeki os.open C çağrısına geçirilen bayraklar (örn. os.O_RDONLY, os.O_TRUNC, vb.).
```
#p.connections(kind="inet")
```
* EN:
Return socket connections opened by process as a list of named tuples. To get system-wide connections use psutil.net_connections(). Every named tuple provides 6 attributes:
* fd: the socket file descriptor. This can be passed to socket.fromfd to obtain a usable socket object. On Windows, FreeBSD and SunOS this is always set to -1.
* family: the address family, either AF_INET, AF_INET6 or AF_UNIX.
* type: the address type, either SOCK_STREAM, SOCK_DGRAM or SOCK_SEQPACKET. .
* laddr: the local address as a (ip, port) named tuple or a path in case of AF_UNIX sockets. For UNIX sockets see notes below.
* raddr: the remote address as a (ip, port) named tuple or an absolute path in case of UNIX sockets. When the remote endpoint is not connected you’ll get an empty tuple (AF_INET*) or "" (AF_UNIX). For UNIX sockets see notes below.
* status: represents the status of a TCP connection. The return value is one of the psutil.CONN_* constants. For UDP and UNIX sockets this is always going to be psutil.CONN_NONE.
* TR:
İşlem tarafından açılan yuva bağlantılarını adlandırılmış demetlerin bir listesi olarak döndürün. Sistem çapında bağlantılar elde etmek için psutil.net_connections() kullanın. Her adlandırılmış demet 6 nitelik sağlar:
* fd: soket dosyası tanımlayıcısı. Bu, kullanılabilir bir soket nesnesi elde etmek için socket.fromfd'ye geçirilebilir. Windows, FreeBSD ve SunOS'ta bu her zaman -1'e ayarlıdır.
* ailesi: AF_INET, AF_INET6 veya AF_UNIX adres ailesi.
* tür: adres türü, SOCK_STREAM, SOCK_DGRAM veya SOCK_SEQPACKET. .
* laddr: AF_UNIX soketleri olması durumunda, bir (ip, port) olarak adlandırılan demet veya bir yol olarak yerel adres. UNIX soketleri için aşağıdaki notlara bakın.
* raddr: UNIX soketleri durumunda, tuple adında bir (ip, port) veya mutlak yol olarak uzak adres. Uzak uç nokta bağlı olmadığında boş bir demet (AF_INET*) veya "" (AF_UNIX) alırsınız. UNIX soketleri için aşağıdaki notlara bakın.
* durum: bir TCP bağlantısının durumunu temsil eder. Dönüş değeri, psutil.CONN_* sabitlerinden biridir. UDP ve UNIX soketleri için bu her zaman psutil.CONN_NONE olacaktır.
```
p = psutil.Process(4)
p.name()
#p.connections()
```
Return whether the current process is running in the current process list. This is reliable also in case the process is gone and its PID reused by another process, therefore it must be preferred over doing psutil.pid_exists(p.pid)
Geçerli işlemin geçerli işlem listesinde çalışıp çalışmadığını döndürür. Bu, işlemin sona ermesi ve PID'sinin başka bir işlem tarafından yeniden kullanılması durumunda da güvenilirdir, bu nedenle psutil.pid_exists(p.pid) yapmak yerine tercih edilmelidir.
```
p.is_running()
#p.suspend() # çalışanı askıya al/suspend the task
#p.resume() # devam ettir/contunie
#p.kill() # öldür/kill
#p.wait(timeout=None) # işin bitmesini bekle/wait for the job to be done
```
## Windows services
```
psutil.win_service_iter() #Return an iterator yielding a WindowsService class instance for all Windows services installed.
#Yüklü tüm Windows hizmetleri için bir WindowsService sınıfı örneği veren bir yineleyici döndürün.
#list(psutil.win_service_iter())
```
Get a Windows service by name, returning a WindowsService instance. Raise psutil.NoSuchProcess if no service with such name exists.
Bir Windows Hizmeti örneği döndürerek ada göre bir Windows hizmeti alın. Bu ada sahip bir hizmet yoksa psutil.NoSuchProcess'i yükseltin.
```
s = psutil.win_service_get('alg')
s.as_dict()
```
Represents a Windows service with the given name. This class is returned by win_service_iter() and win_service_get() functions and it is not supposed to be instantiated directly.
Verilen ada sahip bir Windows hizmetini temsil eder. Bu sınıf, win_service_iter() ve win_service_get() işlevleri tarafından döndürülür ve doğrudan örneklenmesi gerekmez.
| github_jupyter |
# PP Attachment
Let's try out the Preposition Phrase attachment classification!
Through this exercise, you'll practice classification of linguistic aspects of text.
# Setup
Loading the data
```
import csv
from tqdm.notebook import tqdm
from random import choice
from urllib.request import urlopen
def read_pp_examples(file_url):
pp_examples = []
for line in tqdm(urlopen(file_url)):
line = line.decode("utf-8").strip().split()
assert(len(line) == 5)
v,n1,p,n2,answer = line
pp_examples.append( {'answer':answer,'pp':(v,n1,p,n2)} )
return pp_examples
pp_samples_url = 'https://raw.githubusercontent.com/liadmagen/Modeling_course/main/data/pp_examples.txt'
pp_examples = read_pp_examples(pp_samples_url)
```
# Step #1 - looking at the data
Always look at the data first!
```
len(pp_examples)
print(choice(pp_examples))
example = choice(pp_examples)
example['pp']
example['answer']
```
# Step 2: Deciding on the measurement
```
amt = int(0.75 * len(pp_examples))
train_examples, test_examples = pp_examples[:amt], pp_examples[amt:]
print(len(train_examples), len(test_examples))
```
We'll define a classifier evaluator.
Given a set of examples and an evaluator, it returns the accuracy score
```
def evaluate_classifier(examples, pp_resolver):
"""
examples: a list of {'pp':(v,n1,p,n2), 'answer':answer }
pp_resolver has a classify() function: from (v,n1,p,n2) to 'N' / 'V'
"""
correct = 0.0
incorrect = 0.0
for example in examples:
answer = pp_resolver.classify(example['pp'])
if answer == example['answer']:
correct += 1
else:
incorrect += 1
return correct / (correct + incorrect)
```
# Classifiers
Let's test it on an extremely naive classifiers:
```
class AlwaysSayN:
"""
This naive clasifier answers always with 'Noun'
"""
def __init__(self): pass
def classify(self, pp):
return 'N'
class AlwaysSayV:
"""
This naive clasifier answers always with 'Verb'
"""
def __init__(self): pass
def classify(self, pp):
return 'V'
evaluate_classifier(test_examples, AlwaysSayV())
evaluate_classifier(test_examples, AlwaysSayN())
```
We can see that saying always 'Noun', leads to an accuracy result of 53%.
---
It also means that our dataset is quite balaneced ;)
We could, instead, have tested which class has the majority and simply select it:
```
class MajorityClassResolver:
def __init__(self, training_examples):
answers = [item['answer'] for item in training_examples]
num_n = len([a for a in answers if a == 'N'])
num_v = len([a for a in answers if a == 'V'])
if num_v > num_n:
self.answer = 'V'
else:
self.answer = 'N'
def classify(self, pp):
return self.answer
evaluate_classifier(test_examples, MajorityClassResolver(train_examples))
```
Or make it a bit more sophisticated by peeking at the training examples:
```
class LookupResolver:
def __init__(self, training_examples):
self.answers = {}
for item in training_examples:
self.answers[item['pp']] = item['answer']
self.backoff = MajorityClassResolver(training_examples)
def classify(self, pp):
if pp in self.answers:
return self.answers[pp]
else:
return self.backoff.classify(pp)
evaluate_classifier(test_examples, LookupResolver(train_examples))
```
# Exercise (Optional) - Your Classifier:
Implement a discriminative PP-attachment model, using a classifier of your choice (i.e. - Naive Bayes Classifier https://web.stanford.edu/~jurafsky/slp3/4.pdf) from a toolkit such as [sklearn](https://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html#sklearn.naive_bayes.GaussianNB).
Possible features:
Single items
* Identity of v
* Identity of p
* Identity of n1
* Identity of n2
Pairs:
* Identity of (v, p)
* Identity of (n1, p)
* Identity of (p, n1)
Triplets:
* Identity of (v, n1, p)
* Identity of (v, p, n2)
* Identity of (n1, p, n2)
Quadruple:
* Identity of (v, n1, p, n2)
Corpus Level:
* Have we seen the (v, p) pair in a 5-word window in a big corpus?
* Have we seen the (n1, p) pair in a 5-word window in a big corpus?
* Have we seen the (n1, p, n2) triplet in a 5-word window in a big corpus?
* Also: we can use counts, or binned counts.
Distance:
* Distance (in words) between v and p
* Distance (in words) between n1 and p
Try thinking of additional text-features that may assist for this problem.
Note: You can use Bag-of-Words (BoW) with CountVectorizer to represent the words.
```
from sklearn.naive_bayes import GaussianNB
from sklearn.feature_extraction.text import CountVectorizer
class NaiveBayesClassifier():
def __init__(self, training_examples):
classifier = GaussianNB()
def classify(self, pp):
pass
evaluate_classifier(test_examples, NaiveBayesClassifier(train_examples))
```
| github_jupyter |
# Domain, Halo and Padding regions
In this tutorial we will learn about data regions and how these impact the `Operator` construction. We will use a simple time marching example.
```
from devito import Eq, Grid, TimeFunction, Operator
grid = Grid(shape=(3, 3))
u = TimeFunction(name='u', grid=grid)
u.data[:] = 1
```
At this point, we have a time-varying 3x3 grid filled with _1's_. Below, we can see the _domain_ data values:
```
print(u.data)
```
We now create a time-marching `Operator` that, at each timestep, increments by `2` all points in the computational domain.
```
from devito import configuration
configuration['openmp'] = 0
eq = Eq(u.forward, u+2)
op = Operator(eq, dle='noop')
```
We can print `op` to get the generated code.
```
print(op)
```
When we take a look at the constructed expression, `u[t1][x + 1][y + 1] = u[t0][x + 1][y + 1] + 2`, we see several `+1` were added to the `u`'s spatial indices.
This is because the domain region is actually surrounded by 'ghost' points, which can be accessed via a stencil when iterating in proximity of the domain boundary. The ghost points define the _halo region._ The halo region can be accessed through the `data_with_halo` data accessor. As we see below, the halo points correspond to the zeros surrounding the domain region.
```
print(u.data_with_halo)
```
By adding the `+1` offsets, the Devito compiler ensures the array accesses are logically aligned to the equation’s physical domain. For instance, the `TimeFunction` `u(t, x, y)` used in the example above has one point on each side of the `x` and `y` halo regions; if the user writes an expression including `u(t, x, y)` and `u(t, x + 2, y + 2)`, the compiler will ultimately generate `u[t, x + 1, y + 1]` and `u[t, x + 3, y + 3]`. When `x = y = 0`, therefore, the values `u[t, 1, 1]` and `u[t, 3, 3]` are fetched, representing the first and third points in the physical domain.
By default, the halo region has `space_order` points on each side of the space dimensions. Sometimes, these points may be unnecessary, or, depending on the partial differential equation being approximated, extra points may be needed.
```
u0 = TimeFunction(name='u0', grid=grid, space_order=0)
u0.data[:] = 1
print(u0.data_with_halo)
u2 = TimeFunction(name='u2', grid=grid, space_order=2)
u2.data[:] = 1
print(u2.data_with_halo)
```
One can also pass a 3-tuple `(o, lp, rp)` instead of a single integer representing the discretization order. Here, `o` is the discretization order, while `lp` and `rp` indicate how many points are expected on left and right sides of a point of interest, respectivelly.
```
u_new = TimeFunction(name='u_new', grid=grid, space_order=(4, 3, 1))
u_new.data[:] = 1
print(u_new.data_with_halo)
```
Let's have a look at the generated code when using `u_new`.
```
equation = Eq(u_new.forward, u_new + 2)
op = Operator(equation, dle='noop')
print(op)
```
And finally, let's run it, to convince ourselves that only the domain region values will be incremented at each timestep.
```
#NBVAL_IGNORE_OUTPUT
op.apply(time_M=2)
print(u_new.data_with_halo)
```
The halo region, in turn, is surrounded by the _padding region_, which can be used for data alignment. By default, there is no padding. This can be changed by passing a suitable value to `padding`, as shown below:
```
u_pad = TimeFunction(name='u_pad', grid=grid, space_order=2, padding=(0,2,2))
u_pad.data_with_halo[:] = 1
u_pad.data[:] = 2
equation = Eq(u_pad.forward, u_pad + 2)
op = Operator(equation, dle='noop')
print(op)
```
Although in practice not very useful, with the (private) `_data_allocated` accessor one can see the entire _domain + halo + padding region_.
```
print(u_pad._data_allocated)
```
Above, the __domain__ is filled with __2__, the __halo__ is filled with __1__, and the __padding__ is filled with __0__.
| github_jupyter |
```
# Copyright 2020 IITK EE604A Image Processing. All Rights Reserved.
#
# Licensed under the MIT License. Use and/or modification of this code outside of EE604 must reference:
#
# © IITK EE604A Image Processing
# https://github.com/ee604/ee604_assignments
#
# Author: Shashi Kant Gupta and Prof K. S. Venkatesh, Department of Electrical Engineering, IIT Kanpur
```
## NumPy and Matplotlib Tutorial
SciPy contains a collection of python packages for mathematics, science and egineering. We will be covering some of the basics of some of the important packages inside SciPy: NumPy and Matplotlib
### NumPy
NumPy library basically contains multidimensional arrays and matrix data structures and various methods to perform mathematical operations on them.
#### Basics
```
# This is how you import libraries in Python
# We imported numpy and named it as np for convenience. Its not necessary to use np
import numpy as np
# creating numpy arrays
x = np.array([3, 1, 5])
print("Array x", x)
print("Shape", x.shape) # prints the shape of array x
print("Index", x[1]) # call the value at index 1
print("Slice", x[:2]) # Slicing is similar to python lists
# 2 dimensional array
y = np.array([[1, 2],[3, 4]])
print("---")
print("Shape", y.shape)
print("Array")
print(y)
x = np.random.random((2,2)) #random 2x2 array
print(x.shape)
print(x)
print(x[1,1])
x = np.arange(16) #linear array with values ranging from 0 to 15
print("Shape", x.shape)
print(x)
print("---")
x = x.reshape((4,4)) #reshaping
print("Shape", x.shape)
print(x)
# slicing and indexing
y = x[:2, 1:]
print(y)
print("---\nShape:")
print(y.shape)
print(y.shape[0], y.shape[1])
# boolean indexing. very very usefull
x = np.arange(8)
print(x)
print(x>5)
print(x[x>5])
```
#### Array operations
```
x = np.array([[1, 2],[3, 4]])
y = np.ones((2, 2)) #arrays of ones of size 2 x 2
z = np.zeros((2, 2)) #arrays of zeros of size 2 x 2
print("x\n", x)
print("---\ny\n", y)
print("---\nz\n", z)
# Addition
print("x + y\n", x + y)
print("---")
print("x + z\n", x + z)
# Multiplication
print("x * y\n", x * y)
print("---")
print("x * z\n", x * z)
# Matrix operations
print("Transpose\n", x.T)
print("---")
print("Dot product\n", np.dot(x, y))
print("---")
print("Inverse\n", np.linalg.inv(x))
```
#### Broadcasting
```
# Broadcasting
x = np.asarray([1, 4, 9, 16])
## Adding 1 to each element of x
# Usual way
y = np.ones(4)
print(x+y)
# broadcasting
print(x+1.0)
x = np.asarray([[1, 2], [3, 4]])
print(x)
y = np.asarray([[2, 2], [2, 2]])
print(x*y) #multiply 2 to all elements of x
z = np.asarray([[2], [2]])
print(x*y) #this is same
z = 2
print(x*y) #even this is same
x = np.asarray([[1, 2], [3, 4]])
y = np.asarray([[2], [2]])
print(x)
print(y)
print(x*y) #mulptiplication
print(np.dot(x, y)) #dot product
print(y.shape)
print(y.T.shape) # transpose
```
**Important**
Must go through this: https://numpy.org/devdocs/user/absolute_beginners.html
---
### Matplotlib
Matplotlib is commonly used library for visualization in Python.
```
import matplotlib.pyplot as plt # creating a shorthand name for the imported library
# Simple 2D plot
x = np.arange(0, 6 * np.pi, 0.2) # create a linear sequence: 0, 0.2, 0.4, ...., 18.8
ys = np.sin(x) # sin of x
yc = np.cos(x) # cos of x
# Plotting
# plt.plot(xvalues, yvalues, label="legend_name")
plt.plot(x, ys, c="black", label="sin(x)") # plot ys - sin(x) vs x
plt.plot(x, yc, c="red", label="cos(x)") # plot yc - cos(x) vs x
# Naming x and y axis
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.title('sin(x) and cos(x) curve') # Plot title
plt.legend() # Show legends
plt.grid() # Show grids
plt.show() # Display the generated plot
```
**Go through this:** https://matplotlib.org/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-py
**More examples:** https://matplotlib.org/tutorials/introductory/sample_plots.html#sphx-glr-tutorials-introductory-sample-plots-py
| github_jupyter |
# Collision Avoidance - Train Model (衝突回避 - alexnetモデルの学習)
このノートブックは[11_train_model_JP.ipynb](11_train_model_JP.ipynb)と同じですが、学習中に精度と損失をグラフに表示するサンプルになります。
このノートブックでは、衝突回避のために``free「直進する」``と``blocked「旋回する」``の2つのクラスを特定する画像分類モデルを学習します。
モデルの学習には人気のあるディープラーニングライブラリの *PyTorch* を使います。
```
########################################
# 利用するライブラリを読み込みます。
########################################
import torch
import torch.optim as optim
import torch.nn.functional as F
import torchvision
import torchvision.datasets as datasets
import torchvision.models as models
import torchvision.transforms as transforms
```
### データセットインスタンスを生成
[torchvision.datasets](https://pytorch.org/docs/stable/torchvision/datasets.html)パッケージに含まれる``ImageFolder`` classを使用します。学習用のデータを準備するために、``torchvision.transforms``パッケージを使って画像変換を定義します。
pytorch ImageNetの学習に使われた140万件のデータセットから得られる各チャンネルの平均と標準偏差は以下の値になります。
RGB各要素の平均:[0.485, 0.456, 0.406]
RGB各要素の標準偏差:[0.229, 0.224, 0.225]
正規化に関する部分はライブデモの「カメラ画像の前処理作成」の部分でもう少し詳しく説明してあります。
* ImageFolderリファレンス:
* https://pytorch.org/docs/stable/torchvision/datasets.html#imagefolder
* ImageFolder実装コード:
* https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py
* Normalizeリファレンス:
* https://pytorch.org/docs/stable/torchvision/transforms.html
* Normalize実装コード:
* https://github.com/pytorch/vision/blob/master/torchvision/transforms/transforms.py
* 正規化パラメータの値の理由:
* https://stackoverflow.com/questions/58151507/why-pytorch-officially-use-mean-0-485-0-456-0-406-and-std-0-229-0-224-0-2
* 正規化に意味があるのかどうか:
* https://teratail.com/questions/234027
```
########################################
# jpeg画像データを学習可能なデータフォーマットに変換して提供するインスタンスを作成します。
# このデータセットは、アクセス毎にtransformsを実行するため、ColorJitterにより毎回色合いがランダムに変化します。
# dataset変数には以下のような値が入ります。
# dataset[データ番号][0]:(3x224x224)のCHWデータ(ColorJitterによりアクセス毎に色合いがランダムに変化します)
# dataset[データ番号][1]:ラベル番号(blockedの場合は0、freeの場合は1)
########################################
dataset = datasets.ImageFolder(
'dataset', # データセットのディレクトリパスを指定します。
transforms.Compose([
transforms.ColorJitter(0.1, 0.1, 0.1, 0.1), # カラージッターは画像の明るさ、コントラスト、彩度をランダムに変更します。
transforms.Resize((224, 224)), # 画像サイズを224x224にリサイズします。
transforms.ToTensor(), # cudnnはHWC(Height x Width x Channel)をサポートしません。そのため画像(HWC layout)からTensor(CHW layout)に変換します。また、RGB各値を[0, 255]から[0.0, 1.0]の範囲にスケーリングします。
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) # この値はpytorch ImageNetの学習に使われた正規化(ImageNetデータセットのRGB毎に平均を0、標準偏差が1になるようにスケーリングすること)のパラメータです。学習済みモデルをベースとした転移学習を行うため、カメラ画像はこの値でRGBを正規化することが望ましいでしょう。
])
)
```
### トレーニングデータとテストデータに分ける
次に、データセットを*トレーニング用*と*テスト用*のデータセットに分割します。この例では、*トレーニング用*に50%, *テスト用*に50%で分けます。
*テスト用*のデータセットは、学習中にモデルの精度を検証するために使用されます。
```
########################################
# 学習に使うデータと学習させずに精度検証のために使うデータに分けます。
# blocked、freeの順で読込まれていたデータをランダムに抽出して、学習用と検証用にデータを分けます。
########################################
test_percent = 0.5 # テストデータ件数を50%にする
num_test = int(test_percent * len(dataset))
train_dataset, test_dataset = torch.utils.data.random_split(dataset, [len(dataset) - num_test, num_test])
```
### バッチ処理で学習データとテストデータを読み込むためのデータローダーを作成
[torch.utils.data.DataLoader](https://github.com/pytorch/pytorch/blob/master/torch/utils/data/dataloader.py)クラスは、モデル学習中に次のデータ処理が完了出来るようにサブプロセスで並列処理にして実装します。
データのシャッフル、バッチでのデータロードのために使用します。この例では、1回のバッチ処理でbatch_size枚の画像を使用します。これをバッチサイズと呼び、GPUのメモリ使用量と、モデルの精度に影響を与えます。
* DataLoaderリファレンス:
* https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader
* DataLoader実装コード:
* https://github.com/pytorch/pytorch/blob/master/torch/utils/data/dataloader.py
```
########################################
# データセットを分割読込みするためのデータローダーを作成します。
########################################
train_loader = torch.utils.data.DataLoader(
train_dataset,
batch_size=16,
shuffle=True,
num_workers=4
)
test_loader = torch.utils.data.DataLoader(
test_dataset,
batch_size=16,
shuffle=True,
num_workers=4
)
```
### JetBot用にモデルを変更する
torchvisionで使用可能なImageNetデータセットで学習済みのAlexNetモデルを使用します。
*転移学習*と呼ばれる手法で、すでに画像分類できる特徴を持つニューラルネットワーク層を、別の目的のために作られたモデルに適用することで、短時間で良好な結果を得られるモデルを作成することができます。
AlexNetの詳細:https://github.com/pytorch/vision/blob/master/torchvision/models/alexnet.py
転移学習の詳細:https://www.youtube.com/watch?v=yofjFQddwHE
```
########################################
# PyTorchで提供されているImageNetデータセットで学習済みのAlexNetモデルを読込みます。
########################################
model = models.alexnet(pretrained=True)
```
AlexNetの学習済みモデルは1000クラスのラベルを学習しています。しかしJetBotの衝突回避モデルの出力は「free」と「blocked」の2種類しか用意していません。
`AlexNet`のモデルは出力層の手前にある層が4096のノード数を持っているので、モデルの出力層を(4096,2)に置き換えて使います。
```
########################################
# モデルの出力層をJetBotの衝突回避モデル用に置き換えます。
########################################
model.classifier[6] = torch.nn.Linear(model.classifier[6].in_features, 2)
```
デフォルトではモデルのweightの計算はCPUで処理されるため、GPUを利用するようにモデルを設定します。
```
########################################
# GPU処理が可能な部分をGPUで処理するように設定します。
########################################
device = torch.device('cuda')
model = model.to(device)
```
### 可視化ユーティリティ
学習中の損失(loss)と精度(accuracy)をグラフに表示するために、bokehライブラリを利用します。
bokehがインストールされていない場合は、ターミナルで以下のコマンドを実行してインストールしてください。
```bash
sudo pip3 install bokeh
sudo jupyter labextension install @jupyter-widgets/jupyterlab-manager
sudo jupyter labextension install @bokeh/jupyter_bokeh
```
* bokeh:
* https://docs.bokeh.org/en/latest/docs/installation.html
```
from bokeh.io import push_notebook, show, output_notebook
from bokeh.layouts import row
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
from bokeh.models.tickers import SingleIntervalTicker
output_notebook()
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728']
p1 = figure(title="Loss", x_axis_label="Epoch", plot_height=300, plot_width=360)
p2 = figure(title="Accuracy", x_axis_label="Epoch", plot_height=300, plot_width=360)
source1 = ColumnDataSource(data={'epochs': [], 'trainlosses': [], 'testlosses': [] })
source2 = ColumnDataSource(data={'epochs': [], 'train_accuracies': [], 'test_accuracies': []})
#r = p1.multi_line(ys=['trainlosses', 'testlosses'], xs='epochs', color=colors, alpha=0.8, legend_label=['Training','Test'], source=source)
r1 = p1.line(x='epochs', y='trainlosses', line_width=2, color=colors[0], alpha=0.8, legend_label="Train", source=source1)
r2 = p1.line(x='epochs', y='testlosses', line_width=2, color=colors[1], alpha=0.8, legend_label="Test", source=source1)
r3 = p2.line(x='epochs', y='train_accuracies', line_width=2, color=colors[0], alpha=0.8, legend_label="Train", source=source2)
r4 = p2.line(x='epochs', y='test_accuracies', line_width=2, color=colors[1], alpha=0.8, legend_label="Test", source=source2)
p1.legend.location = "top_right"
p1.legend.click_policy="hide"
p2.legend.location = "bottom_right"
p2.legend.click_policy="hide"
```
### モデルの学習
30エポック学習し、各エポックでテストデータにおけるこれまでの最高精度と現在の精度を比較することにより、最高精度を更新した場合に保存します。
> 1エポックは、私たちが用意したトレーニング用のデータ全部を1回学習することです。データローダーのbatch_sizeで指定した数の画像を一度に学習するミニバッチ処理を複数回実行することで1エポックが完了します。
* バックプロパゲーションと勾配更新の関係について:
* https://stackoverflow.com/questions/53975717/pytorch-connection-between-loss-backward-and-optimizer-step
* torch.tensorとnp.ndarrayの違いについて:
* https://stackoverflow.com/questions/63582590/why-do-we-call-detach-before-calling-numpy-on-a-pytorch-tensor/63869655#63869655
```
NUM_EPOCHS = 30 # 学習するエポック数。
BEST_MODEL_PATH = 'best_model.pth' # 学習結果を保存するファイル名。
best_accuracy = 0.0 # 検証用の初期精度は0%の精度を意味する0.0としておきます。
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9) # 確率的勾配降下法を実装します。学習率と運動量はJetBotの学習に適した値を指定します。
handle = show(row(p1, p2), notebook_handle=True) # Jupyterノートブックの出力セルのbokehプロットを作成します。
########################################
# 学習を開始します。
########################################
for epoch in range(NUM_EPOCHS):
train_loss = 0.0 # 損失を0.0として初期化します。
train_error_count = 0.0 # 不一致件数を0件として初期化します。
####################
# SGDに基づいた学習をバッチ毎に実行します。
####################
for images, labels in iter(train_loader): # batch_size分の学習データを読み込みます。
images = images.to(device) # 画像データをGPUメモリに転送します。
labels = labels.to(device) # ラベルデータをGPUメモリに転送します。
optimizer.zero_grad() # 最適化されたすべてのtorch.Tensorの勾配をゼロに設定します。
outputs = model(images) # batch_size分の予測を一度に実行します。
loss = F.cross_entropy(outputs, labels) # batch_size分のモデルの予測結果と正解ラベルを照合して損失を計算します。
train_loss += loss # 1epochの損失を求めるために、今回のバッチの損失を加算します。
train_error_count += float(torch.sum(torch.abs(labels - outputs.argmax(1)))) # 予測結果と正解ラベルが不一致となった件数をカウントします。
loss.backward() # 各パラメータ毎の損失の勾配を計算します。
optimizer.step() # 計算された損失勾配で各パラメータの勾配を更新します。
train_loss /= len(train_loader) # 1epochの損失からデータ1件あたりの学習損失を求めます。
####################
# 未学習のデータでモデルの精度を検証します。
####################
test_loss = 0.0 # 損失を0.0として初期化します。
test_error_count = 0.0 # 不一致件数を0件として初期化します。
for images, labels in iter(test_loader): # batch_size分の学習データを読み込みます。
images = images.to(device) # 画像データをGPUメモリに転送します。
labels = labels.to(device) # ラベルデータをGPUメモリに転送します。
outputs = model(images) # batch_size分の予測を一度に実行します。
loss = F.cross_entropy(outputs, labels) # バッチ1回分のモデルの予測結果と正解ラベルを照合して損失を計算します。
test_loss += loss # 1epochの損失を求めるために、今回のバッチの損失を加算します。
test_error_count += float(torch.sum(torch.abs(labels - outputs.argmax(1)))) # 予測結果と正解ラベルが不一致となった件数をカウントします。
test_loss /= len(test_loader) # 1epochの損失からデータ1件あたりの評価損失を求めます。
####################
# 学習結果をログに表示します。
####################
train_accuracy = 1.0 - float(train_error_count) / float(len(train_dataset)) # 不一致となった割合から精度を算出します。
test_accuracy = 1.0 - float(test_error_count) / float(len(test_dataset)) # 不一致となった割合から精度を算出します。
print('%d: %f, %f, %f, %f' % (epoch+1, train_loss, test_loss, train_accuracy, test_accuracy)) # 学習結果をログに表示します。
####################
# 学習状況をグラフに表示します
####################
new_data1 = {'epochs': [epoch+1],
'trainlosses': [float(train_loss)],
'testlosses': [float(test_loss)] }
source1.stream(new_data1)
new_data2 = {'epochs': [epoch+1],
'train_accuracies': [float(train_accuracy)],
'test_accuracies': [float(test_accuracy)] }
source2.stream(new_data2)
push_notebook(handle=handle) # Jupyterノートブックの出力セルのbokehプロットを更新します。
####################
# 今回のepoch学習のテスト結果がよければ保存します
####################
if test_accuracy > best_accuracy:
torch.save(model.state_dict(), BEST_MODEL_PATH)
best_accuracy = test_accuracy
```
学習が完了すると、``12_live_demo_JP.ipynb``で推論に使う``best_model.pth``が生成されます。
※ グラフを初期化したい場合は、視覚化ユーティリティの項目のグラフの初期化をおこなっているCellを再度実行します。
## 次
JetBot本体で学習した場合は、このノートブックを閉じてからJupyter左側にある「Running Terminals and Kernels」を選択して「13_train_model_plot_JP.ipynb」の横にある「SHUT DOWN」をクリックしてJupyter Kernelをシャットダウンしてから[12_live_demo_JP.ipynb](12_live_demo_JP.ipynb)に進んでください。
| github_jupyter |
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-59152712-8"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-59152712-8');
</script>
# Start-to-Finish Example: Unit Testing `GiRaFFE_NRPy`: Boundary Conditions
## Author: Patrick Nelson
## This module Validates the Boundary Conditions routines for `GiRaFFE_NRPy`.
**Notebook Status:** <font color='orange'><b>In Progress</b></font>
**Validation Notes:** This module will validate the routines in [Tutorial-GiRaFFE_NRPy-BCs](Tutorial-GiRaFFE_NRPy-BCs.ipynb).
### NRPy+ Source Code for this module:
* [GiRaFFE_NRPy/GiRaFFE_NRPy_BCs.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_BCs.py) [\[**tutorial**\]](Tutorial-GiRaFFE_NRPy-BCs.ipynb) Generates the driver to compute the magnetic field from the vector potential in arbitrary spactimes.
## Introduction:
This notebook validates the code that will interpolate the metric gridfunctions on cell faces. These values, along with the reconstruction of primitive variables on the faces, are necessary for the Riemann solvers to compute the fluxes through the cell faces.
It is, in general, good coding practice to unit test functions individually to verify that they produce the expected and intended output. We will generate test data with arbitrarily-chosen analytic functions and calculate gridfunctions at the cell centers on a small numeric grid. We will then compute the values on the cell faces in two ways: first, with our interpolator, then second, we will shift the grid and compute them analytically. Then, we will rerun the function at a finer resolution. Finally, we will compare the results of the two runs to show third-order convergence.
When this notebook is run, the significant digits of agreement between the approximate and exact values in the ghost zones will be evaluated. If the agreement falls below a thresold, the point, quantity, and level of agreement are reported [here](#compile_run).
<a id='toc'></a>
# Table of Contents
$$\label{toc}$$
This notebook is organized as follows
1. [Step 1](#setup): Set up core functions and parameters for unit testing the BCs algorithm
1. [Step 1.a](#expressions) Write expressions for the gridfunctions we will test
1. [Step 1.b](#ccodekernels) Generate C functions to calculate the gridfunctions
1. [Step 1.c](#free_parameters) Set free parameters in the code
1. [Step 2](#mainc): `BCs_unit_test.c`: The Main C Code
1. [Step 2.a](#compile_run): Compile and run the code
1. [Step 3](#convergence): Code validation: Verify that relative error in numerical solution converges to zero at the expected order
1. [Step 4](#latex_pdf_output): Output this notebook to $\LaTeX$-formatted PDF file
<a id='setup'></a>
# Step 1: Set up core functions and parameters for unit testing the BCs algorithm \[Back to [top](#toc)\]
$$\label{setup}$$
We'll start by appending the relevant paths to `sys.path` so that we can access sympy modules in other places. Then, we'll import NRPy+ core functionality and set up a directory in which to carry out our test.
```
import os, sys # Standard Python modules for multiplatform OS-level functions
# First, we'll add the parent directory to the list of directories Python will check for modules.
nrpy_dir_path = os.path.join("..")
if nrpy_dir_path not in sys.path:
sys.path.append(nrpy_dir_path)
nrpy_dir_path = os.path.join("..","..")
if nrpy_dir_path not in sys.path:
sys.path.append(nrpy_dir_path)
from outputC import outCfunction, lhrh # NRPy+: Core C code output module
import finite_difference as fin # NRPy+: Finite difference C code generation module
import NRPy_param_funcs as par # NRPy+: Parameter interface
import grid as gri # NRPy+: Functions having to do with numerical grids
import indexedexp as ixp # NRPy+: Symbolic indexed expression (e.g., tensors, vectors, etc.) support
import reference_metric as rfm # NRPy+: Reference metric support
import cmdline_helper as cmd # NRPy+: Multi-platform Python command-line interface
out_dir = "Validation/"
cmd.mkdir(out_dir)
thismodule = "Start_to_Finish_UnitTest-GiRaFFE_NRPy-BCs"
# Set the finite-differencing order to 2
par.set_parval_from_str("finite_difference::FD_CENTDERIVS_ORDER", 2)
```
<a id='expressions'></a>
## Step 1.a: Write expressions for the gridfunctions we will test \[Back to [top](#toc)\]
$$\label{expressions}$$
Now, we'll choose some functions with arbitrary forms to generate test data. We'll need to set seven gridfunctions, so expressions are being pulled from several previously written unit tests.
\begin{align}
A_x &= dy + ez + f \\
A_y &= mx + nz + p \\
A_z &= sx + ty + u. \\
\bar{v}^x &= ax + by + cz \\
\bar{v}^y &= bx + cy + az \\
\bar{v}^z &= cx + ay + bz \\
[\sqrt{\gamma} \Phi] &= 1 - (x+2y+z) \\
\end{align}
```
a,b,c,d,e,f,g,h,l,m,n,o,p,q,r,s,t,u = par.Cparameters("REAL",thismodule,["a","b","c","d","e","f","g","h","l","m","n","o","p","q","r","s","t","u"],1e300)
M_PI = par.Cparameters("#define",thismodule,["M_PI"], "")
AD = ixp.register_gridfunctions_for_single_rank1("EVOL","AD",DIM=3)
ValenciavU = ixp.register_gridfunctions_for_single_rank1("AUXEVOL","ValenciavU",DIM=3)
psi6Phi = gri.register_gridfunctions("EVOL","psi6Phi")
par.set_parval_from_str("reference_metric::CoordSystem","Cartesian")
rfm.reference_metric()
x = rfm.xxCart[0]
y = rfm.xxCart[1]
z = rfm.xxCart[2]
AD[0] = d*y + e*z + f
AD[1] = m*x + n*z + o
AD[2] = s*x + t*y + u
ValenciavU[0] = a#*x + b*y + c*z
ValenciavU[1] = b#*x + c*y + a*z
ValenciavU[2] = c#*x + a*y + b*z
psi6Phi = sp.sympify(1) - (x + sp.sympify(2)*y + z)
```
<a id='ccodekernels'></a>
## Step 1.b: Generate C functions to calculate the gridfunctions \[Back to [top](#toc)\]
$$\label{ccodekernels}$$
Here, we will use the NRPy+ function `outCfunction()` to generate C code that will calculate our metric gridfunctions over an entire grid; note that we call the function twice, once over just the interior points, and once over all points. This will allow us to compare against exact values in the ghostzones. We will also call the function to generate the boundary conditions function we are testing.
```
metric_gfs_to_print = [\
lhrh(lhs=gri.gfaccess("evol_gfs","AD0"),rhs=AD[0]),\
lhrh(lhs=gri.gfaccess("evol_gfs","AD1"),rhs=AD[1]),\
lhrh(lhs=gri.gfaccess("evol_gfs","AD2"),rhs=AD[2]),\
lhrh(lhs=gri.gfaccess("auxevol_gfs","ValenciavU0"),rhs=ValenciavU[0]),\
lhrh(lhs=gri.gfaccess("auxevol_gfs","ValenciavU1"),rhs=ValenciavU[1]),\
lhrh(lhs=gri.gfaccess("auxevol_gfs","ValenciavU2"),rhs=ValenciavU[2]),\
lhrh(lhs=gri.gfaccess("evol_gfs","psi6Phi"),rhs=psi6Phi),\
]
desc = "Calculate test data on the interior grid for boundary conditions"
name = "calculate_test_data"
outCfunction(
outfile = os.path.join(out_dir,name+".h"), desc=desc, name=name,
params ="const paramstruct *restrict params,REAL *restrict xx[3],REAL *restrict auxevol_gfs,REAL *restrict evol_gfs",
body = fin.FD_outputC("returnstring",metric_gfs_to_print,params="outCverbose=False").replace("IDX4","IDX4S"),
loopopts="InteriorPoints,Read_xxs")
desc = "Calculate test data at all points for comparison"
name = "calculate_test_data_exact"
outCfunction(
outfile = os.path.join(out_dir,name+".h"), desc=desc, name=name,
params ="const paramstruct *restrict params,REAL *restrict xx[3],REAL *restrict auxevol_gfs,REAL *restrict evol_gfs",
body = fin.FD_outputC("returnstring",metric_gfs_to_print,params="outCverbose=False").replace("IDX4","IDX4S"),
loopopts="AllPoints,Read_xxs")
import GiRaFFE_NRPy.GiRaFFE_NRPy_BCs as BC
BC.GiRaFFE_NRPy_BCs(os.path.join(out_dir,"boundary_conditions"))
```
<a id='free_parameters'></a>
## Step 1.c: Set free parameters in the code \[Back to [top](#toc)\]
$$\label{free_parameters}$$
We also need to create the files that interact with NRPy's C parameter interface.
```
# Step 3.d.i: Generate declare_Cparameters_struct.h, set_Cparameters_default.h, and set_Cparameters[-SIMD].h
# par.generate_Cparameters_Ccodes(os.path.join(out_dir))
# Step 3.d.ii: Set free_parameters.h
with open(os.path.join(out_dir,"free_parameters.h"),"w") as file:
file.write("""
// Override parameter defaults with values based on command line arguments and NGHOSTS.
params.Nxx0 = atoi(argv[1]);
params.Nxx1 = atoi(argv[2]);
params.Nxx2 = atoi(argv[3]);
params.Nxx_plus_2NGHOSTS0 = params.Nxx0 + 2*NGHOSTS;
params.Nxx_plus_2NGHOSTS1 = params.Nxx1 + 2*NGHOSTS;
params.Nxx_plus_2NGHOSTS2 = params.Nxx2 + 2*NGHOSTS;
// Step 0d: Set up space and time coordinates
// Step 0d.i: Declare \Delta x^i=dxx{0,1,2} and invdxx{0,1,2}, as well as xxmin[3] and xxmax[3]:
const REAL xxmin[3] = {-1.0,-1.0,-1.0};
const REAL xxmax[3] = { 1.0, 1.0, 1.0};
params.dxx0 = (xxmax[0] - xxmin[0]) / ((REAL)params.Nxx_plus_2NGHOSTS0-1.0);
params.dxx1 = (xxmax[1] - xxmin[1]) / ((REAL)params.Nxx_plus_2NGHOSTS1-1.0);
params.dxx2 = (xxmax[2] - xxmin[2]) / ((REAL)params.Nxx_plus_2NGHOSTS2-1.0);
printf("dxx0,dxx1,dxx2 = %.5e,%.5e,%.5e\\n",params.dxx0,params.dxx1,params.dxx2);
params.invdx0 = 1.0 / params.dxx0;
params.invdx1 = 1.0 / params.dxx1;
params.invdx2 = 1.0 / params.dxx2;
\n""")
# Generates declare_Cparameters_struct.h, set_Cparameters_default.h, and set_Cparameters[-SIMD].h
par.generate_Cparameters_Ccodes(os.path.join(out_dir))
```
<a id='mainc'></a>
# Step 2: `BCs_unit_test.c`: The Main C Code \[Back to [top](#toc)\]
$$\label{mainc}$$
```
%%writefile $out_dir/BCs_unit_test.c
// These are common packages that we are likely to need.
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#include "string.h" // Needed for strncmp, etc.
#include "stdint.h" // Needed for Windows GCC 6.x compatibility
#include <time.h> // Needed to set a random seed.
#define REAL double
#include "declare_Cparameters_struct.h"
const int NGHOSTS = 3;
REAL a,b,c,d,e,f,g,h,l,m,n,o,p,q,r,s,t,u;
// Standard NRPy+ memory access:
#define IDX4S(g,i,j,k) \
( (i) + Nxx_plus_2NGHOSTS0 * ( (j) + Nxx_plus_2NGHOSTS1 * ( (k) + Nxx_plus_2NGHOSTS2 * (g) ) ) )
// Standard formula to calculate significant digits of agreement:
#define SDA(a,b) 1.0-log10(2.0*fabs(a-b)/(fabs(a)+fabs(b)))
// Give gridfunctions their names:
#define VALENCIAVU0GF 0
#define VALENCIAVU1GF 1
#define VALENCIAVU2GF 2
#define NUM_AUXEVOL_GFS 3
#define AD0GF 0
#define AD1GF 1
#define AD2GF 2
#define STILDED0GF 3
#define STILDED1GF 4
#define STILDED2GF 5
#define PSI6PHIGF 6
#define NUM_EVOL_GFS 7
#include "calculate_test_data.h"
#include "calculate_test_data_exact.h"
#include "boundary_conditions/GiRaFFE_boundary_conditions.h"
int main(int argc, const char *argv[]) {
paramstruct params;
#include "set_Cparameters_default.h"
// Step 0c: Set free parameters, overwriting Cparameters defaults
// by hand or with command-line input, as desired.
#include "free_parameters.h"
#include "set_Cparameters-nopointer.h"
// We'll define our grid slightly different from how we normally would. We let our outermost
// ghostzones coincide with xxmin and xxmax instead of the interior of the grid. This means
// that the ghostzone points will have identical positions so we can do convergence tests of them.
// Step 0e: Set up cell-centered Cartesian coordinate grids
REAL *xx[3];
xx[0] = (REAL *)malloc(sizeof(REAL)*Nxx_plus_2NGHOSTS0);
xx[1] = (REAL *)malloc(sizeof(REAL)*Nxx_plus_2NGHOSTS1);
xx[2] = (REAL *)malloc(sizeof(REAL)*Nxx_plus_2NGHOSTS2);
for(int j=0;j<Nxx_plus_2NGHOSTS0;j++) xx[0][j] = xxmin[0] + ((REAL)(j))*dxx0;
for(int j=0;j<Nxx_plus_2NGHOSTS1;j++) xx[1][j] = xxmin[1] + ((REAL)(j))*dxx1;
for(int j=0;j<Nxx_plus_2NGHOSTS2;j++) xx[2][j] = xxmin[2] + ((REAL)(j))*dxx2;
//for(int i=0;i<Nxx_plus_2NGHOSTS0;i++) printf("xx[0][%d] = %.15e\n",i,xx[0][i]);
// This is the array to which we'll write the NRPy+ variables.
REAL *auxevol_gfs = (REAL *)malloc(sizeof(REAL) * NUM_AUXEVOL_GFS * Nxx_plus_2NGHOSTS2 * Nxx_plus_2NGHOSTS1 * Nxx_plus_2NGHOSTS0);
REAL *evol_gfs = (REAL *)malloc(sizeof(REAL) * NUM_EVOL_GFS * Nxx_plus_2NGHOSTS2 * Nxx_plus_2NGHOSTS1 * Nxx_plus_2NGHOSTS0);
// And another for exact data:
REAL *auxevol_exact_gfs = (REAL *)malloc(sizeof(REAL) * NUM_AUXEVOL_GFS * Nxx_plus_2NGHOSTS2 * Nxx_plus_2NGHOSTS1 * Nxx_plus_2NGHOSTS0);
REAL *evol_exact_gfs = (REAL *)malloc(sizeof(REAL) * NUM_EVOL_GFS * Nxx_plus_2NGHOSTS2 * Nxx_plus_2NGHOSTS1 * Nxx_plus_2NGHOSTS0);
// Generate some random coefficients. Leave the random seed on its default for consistency between trials.
a = (double)(rand()%20)/5.0;
f = (double)(rand()%20)/5.0;
m = (double)(rand()%20)/5.0;
b = (double)(rand()%10-5)/100.0;
c = (double)(rand()%10-5)/100.0;
d = (double)(rand()%10-5)/100.0;
g = (double)(rand()%10-5)/100.0;
h = (double)(rand()%10-5)/100.0;
l = (double)(rand()%10-5)/100.0;
n = (double)(rand()%10-5)/100.0;
o = (double)(rand()%10-5)/100.0;
p = (double)(rand()%10-5)/100.0;
// First, calculate the test data on our grid, along with the comparison:
calculate_test_data(¶ms,xx,auxevol_gfs,evol_gfs);
calculate_test_data_exact(¶ms,xx,auxevol_exact_gfs,evol_exact_gfs);
// Run the BCs driver on the test data to fill in the ghost zones:
apply_bcs_potential(¶ms,evol_gfs);
apply_bcs_velocity(¶ms,auxevol_gfs);
/*char filename[100];
sprintf(filename,"out%d-numer.txt",Nxx0);
FILE *out2D = fopen(filename, "w");
for(int i2=0;i2<Nxx_plus_2NGHOSTS2;i2++) for(int i1=0;i1<Nxx_plus_2NGHOSTS1;i1++) for(int i0=0;i0<Nxx_plus_2NGHOSTS0;i0++) {
// We print the difference between approximate and exact numbers.
fprintf(out2D,"%.16e\t %e %e %e\n",
//auxevol_gfs[IDX4S(VALENCIAVU2GF,i0,i1,i2)]-auxevol_exact_gfs[IDX4S(VALENCIAVU2GF,i0,i1,i2)],
evol_gfs[IDX4S(AD2GF,i0,i1,i2)]-evol_exact_gfs[IDX4S(AD2GF,i0,i1,i2)],
xx[0][i0],xx[1][i1],xx[2][i2]
);
}
fclose(out2D);*/
int all_agree = 1;
for(int i0=0;i0<Nxx_plus_2NGHOSTS0;i0++){
for(int i1=0;i1<Nxx_plus_2NGHOSTS1;i1++){
for(int i2=0;i2<Nxx_plus_2NGHOSTS2;i2++){
if(SDA(evol_gfs[IDX4S(AD0GF, i0,i1,i2)],evol_exact_gfs[IDX4S(AD0GF, i0,i1,i2)])<10.0){
printf("Quantity AD0 only agrees with the original GiRaFFE to %.2f digits at i0,i1,i2=%d,%d,%d!\n",
SDA(evol_gfs[IDX4S(AD0GF, i0,i1,i2)],evol_exact_gfs[IDX4S(AD0GF, i0,i1,i2)]),i0,i1,i2);
all_agree=0;
}
if(SDA(evol_gfs[IDX4S(AD1GF, i0,i1,i2)],evol_exact_gfs[IDX4S(AD1GF, i0,i1,i2)])<10.0){
printf("Quantity AD1 only agrees with the original GiRaFFE to %.2f digits at i0,i1,i2=%d,%d,%d!\n",
SDA(evol_gfs[IDX4S(AD1GF, i0,i1,i2)],evol_exact_gfs[IDX4S(AD1GF, i0,i1,i2)]),i0,i1,i2);
all_agree=0;
}
if(SDA(evol_gfs[IDX4S(AD2GF, i0,i1,i2)],evol_exact_gfs[IDX4S(AD2GF, i0,i1,i2)])<10.0){
printf("Quantity AD2 only agrees with the original GiRaFFE to %.2f digits at i0,i1,i2=%d,%d,%d!\n",
SDA(evol_gfs[IDX4S(AD2GF, i0,i1,i2)],evol_exact_gfs[IDX4S(AD2GF, i0,i1,i2)]),i0,i1,i2);
all_agree=0;
}
if(SDA(auxevol_gfs[IDX4S(VALENCIAVU0GF, i0,i1,i2)],auxevol_exact_gfs[IDX4S(VALENCIAVU0GF, i0,i1,i2)])<10.0){
printf("Quantity ValenciavU0 only agrees with the original GiRaFFE to %.2f digits at i0,i1,i2=%d,%d,%d!\n",
SDA(auxevol_gfs[IDX4S(VALENCIAVU0GF, i0,i1,i2)],auxevol_exact_gfs[IDX4S(VALENCIAVU0GF, i0,i1,i2)]),i0,i1,i2);
all_agree=0;
}
if(SDA(auxevol_gfs[IDX4S(VALENCIAVU1GF, i0,i1,i2)],auxevol_exact_gfs[IDX4S(VALENCIAVU1GF, i0,i1,i2)])<10.0){
printf("Quantity ValenciavU1 only agrees with the original GiRaFFE to %.2f digits at i0,i1,i2=%d,%d,%d!\n",
SDA(auxevol_gfs[IDX4S(VALENCIAVU1GF, i0,i1,i2)],auxevol_exact_gfs[IDX4S(VALENCIAVU1GF, i0,i1,i2)]),i0,i1,i2);
all_agree=0;
}
if(SDA(auxevol_gfs[IDX4S(VALENCIAVU2GF, i0,i1,i2)],auxevol_exact_gfs[IDX4S(VALENCIAVU2GF, i0,i1,i2)])<10.0){
printf("Quantity ValenciavU2 only agrees with the original GiRaFFE to %.2f digits at i0,i1,i2=%d,%d,%d!\n",
SDA(auxevol_gfs[IDX4S(VALENCIAVU2GF, i0,i1,i2)],auxevol_exact_gfs[IDX4S(VALENCIAVU2GF, i0,i1,i2)]),i0,i1,i2);
all_agree=0;
}
if(SDA(evol_gfs[IDX4S(PSI6PHIGF, i0,i1,i2)],evol_exact_gfs[IDX4S(PSI6PHIGF, i0,i1,i2)])<10.0){
printf("psi6Phi = %.15e,%.15e\n",evol_gfs[IDX4S(PSI6PHIGF, i0,i1,i2)],evol_exact_gfs[IDX4S(PSI6PHIGF, i0,i1,i2)]);
//printf("Quantity psi6Phi only agrees with the original GiRaFFE to %.2f digits at i0,i1,i2=%d,%d,%d!\n",
// SDA(evol_gfs[IDX4S(PSI6PHIGF, i0,i1,i2)],evol_exact_gfs[IDX4S(PSI6PHIGF, i0,i1,i2)]),i0,i1,i2);
all_agree=0;
}
}
}
}
if(all_agree) printf("All quantities agree at all points!\n");
}
```
<a id='compile_run'></a>
## Step 2.a: Compile and run the code \[Back to [top](#toc)\]
$$\label{compile_run}$$
Now that we have our file, we can compile it and run the executable.
```
import time
print("Now compiling, should take ~2 seconds...\n")
start = time.time()
cmd.C_compile(os.path.join(out_dir,"BCs_unit_test.c"), os.path.join(out_dir,"BCs_unit_test"))
end = time.time()
print("Finished in "+str(end-start)+" seconds.\n\n")
print("Now running...\n")
start = time.time()
!./Validation/BCs_unit_test 2 2 2
# To do a convergence test, we'll also need a second grid with twice the resolution.
# !./Validation/BCs_unit_test 9 9 9
end = time.time()
print("Finished in "+str(end-start)+" seconds.\n\n")
```
<a id='latex_pdf_output'></a>
# Step 4: Output this notebook to $\LaTeX$-formatted PDF file \[Back to [top](#toc)\]
$$\label{latex_pdf_output}$$
The following code cell converts this Jupyter notebook into a proper, clickable $\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial directory, with filename
[Tutorial-Start_to_Finish-GiRaFFE_NRPy-Metric_Face_Values.pdf](Tutorial-Start_to_Finish-GiRaFFE_NRPy-Metric_Face_Values.pdf) (Note that clicking on this link may not work; you may need to open the PDF file through another means.)
```
import cmdline_helper as cmd # NRPy+: Multi-platform Python command-line interface
cmd.output_Jupyter_notebook_to_LaTeXed_PDF("Tutorial-Start_to_Finish_UnitTest-GiRaFFE_NRPy-BCs")
```
| github_jupyter |
## Text Similarity using Word Embeddings
In this notebook we're going to play around with pre build word embeddings and do some fun calcultations:
```
%matplotlib inline
import os
from keras.utils import get_file
import gensim
import subprocess
import numpy as np
import matplotlib.pyplot as plt
from IPython.core.pylabtools import figsize
figsize(10, 10)
from sklearn.manifold import TSNE
import json
from collections import Counter
from itertools import chain
```
We'll start by downloading a pretrained model from Google News. We're using `zcat` to unzip the file, so you need to make sure you have that installed or replace it by something else.
```
MODEL = 'GoogleNews-vectors-negative300.bin'
path = get_file(MODEL + '.gz', 'https://s3.amazonaws.com/dl4j-distribution/%s.gz' % MODEL)
if not os.path.isdir('generated'):
os.path.mkdir('generated')
unzipped = os.path.join('generated', MODEL)
if not os.path.isfile(unzipped):
with open(unzipped, 'wb') as fout:
zcat = subprocess.Popen(['zcat'],
stdin=open(path),
stdout=fout
)
zcat.wait()
model = gensim.models.KeyedVectors.load_word2vec_format(unzipped, binary=True)
```
Let's take this model for a spin by looking at what things are most similar to espresso. As expected, coffee like items show up:
```
model.most_similar(positive=['espresso'])
```
Now for the famous equation, what is like woman if king is like man? We create a quick method to these calculations here:
```
def A_is_to_B_as_C_is_to(a, b, c, topn=1):
a, b, c = map(lambda x:x if type(x) == list else [x], (a, b, c))
res = model.most_similar(positive=b + c, negative=a, topn=topn)
if len(res):
if topn == 1:
return res[0][0]
return [x[0] for x in res]
return None
A_is_to_B_as_C_is_to('man', 'woman', 'king')
```
We can use this equation to acurately predict the capitals of countries by looking at what has the same relationship as Berlin has to Germany for selected countries:
```
for country in 'Italy', 'France', 'India', 'China':
print('%s is the capital of %s' %
(A_is_to_B_as_C_is_to('Germany', 'Berlin', country), country))
```
Or we can do the same for important products for given companies. Here we seed the products equation with two products, the iPhone for Apple and Starbucks_coffee for Starbucks. Note that numbers are replaced by # in the embedding model:
```
for company in 'Google', 'IBM', 'Boeing', 'Microsoft', 'Samsung':
products = A_is_to_B_as_C_is_to(
['Starbucks', 'Apple'],
['Starbucks_coffee', 'iPhone'],
company, topn=3)
print('%s -> %s' %
(company, ', '.join(products)))
```
Let's do some clustering by picking three categories of items, drinks, countries and sports:
```
beverages = ['espresso', 'beer', 'vodka', 'wine', 'cola', 'tea']
countries = ['Italy', 'Germany', 'Russia', 'France', 'USA', 'India']
sports = ['soccer', 'handball', 'hockey', 'cycling', 'basketball', 'cricket']
items = beverages + countries + sports
len(items)
```
And looking up their vectors:
```
item_vectors = [(item, model[item])
for item in items
if item in model]
len(item_vectors)
```
Now use TSNE for clustering:
```
vectors = np.asarray([x[1] for x in item_vectors])
lengths = np.linalg.norm(vectors, axis=1)
norm_vectors = (vectors.T / lengths).T
tsne = TSNE(n_components=2, perplexity=10, verbose=2).fit_transform(norm_vectors)
```
And matplotlib to show the results:
```
x=tsne[:,0]
y=tsne[:,1]
fig, ax = plt.subplots()
ax.scatter(x, y)
for item, x1, y1 in zip(item_vectors, x, y):
ax.annotate(item[0], (x1, y1), size=14)
plt.show()
```
| github_jupyter |
# Understanding Bayesian Optimization
A simple worked through example of using BO to find the minimum of a one dimensional function
The majority of this is taken from *Gaussian processes for machine learning* by C. E. Rasmussen and C. K. I. Williams.
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (10,7)
```
### Target function and input domain
We start by defning the target funtion and generating the input domain, x_true
```
# Define the function we're trying to minimize
# def f(x):
# return x**2
def f(x):
return -np.exp(-(x - 2)**2) + np.exp(-(x - 6)**2/10) + 1/ (x**2 + 1)
# define a set of measurmenets
min_x,max_x, n_samples = -5,10,4
# True distirubtuion
X_true = np.linspace(min_x,max_x,1000)
f_x_true = [f(x) for x in X_true]
# PSeudo data, we made n_sample measurements
plt.plot(X_true,f_x_true)
plt.title('Target')
plt.ylabel('f(x)')
plt.xlabel('x')
```
## Visualizing samples from a Gaussian process
We need to first define a kernel,or covariance, between the a test set of inputs X_test. We are going to first draw a few lines
Then we're going to draw samples of gaussian process given the conditional obserations already made
```
def kernel(X,X_prime,l = 1.0):
"""
The covariance or kernel of the gaussian processes used to minimize
this example
Sometimes this covariance function is called the Radial Basis Function (RBF) or Gaussian;
here we prefer squared exponential.
"""
assert l != 0.0, "ERROR: the length scale must be non-zero"
K = []
for i,x in enumerate(X):
row = []
for j,x_p in enumerate(X_prime):
row.append( np.exp( -0.5*np .square( x - x_p )) )
K.append( row )
return np.array(K)
# Geneate the kernal matrix and cahce it so we don't run this costlye process every time
Sigma = kernel( X_true,X_true )
for n_examples in xrange(5):
plt.plot(X_true,np.random.multivariate_normal(np.zeros(len(X_true)), Sigma))
%time
```
## Evaluating the Postier: Conditional sampling from Gaussian process
We now want to evaluate a postierier distribution given our observation set X. From this we want to asses where is the next best choice for a new value
In an optimization problem we would also wish to evaluate the acquisition, or utility, function. We're going to examine a function that's peak is where we have the biggest uncertainty about the model - the so called expected improvement acquisition funtion

```
def postierier(x,X,f_X,l = 1.0):
"""
The postier function given input:
x: distibution in x to be tested over
X: measured X that will be integrated out
f_X: measured Y associated with each point x
"""
k_xX = kernel(x,X,l)
k_XX = kernel(X,X,l)
k_XX_inv = np.linalg.inv(k_XX)
k_xx = kernel(x,x,l)
k_Xx = kernel(X,x,l)
mean = np.matmul(k_XX_inv,f_X )
mean = np.matmul( k_xX, mean)
sigma = np.matmul(k_XX_inv, k_Xx)
sigma = np.matmul(k_xX, sigma)
sigma = k_xx - sigma
return mean, sigma
from scipy.stats import norm
def utility(x,f_x, mean,sigma):
"""
expected improvement acquisition
x: Measured x values distribution
f_X: Measured values of function we're trying to optimize
m: Mean value of the gaussian processes at each point in x-space
sigma: width of the gaussians at each point in x-space
"""
f_min = np.min(f_x)
f_max = np.max(f_x)
z = (mean-f_max)
return (mean - f_min)*norm.cdf(z) + sigma*norm.pdf(z)
# Z = np.divide( (-m +f_min), sigma)
# return np.nan_to_num(np.multiply(-m+f_min,norm.cdf(f_min,m,sigma )) + np.multiply(sigma, norm.pdf(Z) ))
X = np.linspace(min_x,max_x,5)
f_X = [f(x) for x in X]
m, s = postierier(X_true, X,f_X,l=2 )
sig = np.diag(s)
# Draw the 3 sigma band of the postier distirbution
plt.fill_between(X_true, m - 3*sig, m+3*sig,alpha=0.5,color='green')
plt.fill_between(X_true, m - 2*sig, m+2*sig,alpha=0.5,color='yellow')
plt.plot(X_true,f_x_true,color='red',linewidth=3.0)
plt.title('Target')
plt.ylabel('f(x)')
plt.xlabel('x')
# sample and draw a few postieriers
# for n_examples in xrange(1,3):
# plt.plot(X_true,np.random.multivariate_normal(m,s))
# Draw the means
plt.plot(X_true,m,color = 'black')
plt.plot(X,f_X,'bo')
plt.show()
# Draw the utility function for the current postier
u = utility(X,f_X, m, sig)
x_max, u_max = X_true[np.argmax(u)],np.max(u)
plt.fill_between(X_true, 0,u,alpha=0.5,color='blue')
plt.plot( [x_max],[u_max], 'y*',
markersize=24)
```
## Performing an optimization
We now have the tools to implement an optimization so let's iterate through an optimization procedure
```
from copy import copy
class Iteration:
def __init__(self,
mean,
covariance,
X,
f_X,
u
):
self.mean = copy(mean)
self.covariance = copy(covariance)
self.sigma = copy(np.diag(covariance))
self.X = copy(X)
self.f_X = copy(f_X)
self.u = copy(u)
def optimize(f,x_initial, x_range, stop_criteria=20):
"""
Performs a bayesian optimziation procedure
"""
# Rename the initial guesses to
# captal X which always represents the measured
# X points
X = x_initial
f_X = [f(x) for x in X ]
iterations = []
# Keep evaluating until we've satisifed our finishing criteria
for i in xrange(stop_criteria):
print "Performing Iteration: ", i
# Evaluate the postier, and get the mean and
# covariance matrix
try:
mean, covar = postierier(x_range, X,f_X, l =4.3)
except:
print "ERROR: Signular covariance in measured X..."
return iterations
# Evalaute the width at each point
sig = np.diag(covar)
# Draw the utility function for the current postier
u = utility(X,f_X, mean, sig)
x_max, u_max = X_true[np.argmax(u)],np.max(u)
print " maximal utlity: ", u_max
print " next x: ", x_max
# Add this iterations values to the store of them
iterations.append( Iteration(mean,
covar,
X,
f_X,
u ))
# Update the list of measurements to include the next
# best guess
X.append(x_max)
f_X.append(f(x_max))
return iterations
X_initial = [1.0]
X_test_range = np.linspace(-5,10,1000)
iterations = optimize( f, X_initial,X_test_range,stop_criteria = 25)
print "Finished optimization"
```
#### Draw the optimization
```
X_true = X_test_range
f_x_true = [f(x) for x in X_true ]
from matplotlib.backends.backend_pdf import PdfPages
with PdfPages('optimization_output.pdf') as pdf:
for iteration in iterations:
m = iteration.mean
sig = iteration.sigma
f_X = iteration.f_X
X = iteration.X
# Setup a figure with an upper and lower pannel
fig = plt.figure(figsize=(8, 8))
gs = gridspec.GridSpec(2, 1, width_ratios=[1],height_ratios=[3,1])
ax0 = plt.subplot(gs[0])
# Draw the upwer pannel
ax0.fill_between(X_true, m - 2*sig, m+2*sig,alpha=0.5,color='green',label = r'$\pm 2\sigma$')
ax0.fill_between(X_true, m - sig, m+sig,alpha=0.5,color='yellow',label = r'$\pm 1\sigma$')
ax0.plot(X_true,f_x_true,color='red',linewidth=3.0, label='target')
ax0.set_ylabel('f(x)')
ax0.plot(X_true,m,color = 'black', label='Mean')
ax0.plot(X,f_X,'bo', label='Measured')
ax0.legend()
# Draw the utility function for the current postier
u = iteration.u
x_max, u_max = X_true[np.argmax(u)],np.max(u)
ax1 = plt.subplot(gs[1])
ax1.fill_between(X_true, 0,u,alpha=0.5,color='blue')
ax1.plot( [x_max],[u_max], 'y*',
markersize=24)
ax1.set_xlabel('x')
ax1.set_ylabel('U(x)')
plt.tight_layout()
plt.show()
pdf.savefig(fig)
plt.close()
print "True maximum: ", np.max(f_x_true)
print "Evaluated max: ", f_x_true[np.argmax(iterations[-1].u)]
print "True maximum: ", X_test_range[np.argmax(f_x_true)]
print "Evaluated max: ", X_test_range[np.argmax(iterations[-1].u)]
```
| github_jupyter |
```
import math
import torch
import matplotlib.pyplot as plt
%matplotlib inline
from torch.utils.data import DataLoader
from torchvision import datasets, transforms, utils
# We will set a seed to ensure repeatability of training
torch.manual_seed(42)
# Load the dataset
mnist_transforms = transforms.Compose([transforms.Resize((32, 32)),
transforms.ToTensor()])
train_data = datasets.MNIST(
root = 'datasets',
train = True,
transform = mnist_transforms,
download = True,
)
test_data = datasets.MNIST(
root = 'datasets',
train = False,
transform = mnist_transforms,
download = True,
)
# Let us take a look at the train and test data
# Each image is of shape 28 * 28 and we have 60000 train examples
assert train_data.data.shape == torch.Size((60000, 28, 28))
print(f"Train data size {train_data.data.shape}") # We have 60000 images of shape 28x28
assert train_data.targets.shape == torch.Size([60000])# We have a target for each image
print(f"Train data target {train_data.targets.shape}")
print(f"Test data size {test_data.data.shape}") # We have 10000 images for test
print(f"Test data target {test_data.targets.shape}")
def plot_data(X, y, prefix, num_to_plot=24):
# Let us sample a few random images to plot
assert X.shape[0] == y.shape[0]
sample_idx = torch.randint(len(X), size=(num_to_plot,))
# We will plot the images in a grid
figure = plt.figure(figsize=(10, 8))
num_cols = 3
num_rows = int(math.ceil(num_to_plot/ num_cols))
for i in range(num_to_plot):
img = X[sample_idx[i]]
label = y[sample_idx[i]]
figure.add_subplot(num_rows, num_cols, i+1)
plt.title(f"{prefix}_{label}")
plt.axis("off")
plt.tight_layout()
plt.imshow(img.squeeze(), cmap="gray")
plt.show()
plot_data(train_data.data, train_data.targets, "gt")
# Let us define the neural network architecture
class LeNet(torch.nn.Module):
def __init__(self, num_classes):
super(LeNet, self).__init__()
self.conv1 = torch.nn.Sequential(
torch.nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5, stride=1),
torch.nn.Tanh(),
torch.nn.AvgPool2d(kernel_size=2))
self.conv2 = torch.nn.Sequential(
torch.nn.Conv2d(in_channels=6, out_channels=16, kernel_size=5, stride=1),
torch.nn.Tanh(),
torch.nn.AvgPool2d(kernel_size=2))
self.conv3 = torch.nn.Sequential(
torch.nn.Conv2d(in_channels=16, out_channels=120, kernel_size=5, stride=1),
torch.nn.Tanh())
self.fc1 = torch.nn.Sequential(
torch.nn.Linear(in_features=120, out_features=84),
torch.nn.Tanh())
self.fc2 = torch.nn.Linear(in_features=84, out_features=num_classes)
def forward(self, X):
conv_out = self.conv3(self.conv2(self.conv1(X)))
batch_size = conv_out.shape[0]
conv_out = conv_out.reshape(batch_size, -1)
logits = self.fc2(self.fc1(conv_out))
return logits
def predict(self, X):
logits = self.forward(X)
probs = torch.softmax(logits, dim=1)
return torch.argmax(probs, 1)
# Let us create dataloaders for the datasets
batch_size=100
train_dataloader = torch.utils.data.DataLoader(train_data,
batch_size=batch_size,
shuffle=True,
num_workers=0)
test_dataloader = torch.utils.data.DataLoader(test_data,
batch_size=batch_size,
shuffle=True,
num_workers=0)
def compute_accuracy(gt, logits):
assert gt.shape[0] == logits.shape[0] # Same batch size
with torch.no_grad():
probs = torch.softmax(logits, 1)
predicted_labels = torch.argmax(probs, 1)
correct_pred = (predicted_labels == gt).to(torch.int).sum()
accuracy = correct_pred / len(gt)
return accuracy
def train(model, data_loader, criterion, optimizer, device, epoch):
# Set training mode
model.train()
for i, (X, y_true) in enumerate(data_loader):
optimizer.zero_grad()
X = X.to(device)
y_true = y_true.to(device)
y_pred_logits = model.forward(X)
loss = criterion(y_pred_logits, y_true)
if i % 100 == 0:
accuracy = compute_accuracy(y_true, y_pred_logits)
print(f"Epoch {epoch}, Step {i}: Training loss: {loss} Accuracy: {accuracy}")
loss.backward()
optimizer.step()
def test(model, data_loader, criterion, device):
model.eval()
batch_loss, batch_acc = [], []
for i, (X, y_true) in enumerate(data_loader):
X = X.to(device)
y_true = y_true.to(device)
y_pred_logits = model.forward(X)
batch_loss.append(criterion(y_pred_logits, y_true))
batch_acc.append(compute_accuracy(y_true, y_pred_logits))
avg_loss = sum(batch_loss) / len(batch_loss)
avg_acc = sum(batch_acc) / len(batch_acc)
return {"loss": avg_loss, "accuracy": avg_acc}
# Train test loop
num_classes = 10
# To determine the device. If torch.cuda is available, we use the GPU else CPU
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Model
model = LeNet(num_classes).to(device)
# Optimizer
optimizer = torch.optim.SGD(model.parameters(), lr=0.01,
momentum=0.9)
# Criterion
criterion = torch.nn.CrossEntropyLoss()
num_epochs = 10
for epoch in range(num_epochs):
train(model, train_dataloader, criterion, optimizer, device, epoch)
with torch.no_grad():
test_results = test(model, test_dataloader, criterion, device)
print(f"Epoch {epoch}, Test loss: {test_results['loss']} Accuracy: {test_results['accuracy']}")
# Saving the best model
# We save the entire state dictionary here. If you want to save only the model weights,
# then you can just save model.state_dict()
save_path = "/tmp/lenet_mnist.pkl"
torch.save({
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'test_results': test_results,
}, save_path)
# Let us visualize some results
model.eval()
X, y_true = (iter(test_dataloader)).next()
with torch.no_grad():
y_pred = model.predict(X)
plot_data(X, y_pred, "pred", num_to_plot=24)
def visualize_filters(weights, title):
n,c,w,h = weights.shape
weights = weights.view(n*c, -1, w, h)
nrow = 10
rows = min(weights.shape[0] // nrow + 1, 64)
grid = utils.make_grid(weights, nrow=nrow, normalize=True, padding=1)
plt.figure(figsize=(nrow, rows))
plt.title(title)
plt.axis('off')
plt.imshow(grid.numpy().transpose((1, 2, 0)))
def plot_conv_filters(model):
# Get all the conv filters
conv_filters = [module for module in model.modules() if isinstance(module, torch.nn.Conv2d)]
for i, conv in enumerate(conv_filters):
visualize_filters(conv.weight.detach(), f"conv_{i}")
plot_conv_filters(model)
```
| github_jupyter |
# Wikipedia's Weekly List of Top Articles
The code below produces the weekly visuaization of the top articles that is used for the report published on https://en.wikipedia.org/wiki/Wikipedia:Top_25_Report
Here is what it does:
1. Import this week's top 25 table
2. Import the previous week's top 25 table
3. Compare the current table to the previous one, and create two columns. The first, showing whether or not an entry is new, going up, going down, or at the same level compared to the previous week. The second column translates the newly-created column into symbols; ('▲', '▼', '▶', 'new'), colored green, red, or black, signifying up, down, or same level.
4. Plot the values using a horizontal bar char, coloring the entry labels with their respective colors.
5. Save the chart to a file ready for upload.
To create the chart, simply place the cursor inside the following code cell, and then hit the 'play' button above.
```
%config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
from matplotlib.ticker import EngFormatter
import pandas as pd
import requests
from bs4 import BeautifulSoup
page = 'https://en.wikipedia.org/wiki/Wikipedia:Top_25_Report'
resp_this_week = requests.get(page)
soup_this_week = BeautifulSoup(resp_this_week.text, 'lxml')
page_links = soup_this_week.find_all('a')
uri_last_week = [p for p in page_links if "Last week's report" in p.text][0]['href']
url_last_week = 'https://en.wikipedia.org' + uri_last_week
this_week = pd.read_html(page, header=0)[2]
last_week = pd.read_html(url_last_week, header=0)[2]
this_week['Views'] = this_week['Views'].astype(str).str.replace('\D+', '').astype(int)
last_week['Views'] = last_week['Views'].astype(str).str.replace('\D+', '').astype(int)
rank_changes = []
for rank, article in zip(this_week['Rank'], this_week['Article']):
if article in last_week['Article'].values:
rank_changes.append(last_week['Article'].values.tolist().index(article)+1-rank)
else:
rank_changes.append('')
top25 = this_week
top25['rank_changes'] = rank_changes
arrows = {
'positive': 9650,
'negative': 9660,
'same': 9654,
}
rank_changes_chr = []
for rank in top25['rank_changes']:
if str(rank) == '0':
rank_changes_chr.append(chr(arrows['same']))
elif not rank:
rank_changes_chr.append('new')
elif str(rank) < '0':
rank_changes_chr.append(chr(arrows['negative']))
elif '0' < str(rank): # < '25':
rank_changes_chr.append(chr(arrows['positive']))
rank_changes_color = []
for rank in top25['rank_changes']:
if str(rank) == '0':
rank_changes_color.append('black')
elif not rank:
rank_changes_color.append('black')
elif str(rank) < '0':
rank_changes_color.append('red')
elif '0' < str(rank):
rank_changes_color.append('green')
top25['rank_changes_chr'] = rank_changes_chr
top25['rank_changes_color'] = rank_changes_color
fig, ax = plt.subplots()
fig.set_size_inches(14, 14)
fig.set_facecolor('#eeeeee')
ax.set_facecolor('#eeeeee')
ax.set_frame_on(False)
ax.grid(alpha=0.3)
y_text = (
top25['Article'][::-1].astype(str) +
top25['Rank'][::-1].astype(str).str.rjust(3) +
('(' + top25['rank_changes'][::-1].astype(str) + top25['rank_changes_chr'][::-1].astype(str) + ')').str.rjust(7, ' ')
)
ax.barh(y=y_text,
width=top25['Views'][::-1], alpha=0.8)
ax.xaxis.set_major_formatter(EngFormatter())
ax.yaxis.set_tick_params(labelsize=15)
ax.xaxis.set_tick_params(labelsize=15)
for i in range(25):
ax.text(x=top25['Views'][i],
y=y_text.values[::-1][i],
s='{:,}'.format(top25['Views'][i]),
color=top25['rank_changes_color'][i],
horizontalalignment='left',
verticalalignment='center', fontsize=15)
colors = top25['rank_changes_color'][::-1]
for ytick, color in zip(ax.get_yticklabels(), colors):
ytick.set_color(color)
ax.set_xlabel('Views', fontsize=20)
ax.set_title(soup_this_week.select('h2 .mw-headline')[0].text +
'\nTotal Views: ' + format(top25['Views'].sum(), ','),
fontsize=22)
plt.tight_layout()
fig.savefig(soup_this_week.select('h2 .mw-headline')[0].text + '.png',
facecolor='#eeeeee', dpi=150, bbox_inches='tight')
plt.show()
```
## Optional: Tweet the chart!
This code creates a tweet that has a link to the report on Wikipedia, and creates hashtags of the top topics, making sure they fit in a tweet's maximum of 280 characters
```
import re
title = soup_this_week.select('h2 .mw-headline')[0].text
title = re.sub('\(|\)|\.', '', title).replace('Wiki', '@Wiki')
wiki_url = 'http://bit.ly/wikitop25'
hashtags = '#' + top25['Article'].str.replace(' |\(|\)|-|–|!|,|:|\.|\'', '')
headers_len = len(title + '\n' + wiki_url + '\n\n')
remaining_len = 280 - headers_len
last_space = ' '.join(hashtags)[:remaining_len].rfind(' ')
tweet_text = title + '\n' + wiki_url + '\n\n' + '\n'.join(hashtags)[:last_space]
print(tweet_text)
```
| github_jupyter |
<i>Copyright (c) Microsoft Corporation. All rights reserved.</i>
<i>Licensed under the MIT License.</i>
# Deployment of a model to Azure Kubernetes Service (AKS)
## Table of contents
1. [Introduction](#intro)
1. [Model deployment on AKS](#deploy)
1. [Workspace retrieval](#workspace)
1. [Docker image retrieval](#docker_image)
1. [AKS compute target creation](#compute)
1. [Monitoring activation](#monitor)
1. [Service deployment](#svc_deploy)
1. [Clean up](#clean)
1. [Next steps](#next)
## 1. Introduction <a id="intro"/>
In many real life scenarios, trained machine learning models need to be deployed to production. As we saw in the [prior](21_deployment_on_azure_container_instances.ipynb) deployment notebook, this can be done by deploying on Azure Container Instances. In this tutorial, we will get familiar with another way of implementing a model into a production environment, this time using [Azure Kubernetes Service](https://docs.microsoft.com/en-us/azure/aks/concepts-clusters-workloads) (AKS).
AKS manages hosted Kubernetes environments. It makes it easy to deploy and manage containerized applications without container orchestration expertise. It also supports deployments with CPU clusters and deployments with GPU clusters.
At the end of this tutorial, we will have learned how to:
- Deploy a model as a web service using AKS
- Monitor our new service.

### Pre-requisites <a id="pre-reqs"/>
This notebook relies on resources we created in [21_deployment_on_azure_container_instances.ipynb](21_deployment_on_azure_container_instances.ipynb):
- Our Azure Machine Learning workspace
- The Docker image that contains the model and scoring script needed for the web service to work.
If we are missing any of these, we should go back and run the steps from the sections "Pre-requisites" to "3.D Environment setup" to generate them.
### Library import <a id="libraries"/>
Now that our prior resources are available, let's first import a few libraries we will need for the deployment on AKS.
```
# For automatic reloading of modified libraries
%reload_ext autoreload
%autoreload 2
import sys
sys.path.extend(["..", "../.."]) # to access the utils_cv library
# Azure
from azureml.core import Workspace
from azureml.core.compute import AksCompute, ComputeTarget
from azureml.core.webservice import AksWebservice, Webservice
```
## 2. Model deployment on AKS <a id="deploy"/>
### 2.A Workspace retrieval <a id="workspace">
Let's now load the workspace we used in the [prior notebook](21_deployment_on_azure_container_instances.ipynb).
<i><b>Note:</b> The Docker image we will use below is attached to that workspace. It is then important to use the same workspace here. If, for any reason, we needed to use another workspace instead, we would need to reproduce, here, the steps followed to create a Docker image containing our image classifier model in the prior notebook.</i>
To create or access an Azure ML Workspace, you will need the following information. If you are coming from previous notebook you can retreive existing workspace, or create a new one if you are just starting with this notebook.
- subscription ID: the ID of the Azure subscription we are using
- resource group: the name of the resource group in which our workspace resides
- workspace region: the geographical area in which our workspace resides (e.g. "eastus2" -- other examples are ---available here -- note the lack of spaces)
- workspace name: the name of the workspace we want to create or retrieve.
```
subscription_id = "YOUR_SUBSCRIPTION_ID"
resource_group = "YOUR_RESOURCE_GROUP_NAME"
workspace_name = "YOUR_WORKSPACE_NAME"
workspace_region = "YOUR_WORKSPACE_REGION" #Possible values eastus, eastus2 and so on.
```
### 3.A Workspace retrieval <a id="workspace"></a>
In [prior notebook](20_azure_workspace_setup.ipynb) notebook, we created a workspace. This is a critical object from which we will build all the pieces we need to deploy our model as a web service. Let's start by retrieving it.
```
# A util method that creates a workspace or retrieves one if it exists, also takes care of Azure Authentication
from utils_cv.common.azureml import get_or_create_workspace
ws = get_or_create_workspace(
subscription_id,
resource_group,
workspace_name,
workspace_region)
# Print the workspace attributes
print('Workspace name: ' + ws.name,
'Workspace region: ' + ws.location,
'Subscription id: ' + ws.subscription_id,
'Resource group: ' + ws.resource_group, sep = '\n')
```
### 2.B Docker image retrieval <a id="docker_image">
We can reuse the Docker image we created in section 3. of the [previous tutorial](21_deployment_on_azure_container_instances.ipynb). Let's make sure that it is still available.
```
print("Docker images:")
for docker_im in ws.images:
print(f" --> Name: {ws.images[docker_im].name}\n \
--> ID: {ws.images[docker_im].id}\n \
--> Tags: {ws.images[docker_im].tags}\n \
--> Creation time: {ws.images[docker_im].created_time}\n"
)
```
As we did not delete it in the prior notebook, our Docker image is still present in our workspace. Let's retrieve it.
```
docker_image = ws.images["image-classif-resnet18-f48"]
```
We can also check that the model it contains is the one we registered and used during our deployment on ACI. In our case, the Docker image contains only 1 model, so taking the 0th element of the `docker_image.models` list returns our model.
<i><b>Note:</b> We will not use the `registered_model` object anywhere here. We are running the next 2 cells just for verification purposes.</i>
```
registered_model = docker_image.models[0]
print(f"Existing model:\n --> Name: {registered_model.name}\n \
--> Version: {registered_model.version}\n --> ID: {registered_model.id} \n \
--> Creation time: {registered_model.created_time}\n \
--> URL: {registered_model.url}"
)
```
### 2.C AKS compute target creation<a id="compute"/>
In the case of deployment on AKS, in addition to the Docker image, we need to define computational resources. This is typically a cluster of CPUs or a cluster of GPUs. If we already have a Kubernetes-managed cluster in our workspace, we can use it, otherwise, we can create a new one.
<i><b>Note:</b> The name we give to our compute target must be between 2 and 16 characters long.</i>
Let's first check what types of compute resources we have, if any
```
print("List of compute resources associated with our workspace:")
for cp in ws.compute_targets:
print(f" --> {cp}: {ws.compute_targets[cp]}")
```
In the case where we have no compute resource available, we can create a new one. For this, we can choose between a CPU-based or a GPU-based cluster of virtual machines. The latter is typically better suited for web services with high traffic (i.e. > 100 requests per second) and high GPU utilization. There is a [wide variety](https://docs.microsoft.com/en-us/azure/virtual-machines/windows/sizes-general) of machine types that can be used. In the present example, however, we will not need the fastest machines that exist nor the most memory optimized ones. We will use typical default machines:
- [Standard D3 V2](https://docs.microsoft.com/en-us/azure/virtual-machines/windows/sizes-general#dv2-series):
- 4 vCPUs
- 14 GB of memory
- [Standard NC6](https://docs.microsoft.com/en-us/azure/virtual-machines/windows/sizes-gpu):
- 1 GPU
- 12 GB of GPU memory
- These machines also have 6 vCPUs and 56 GB of memory.
<i><b>Notes:</b></i>
- These are Azure-specific denominations
- Information on optimized machines can be found [here](https://docs.microsoft.com/en-us/azure/virtual-machines/windows/sizes-general#other-sizes)
- When configuring the provisioning of an AKS cluster, we need to choose a type of machine, as examplified above. This choice must be such that the number of virtual machines (also called `agent nodes`), we require, multiplied by the number of vCPUs on each machine must be greater than or equal to 12 vCPUs. This is indeed the [minimum needed](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-deploy-and-where#create-a-new-aks-cluster) for such cluster. By default, a pool of 3 virtual machines gets provisioned on a new AKS cluster to allow for redundancy. So, if the type of virtual machine we choose has a number of vCPUs (`vm_size`) smaller than 4, we need to increase the number of machines (`agent_count`) such that `agent_count x vm_size` ≥ `12` virtual CPUs. `agent_count` and `vm_size` are both parameters we can pass to the `provisioning_configuration()` method below.
- [This document](https://docs.microsoft.com/en-us/azure/templates/Microsoft.ContainerService/2019-02-01/managedClusters?toc=%2Fen-us%2Fazure%2Fazure-resource-manager%2Ftoc.json&bc=%2Fen-us%2Fazure%2Fbread%2Ftoc.json#managedclusteragentpoolprofile-object) provides the full list of virtual machine types that can be deployed in an AKS cluster
- Additional considerations on deployments using GPUs are available [here](https://docs.microsoft.com/en-us/azure/virtual-machines/windows/sizes-gpu#deployment-considerations)
- If the Azure subscription we are using is shared with other users, we may encounter [quota restrictions](https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits) when trying to create a new cluster. To ensure that we have enough machines left, we can go to the Portal, click on our workspace name, and navigate to the `Usage + quotas` section. If we need more machines than are currently available, we can request a [quota increase](https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits#request-quota-increases).
Here, we will use a cluster of CPUs. The creation of such resource typically takes several minutes to complete.
```
# Declare the name of the cluster
virtual_machine_type = 'cpu'
aks_name = f'imgclass-aks-{virtual_machine_type}'
if aks_name not in ws.compute_targets:
# Define the type of virtual machines to use
if virtual_machine_type == 'gpu':
vm_size_name ="Standard_NC6"
else:
vm_size_name = "Standard_D3_v2"
# Configure the cluster using the default configuration (i.e. with 3 virtual machines)
prov_config = AksCompute.provisioning_configuration(vm_size = vm_size_name, agent_count=3)
# Create the cluster
aks_target = ComputeTarget.create(workspace = ws,
name = aks_name,
provisioning_configuration = prov_config)
aks_target.wait_for_completion(show_output = True)
print(f"We created the {aks_target.name} AKS compute target")
else:
# Retrieve the already existing cluster
aks_target = ws.compute_targets[aks_name]
print(f"We retrieved the {aks_target.name} AKS compute target")
```
If we need a more customized AKS cluster, we can provide more parameters to the `provisoning_configuration()` method, the full list of which is available [here](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.compute.akscompute?view=azure-ml-py#provisioning-configuration-agent-count-none--vm-size-none--ssl-cname-none--ssl-cert-pem-file-none--ssl-key-pem-file-none--location-none--vnet-resourcegroup-name-none--vnet-name-none--subnet-name-none--service-cidr-none--dns-service-ip-none--docker-bridge-cidr-none-).
When the cluster deploys successfully, we typically see the following:
```
Creating ...
SucceededProvisioning operation finished, operation "Succeeded"
```
In the case when our cluster already exists, we get the following message:
```
We retrieved the <aks_cluster_name> AKS compute target
```
This compute target can be seen on the Azure portal, under the `Compute` tab.
<img src="media/aks_compute_target_cpu.jpg" width="900">
```
# Check provisioning status
print(f"The AKS compute target provisioning {aks_target.provisioning_state.lower()} -- There were '{aks_target.provisioning_errors}' errors")
```
The set of resources we will use to deploy our web service on AKS is now provisioned and available.
### 2.D Monitoring activation <a id="monitor"/>
Once our web app is up and running, it is very important to monitor it, and measure the amount of traffic it gets, how long it takes to respond, the type of exceptions that get raised, etc. We will do so through [Application Insights](https://docs.microsoft.com/en-us/azure/azure-monitor/app/app-insights-overview), which is an application performance management service. To enable it on our soon-to-be-deployed web service, we first need to update our AKS configuration file:
```
# Set the AKS web service configuration and add monitoring to it
aks_config = AksWebservice.deploy_configuration(enable_app_insights=True)
```
### 2.E Service deployment <a id="svc_deploy"/>
We are now ready to deploy our web service. As in the [first](21_deployment_on_azure_container_instances.ipynb) notebook, we will deploy from the Docker image. It indeed contains our image classifier model and the conda environment needed for the scoring script to work properly. The parameters to pass to the `Webservice.deploy_from_image()` command are similar to those used for the deployment on ACI. The only major difference is the compute target (`aks_target`), i.e. the CPU cluster we just spun up.
<i><b>Note:</b> This deployment takes a few minutes to complete.</i>
```
if aks_target.provisioning_state== "Succeeded":
aks_service_name ='aks-cpu-image-classif-web-svc'
aks_service = Webservice.deploy_from_image(
workspace = ws,
name = aks_service_name,
image = docker_image,
deployment_config = aks_config,
deployment_target = aks_target
)
aks_service.wait_for_deployment(show_output = True)
print(f"The web service is {aks_service.state}")
else:
raise ValueError("The web service deployment failed.")
```
When successful, we should see the following:
```
Creating service
Running ...
SucceededAKS service creation operation finished, operation "Succeeded"
The web service is Healthy
```
In the case where the deployment is not successful, we can look at the service logs to debug. [These instructions](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-troubleshoot-deployment) can also be helpful.
```
# Access to the service logs
# print(aks_service.get_logs())
```
The new deployment can be seen on the portal, under the Deployments tab.
<img src="media/aks_webservice_cpu.jpg" width="900">
Our web service is up, and is running on AKS.
## 3. Clean up <a id="clean">
In a real-life scenario, it is likely that the service we created would need to be up and running at all times. However, in the present demonstrative case, and once we have verified that our service works (cf. "Next steps" section below), we can delete it as well as all the resources we used.
In this notebook, the only resource we added to our subscription, in comparison to what we had at the end of the notebook on ACI deployment, is the AKS cluster. There is no fee for cluster management. The only components we are paying for are:
- the cluster nodes
- the managed OS disks.
Here, we used Standard D3 V2 machines, which come with a temporary storage of 200 GB. Over the course of this tutorial (assuming ~ 1 hour), this changed almost nothing to our bill. Now, it is important to understand that each hour during which the cluster is up gets billed, whether the web service is called or not. The same is true for the ACI and workspace we have been using until now.
To get a better sense of pricing, we can refer to [this calculator](https://azure.microsoft.com/en-us/pricing/calculator/?service=kubernetes-service#kubernetes-service). We can also navigate to the [Cost Management + Billing pane](https://ms.portal.azure.com/#blade/Microsoft_Azure_Billing/ModernBillingMenuBlade/Overview) on the portal, click on our subscription ID, and click on the Cost Analysis tab to check our credit usage.
If we plan on no longer using this web service, we can turn monitoring off, and delete the compute target, the service itself as well as the associated Docker image.
```
# Application Insights deactivation
# aks_service.update(enable_app_insights=False)
# Service termination
# aks_service.delete()
# Compute target deletion
# aks_target.delete()
# This command executes fast but the actual deletion of the AKS cluster takes several minutes
# Docker image deletion
# docker_image.delete()
```
At this point, all the service resources we used in this notebook have been deleted. We are only now paying for our workspace.
If our goal is to continue using our workspace, we should keep it available. On the contrary, if we plan on no longer using it and its associated resources, we can delete it.
<i><b>Note:</b> Deleting the workspace will delete all the experiments, outputs, models, Docker images, deployments, etc. that we created in that workspace.</i>
```
# ws.delete(delete_dependent_resources=True)
# This deletes our workspace, the container registry, the account storage, Application Insights and the key vault
```
## 4. Next steps <a id="next"/>
In the [next notebook](23_aci_aks_web_service_testing.ipynb), we will test the web services we deployed on ACI and on AKS.
| github_jupyter |
```
%matplotlib inline
## imports
# site
from scipy.ndimage.morphology import binary_erosion
from matplotlib import colors
from matplotlib import patches
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
import rasterio
import flopy
# std
from pathlib import Path
import datetime
import yaml
def read_array(rasterfile, masked=True, band=1):
with rasterio.open(rasterfile) as src:
return src.read(band, masked=masked)
def read_profile(rasterfile):
with rasterio.open(rasterfile) as src:
return src.profile
def write_array(rasterfile, values, profile):
with rasterio.open(rasterfile, 'w', **profile) as dst:
return dst.write(values, 1)
def read_3d_array(rasterfiles, stack_axis=0, masked=True):
arrays = []
for rasterfile in rasterfiles:
arrays.append(read_array(rasterfile, masked=masked))
return np.ma.stack(arrays, axis=stack_axis)
def save_int(datfile, array):
save_array(datfile, array, fmt='%i', delimiter=' ')
def save_float(datfile, array):
save_array(datfile, array, fmt='%15.6E')
def save_array(datfile, array, fmt, delimiter=''):
np.savetxt(datfile, array, fmt=fmt, delimiter=delimiter)
t0 = datetime.datetime.now()
## input
# name
name = 'mf6brabant_idom'
# workspace
workspace = Path(r'..\output\mf6brabant_idomain')
# exe name
exe_name = Path(r'..\bin\mf6.0.4\bin\mf6.exe')
# spatial reference
xllcorner = 60_000.
yllcorner = 322_500.
# grid dimensions
nlay = 19
nrow = 450
ncol = 601
delr = 250.
delc = 250.
# data files
topfile = Path(r'..\data\topbot\RL{ilay:d}.tif')
botfile = Path(r'..\data\topbot\TH{ilay:d}.tif')
idomainfile = Path(r'..\data\boundary\ibound.tif')
kdfile = Path(r'..\data\kdc\TX{ilay:d}.tif')
cfile = Path(r'..\data\kdc\CL{ilay:d}.tif')
startfile = Path(r'..\data\startingheads\HH{ilay:d}.tif')
rechargefile = Path(r'..\data\recharge\RP1.tif')
drn2005file = Path(r'..\data\mf2005\drn_data.csv')
ghb2005file = Path(r'..\data\mf2005\ghb_data.csv')
riv2005file = Path(r'..\data\mf2005\riv_data.csv')
sqfile = Path(r'..\data\wells\sq_list.csv')
# create workspace directory
workspace.mkdir(exist_ok=True)
# create data directory
datafolder = workspace / 'data'
datafolder.mkdir(exist_ok=True)
# Create the Flopy simulation object
sim = flopy.mf6.MFSimulation(
sim_name=name,
exe_name=str(exe_name),
version='mf6',
sim_ws=str(workspace))
# Create the Flopy temporal discretization object
tdis = flopy.mf6.modflow.mftdis.ModflowTdis(sim,
pname='tdis',
time_units='DAYS',
nper=1,
perioddata=[(1.0, 1, 1.0)],
)
# Create the Flopy groundwater flow (gwf) model object
model_nam_file = '{}.nam'.format(name)
gwf = flopy.mf6.ModflowGwf(sim,
modelname=name,
model_nam_file=model_nam_file,
save_flows=True,
)
# read tops
topfiles = (topfile.parent / topfile.name.format(ilay=i + 1) for i in range(nlay))
tops = read_3d_array(topfiles)
# mask bad nodata values
tops = np.ma.masked_where(tops.mask | (tops < -9990.), tops)
# read bots
botfiles = (botfile.parent / botfile.name.format(ilay=i + 1) for i in range(nlay))
bots = read_3d_array(botfiles)
# mask bad nodata values
bots = np.ma.masked_where(bots.mask | (bots < -9990.), bots)
# convert to top, botm
top = tops[0, :, :].filled(0.)
topdatfile = datafolder / 'top.dat'
save_float(topdatfile, top)
top_ext = {'filename': str(topdatfile.relative_to(workspace))}
botm_ext = []
for ilay in range(nlay):
botm = bots[ilay, :, :].filled((2*ilay + 1) * -1e-3)
botmdatfile = datafolder / 'botm_l{ilay:02d}.dat'.format(ilay=ilay*2 + 1)
save_float(botmdatfile, botm)
botm_ext.append({'filename': str(botmdatfile.relative_to(workspace))})
if (ilay + 1) < nlay:
botm = tops[ilay + 1, :, :].filled((2*ilay + 2) * -1e-3)
botmdatfile = datafolder / 'botm_l{ilay:02d}.dat'.format(ilay=ilay*2 + 2)
save_float(botmdatfile, botm)
botm_ext.append({'filename': str(botmdatfile.relative_to(workspace))})
# read idomain
idomain = read_array(idomainfile).filled(0.).astype(np.int)
idomaindatfile = datafolder / 'idomain.dat'
save_int(idomaindatfile, idomain)
idomain_ext = [{'filename': str(idomaindatfile.relative_to(workspace))} for i in range(nlay*2 - 1)]
# initialize the DIS package
dis = flopy.mf6.modflow.mfgwfdis.ModflowGwfdis(gwf,
pname='dis', nlay=(nlay*2 - 1),
nrow=nrow, ncol=ncol,
delr=delr, delc=delc,
top=top_ext, botm=botm_ext,
idomain=idomain_ext,
length_units='METERS',
)
# read kD
kdfiles = (kdfile.parent / kdfile.name.format(ilay=i + 1) for i in range(nlay))
kd = read_3d_array(kdfiles)
# convert to kh
kh = (kd / (tops - bots))
# fill with low value
kh = kh.filled(1e-6)
# write to file
kh_ext = []
for ilay in range(nlay):
khdatfile = datafolder / 'kh_l{ilay:02d}.dat'.format(ilay=ilay*2 + 1)
save_float(khdatfile, kh[ilay, :, :])
kh_ext.append(
{'filename': str(khdatfile.relative_to(workspace))},
)
if (ilay + 1) < nlay:
# dummy values
kh_ext.append(1e-6)
# read c
cfiles = (cfile.parent / cfile.name.format(ilay=i + 1) for i in range(nlay - 1))
c = read_3d_array(cfiles)
# convert to kv
kv = (bots[:-1, :, :] - tops[1:, :, :]) / c
# fill with high value
kv = kv.filled(1e6)
# write to file
kv_ext = []
for ilay in range(nlay):
# dummy values
kv_ext.append(1e6)
if (ilay + 1) < nlay:
kvdatfile = datafolder / 'kv_l{ilay:02d}.dat'.format(ilay=ilay*2 + 2)
save_float(kvdatfile, kv[ilay, :, :])
kv_ext.append(
{'filename': str(kvdatfile.relative_to(workspace))},
)
# initialize the NPF package
npf = flopy.mf6.modflow.mfgwfnpf.ModflowGwfnpf(
model=gwf,
k=kh_ext,
k22=kh_ext,
k33=kv_ext,
)
# read start
startfiles = (startfile.parent / startfile.name.format(ilay=i + 1) for i in range(nlay))
start = read_3d_array(startfiles)
# mask values larger than 1000
start = np.ma.masked_where(start.mask | (start > 1e3), start)
# fill masked with zeros
start = start.filled(0.)
start_ext = []
for ilay in range(nlay):
startdatfile = datafolder / 'start_l{ilay:02d}.dat'.format(ilay=ilay*2 + 1)
save_float(startdatfile, start[ilay, :, :])
start_ext.append(
{'filename': str(startdatfile.relative_to(workspace))},
)
if (ilay + 1) < nlay:
start_ext.append(
{'filename': str(startdatfile.relative_to(workspace))},
)
# Create the initial conditions package
ic = flopy.mf6.modflow.mfgwfic.ModflowGwfic(gwf, pname='ic', strt=start_ext)
# get boundary data from idomain and starting heads
structure = np.ones((3, 3))
isboundary = (idomain == 1) & ~binary_erosion(idomain, structure)
chd_data = []
for ilay in range(dis.nlay.get_data()):
for row, col in np.ndindex(*isboundary.shape):
if isboundary[row, col]:
chd_data.append((ilay + 1, row + 1, col + 1, start[ilay//2, row, col]))
chd_data = np.array(
chd_data,
dtype=[('ilay', np.int), ('row', np.int), ('col', np.int), ('value', np.float)]
)
chddatfile = datafolder / 'chd.dat'
save_array(chddatfile, chd_data, fmt=' %i %i %i %16.8f')
chd_ext = {0: {
'filename': str(chddatfile.relative_to(workspace)),
}}
# initialize the CHD package
chd = flopy.mf6.modflow.mfgwfchd.ModflowGwfchd(gwf,
pname='chd',
maxbound=len(chd_data),
stress_period_data=chd_ext,
)
# recharge
recharge = read_array(rechargefile).filled(0.)
rechargedatfile = datafolder / 'recharge.dat'
save_float(rechargedatfile, recharge)
recharge_ext = [{'filename': str(rechargedatfile.relative_to(workspace))}]
# initialize the RCH package
rch = flopy.mf6.ModflowGwfrcha(gwf, pname='rch', recharge=recharge_ext)
# DRN stress period data from Modflow 2005
drn2005_data = pd.read_csv(drn2005file)
# select active cells
is_active = (idomain == 1)[drn2005_data.loc[:, 'i'], drn2005_data.loc[:, 'j']]
drn_data = drn2005_data.loc[is_active, ['k', 'i', 'j', 'elev0', 'cond0']]
drn_data.loc[:, 'k'] *= 2
drn_data.loc[:, ['k', 'i', 'j']] += 1
drndatfile = datafolder / 'drn.dat'
save_array(drndatfile, drn_data.values, fmt=' %i %i %i %16.8f %16.8f')
drn_ext = {0: {
'filename': str(drndatfile.relative_to(workspace)),
}}
# initialize the DRN package
drn = flopy.mf6.modflow.mfgwfdrn.ModflowGwfdrn(gwf,
pname='drn',
maxbound=drn_data.shape[0],
stress_period_data=drn_ext,
)
# GHB stress period data from Modflow 2005
ghb2005_data = pd.read_csv(ghb2005file)
# select active cells
is_active = (idomain == 1)[ghb2005_data.loc[:, 'i'], ghb2005_data.loc[:, 'j']]
ghb_data = ghb2005_data.loc[is_active, ['k', 'i', 'j', 'bhead0', 'cond0']]
ghb_data.loc[:, 'k'] *= 2
ghb_data.loc[:, ['k', 'i', 'j']] += 1
ghbdatfile = datafolder / 'ghb.dat'
save_array(ghbdatfile, ghb_data.values, fmt=' %i %i %i %16.8f %16.8f')
ghb_ext = {0: {
'filename': str(ghbdatfile.relative_to(workspace)),
}}
# initialize the GHB package
ghb = flopy.mf6.modflow.mfgwfghb.ModflowGwfghb(gwf,
pname='ghb',
maxbound=ghb_data.shape[0],
stress_period_data=ghb_ext,
)
# RIV stress period data from Modflow 2005
riv2005_data = pd.read_csv(riv2005file)
# select active cells
is_active = (idomain == 1)[riv2005_data.loc[:, 'i'], riv2005_data.loc[:, 'j']]
riv_data = riv2005_data.loc[is_active, ['k', 'i', 'j', 'stage0', 'cond0', 'rbot0']]
riv_data.loc[:, 'k'] *= 2
riv_data.loc[:, ['k', 'i', 'j']] += 1
rivdatfile = datafolder / 'riv.dat'
save_array(rivdatfile, riv_data.values, fmt=' %i %i %i %16.8f %16.8f %16.8f')
riv_ext = {0: {
'filename': str(rivdatfile.relative_to(workspace)),
}}
# initialize the RIV package
riv = flopy.mf6.modflow.mfgwfriv.ModflowGwfriv(gwf,
pname='riv',
maxbound=riv_data.shape[0],
stress_period_data=riv_ext,
)
# read sources data from csv file
sqs = pd.read_csv(sqfile)
# to row,col from x,y
fwd = rasterio.transform.from_origin(xllcorner, yllcorner + nrow*delr, delc, delr)
# transform xy to row,col
sqs.loc[:, 'row'], sqs.loc[:, 'col'] = (
rasterio.transform.rowcol(fwd, sqs['xcoordinate'], sqs['ycoordinate'])
)
# select active cells
is_active = (idomain == 1)[sqs.loc[:, 'row'], sqs.loc[:, 'col']]
# layer numbers & pumping rates
wel_data = sqs.loc[is_active, ['ilay', 'row', 'col', 'q_assigned']]
wel_data.loc[:, 'ilay'] = wel_data.loc[:, 'ilay'] * 2 - 1
wel_data.loc[:, ['row', 'col']] += 1
weldatfile = datafolder / 'wel.dat'
save_array(weldatfile, wel_data.values, fmt=' %i %i %i %16.8f')
wel_ext = {0: {
'filename': str(weldatfile.relative_to(workspace)),
}}
# initialize WEL package
wel = flopy.mf6.modflow.mfgwfwel.ModflowGwfwel(gwf,
pname='wel',
maxbound=len(wel_data),
stress_period_data=wel_ext,
)
# Create the Flopy iterative model solver (ims) Package object
ims = flopy.mf6.modflow.mfims.ModflowIms(sim, pname='ims', complexity='MODERATE')
# Create the output control package
headfile = '{}.hds'.format(name)
head_filerecord = [headfile]
budgetfile = '{}.cbb'.format(name)
budget_filerecord = [budgetfile]
saverecord = [('HEAD', 'ALL'),
('BUDGET', 'ALL')]
printrecord = [('HEAD', 'LAST')]
oc = flopy.mf6.modflow.mfgwfoc.ModflowGwfoc(gwf, pname='oc', saverecord=saverecord,
head_filerecord=head_filerecord,
budget_filerecord=budget_filerecord,
printrecord=printrecord)
# reload idomain (should not be necessary)
idomain = dis.idomain.get_data()
# identify dummy cells based on kD and c values
small_kd = kd <= 0.01
small_c = c <= 2
is_active = idomain==1
# set dummy cells to -1 in idomain "vertical pass through"
idomain[::2][small_kd & is_active[::2]] = -1
idomain[1::2][small_c & is_active[1::2]] = -1
# identify cells with CHD, DRN, GHB, RIV
is_chd = np.zeros((nlay*2 - 1, nrow, ncol), dtype=np.bool)
is_chd[chd_data['ilay'] - 1, chd_data['row'] - 1, chd_data['col'] - 1] = True
is_drn = np.zeros((nlay*2 - 1, nrow, ncol), dtype=np.bool)
is_drn[drn_data['k'] - 1, drn_data['i'] - 1, drn_data['j'] - 1] = True
is_ghb = np.zeros((nlay*2 - 1, nrow, ncol), dtype=np.bool)
is_ghb[ghb_data['k'] - 1, ghb_data['i'] - 1, ghb_data['j'] - 1] = True
is_riv = np.zeros((nlay*2 - 1, nrow, ncol), dtype=np.bool)
is_riv[riv_data['k'] - 1, riv_data['i'] - 1, riv_data['j'] - 1] = True
is_wel = np.zeros((nlay*2 - 1, nrow, ncol), dtype=np.bool)
is_wel[wel_data['ilay'] - 1, wel_data['row'] - 1, wel_data['col'] - 1] = True
# set cells with CHD, DRN, GHB, RIV back to 1 in idomain
# cells with a boundary condition cannot be set to "vertical pass through"
idomain[is_active & (is_chd | is_drn | is_ghb | is_riv | is_wel)] = 1
idomain_ext = []
for ilay in range(nlay*2 - 1):
idomaindatfile = datafolder / 'idomain_l{ilay:02d}.dat'.format(ilay=ilay + 1)
save_int(idomaindatfile, idomain[ilay, :, :])
idomain_ext.append({'filename': str(idomaindatfile.relative_to(workspace))})
dis.idomain.set_data(idomain_ext)
# write simulation to new location
sim.write_simulation()
# Run the simulation
success, buff = sim.run_simulation()
print('\nSuccess is: ', success)
# read heads
headfile = workspace / '{name:}.hds'.format(name=name)
hds = flopy.utils.binaryfile.HeadFile(headfile)
# export to raster
rasterfolder = workspace / 'heads'
rasterfolder.mkdir(exist_ok=True)
profile = read_profile(idomainfile)
heads = hds.get_data()
for i, raster in enumerate(heads[::2]): # export only horizontal flow layers i.e. 1, 3, .. 37
raster[idomain[i, :, :] == 0] = profile['nodata']
rasterfile = rasterfolder / 'phi{ilay:d}.tif'.format(ilay=i + 1)
write_array(rasterfile, raster, profile)
t1 = datetime.datetime.now()
print('notebook execution took {}'.format(t1 - t0))
# plot idomain C12
fig, ax = plt.subplots(figsize=(8, 6))
bxa = []
extent = [xllcorner, xllcorner + ncol*delc, yllcorner, yllcorner + nrow*delr]
is_active = idomain[11 * 2 + 1, :, :] == 1
is_inactive = idomain[11 * 2 + 1, :, :] == 0
is_passthrough = idomain[11 * 2 + 1, :, :] == -1
ax.imshow(is_active, cmap=colors.ListedColormap(['none', 'green']), extent=extent)
ax.imshow(is_inactive, cmap=colors.ListedColormap(['none', 'lightgray']), extent=extent)
ax.imshow(is_passthrough, cmap=colors.ListedColormap(['none', 'yellow']), extent=extent)
ax.set_aspect('equal')
ax.set_title('idomain c laag 12')
handles = [
patches.Patch(facecolor='green', edgecolor='black', label='active'),
patches.Patch(facecolor='lightgray', edgecolor='black', label='inactive'),
patches.Patch(facecolor='yellow', edgecolor='black', label='passthrough'),
]
lgd = ax.legend(handles=handles, loc='upper left', bbox_to_anchor=(1, 1), fontsize=12)
bxa.append(lgd)
plt.savefig(workspace / 'idomain_c12.png', bbox_inches='tight', dpi=200, bbox_extra_artists=bxa)
```
| github_jupyter |
SVM
```
import pandas as pd
from sklearn import svm, metrics
from sklearn.model_selection import train_test_split
swell_eda = pd.read_csv('D:\data\combined-swell-classification-eda-dataset.csv') # need to adjust a path of dataset
swell_eda.columns
original_column_list = ['MEAN', 'MAX', 'MIN', 'RANGE', 'KURT', 'SKEW', 'MEAN_1ST_GRAD',
'STD_1ST_GRAD', 'MEAN_2ND_GRAD', 'STD_2ND_GRAD', 'ALSC', 'INSC', 'APSC',
'RMSC', 'MIN_PEAKS', 'MAX_PEAKS', 'STD_PEAKS', 'MEAN_PEAKS',
'MIN_ONSET', 'MAX_ONSET', 'STD_ONSET', 'MEAN_ONSET', 'condition',
'subject_id', 'MEAN_LOG', 'INSC_LOG', 'APSC_LOG', 'RMSC_LOG',
'RANGE_LOG', 'ALSC_LOG', 'MIN_LOG', 'MEAN_1ST_GRAD_LOG',
'MEAN_2ND_GRAD_LOG', 'MIN_LOG_LOG', 'MEAN_1ST_GRAD_LOG_LOG',
'MEAN_2ND_GRAD_LOG_LOG', 'APSC_LOG_LOG', 'ALSC_LOG_LOG', 'APSC_BOXCOX',
'RMSC_BOXCOX', 'RANGE_BOXCOX', 'MEAN_YEO_JONSON', 'SKEW_YEO_JONSON',
'KURT_YEO_JONSON', 'APSC_YEO_JONSON', 'MIN_YEO_JONSON',
'MAX_YEO_JONSON', 'MEAN_1ST_GRAD_YEO_JONSON', 'RMSC_YEO_JONSON',
'STD_1ST_GRAD_YEO_JONSON', 'RANGE_SQRT', 'RMSC_SQUARED',
'MEAN_2ND_GRAD_CUBE', 'INSC_APSC', 'NasaTLX class', 'Condition Label',
'NasaTLX Label']
original_column_list_withoutString = ['MEAN', 'MAX', 'MIN', 'RANGE', 'KURT', 'SKEW', 'MEAN_1ST_GRAD',
'STD_1ST_GRAD', 'MEAN_2ND_GRAD', 'STD_2ND_GRAD', 'ALSC', 'INSC', 'APSC',
'RMSC', 'MIN_PEAKS', 'MAX_PEAKS', 'STD_PEAKS', 'MEAN_PEAKS',
'MIN_ONSET', 'MAX_ONSET', 'STD_ONSET', 'MEAN_ONSET',
'MEAN_LOG', 'INSC_LOG', 'APSC_LOG', 'RMSC_LOG',
'RANGE_LOG', 'ALSC_LOG', 'MIN_LOG', 'MEAN_1ST_GRAD_LOG',
'MEAN_2ND_GRAD_LOG', 'MIN_LOG_LOG', 'MEAN_1ST_GRAD_LOG_LOG',
'MEAN_2ND_GRAD_LOG_LOG', 'APSC_LOG_LOG', 'ALSC_LOG_LOG', 'APSC_BOXCOX',
'RMSC_BOXCOX', 'RANGE_BOXCOX', 'MEAN_YEO_JONSON', 'SKEW_YEO_JONSON',
'KURT_YEO_JONSON', 'APSC_YEO_JONSON', 'MIN_YEO_JONSON',
'MAX_YEO_JONSON', 'MEAN_1ST_GRAD_YEO_JONSON', 'RMSC_YEO_JONSON',
'STD_1ST_GRAD_YEO_JONSON', 'RANGE_SQRT', 'RMSC_SQUARED',
'MEAN_2ND_GRAD_CUBE', 'INSC_APSC']
selected_colum_list = ['MEAN_RR', 'MEDIAN_RR', 'SDRR', 'RMSSD', 'SDSD', 'SDRR_RMSSD', 'HR',
'pNN25', 'pNN50', 'SD1', 'SD2', 'KURT', 'SKEW', 'MEAN_REL_RR',
'MEDIAN_REL_RR']
stress_data = swell_eda[original_column_list_withoutString]
stress_label = swell_eda['NasaTLX Label']
stress_data
train_data, test_data, train_label, test_label = train_test_split(stress_data, stress_label)
from sklearn.decomposition import PCA
pca = PCA(n_components=25)
pca.fit(train_data)
X_t_train = pca.transform(train_data)
X_t_test = pca.transform(test_data)
model = svm.SVC()
model.fit(X_t_train, train_label)
predict = model.predict(X_t_test)
acc_score = metrics.accuracy_score(test_label, predict)
print(acc_score)
import pickle
import sklearn.externals
import joblib
saved_model = pickle.dumps(model)
joblib.dump(model, 'SVMmodel1.pkl')
model_from_pickle = joblib.load('SVMmodel1.pkl')
predict = model_from_pickle.predict(X_t_test)
acc_score = metrics.accuracy_score(test_label, predict)
print(acc_score)
```
| github_jupyter |
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets, linear_model, preprocessing, grid_search
from sklearn.preprocessing import Imputer, PolynomialFeatures, StandardScaler
from sklearn.tree import DecisionTreeClassifier
from sklearn.cross_validation import KFold
from sklearn.ensemble import RandomForestClassifier
from sklearn.cross_validation import StratifiedKFold, KFold
from sklearn.preprocessing import OneHotEncoder
from sklearn.externals import joblib
from keras.layers import Dense, Activation, Dropout
from keras.models import Sequential
from keras.regularizers import l2, activity_l2
import xgboost as xgb
from sklearn.metrics import roc_auc_score
from sklearn.cross_validation import train_test_split
from joblib import Parallel, delayed
from sklearn.pipeline import Pipeline
from hyperopt import hp, fmin, tpe, STATUS_OK, Trials
from hyperas import optim
from hyperas.distributions import choice, uniform, conditional
import category_encoders as ce
from functools import partial
np.random.seed(1338)
```
# Getting the data
```
def data_import(data,encode='label',split=True,stratify=True,split_size=0.1):
global Data
Data = data
#Reading the data, into a Data Frame.
initial_data = data
#Selcting the columns of string data type
names = initial_data.select_dtypes(include = ['object'])
#Converting string categorical variables to integer categorical variables.
label_encode(names.columns.tolist())
columns = names.drop(['y'],axis=1).columns.tolist()
#Data will be encoded to the form that the user enters
encoding = {'binary':binary_encode,'hashing':hashing_encode,'backward_difference'
:backward_difference_encode,'helmert':helmert_encode,'polynomial':
polynomial_encode,'sum':sum_encode,'label':label_encode}
#Once the above encoding techniques has been selected by the user, the appropriate encoding function is called
encoding[encode](columns)
#This function intializes the dataframes that will be used later in the program
#data_initialize()
#Splitting the data into to train and test sets, according to user preference
if(split == True):
data_split(stratify,split_size)
```
# Data for ensembling (Training)
```
#The dataframes will be used in the training phase of the ensemble models
def second_level_train_data(predict_list, cross_val_X, cross_val_Y):
#Converting the list of predictions into a dataframe, which will be used to train the stacking model.
global stack_X
stack_X = pd.DataFrame()
stack_X = stack_X.append(build_data_frame(predict_list))
#Building a list that contains all the raw features, used as cross validation data for the base models.
global raw_features_X
raw_features_X = pd.DataFrame()
raw_features_X = raw_features_X.append(cross_val_X,ignore_index=True)
#The data frame will contain the predictions and raw features of the base models, for training the blending
#model
global blend_X
blend_X = pd.DataFrame()
blend_X = pd.concat([raw_features_X, stack_X], axis = 1, ignore_index = True)
#Storing the cross validation dataset labels in the variable stack_Y,
#which will be used later to train the stacking and blending models.
global stack_Y
stack_Y = cross_val_Y
```
# Data for ensembling (Testing)
```
#The dataframes will be used in the testing phase of the ensemble models
def second_level_test_data(predict_list, test_X, test_Y):
#Converting the list of predictions into a dataframe, which will be used to test the stacking model.
global test_stack_X
test_stack_X = pd.DataFrame()
test_stack_X = test_stack_X.append(build_data_frame(predict_list))
#Building a list that contains all the raw features, used as test data for the base models.
global test_raw_features_X
test_raw_features_X = pd.DataFrame()
test_raw_features_X = test_raw_features_X.append(test_X,ignore_index=True)
#The data frame will contain the predictions and raw features of the base models, for testing the blending
#model
global test_blend_X
test_blend_X = pd.DataFrame()
test_blend_X = pd.concat([test_raw_features_X, test_stack_X], axis = 1, ignore_index = True)
#Storing the cross validation dataset labels in the variable stack_Y,
#which will be used later to test the stacking and blending models.
global test_stack_Y
test_stack_Y = test_Y
```
# Label Encoding
```
#Function that encodes the string values to numerical values.
def label_encode(column_names):
global Data
#Encoding the data, encoding the string values into numerical values.
encoder = ce.OrdinalEncoder(cols = column_names, verbose = 1)
Data = encoder.fit_transform(Data)
```
# Binary Encoding
```
def binary_encode(column_names):
global Data
#Encoding the data, encoding the string values into numerical values, using binary method.
encoder = ce.BinaryEncoder(cols = column_names, verbose = 1)
Data = encoder.fit_transform(Data)
```
# Hashing Encoding
```
def hashing_encode(column_names):
global Data
#Encoding the data, encoding the string values into numerical values, using hashing method.
encoder = ce.HashingEncoder(cols = column_names, verbose = 1, n_components = 128)
Data = encoder.fit_transform(Data)
```
# Backward Difference Encoding
```
def backward_difference_encode(column_names):
global Data
#Encoding the data, encoding the string values into numerical values, using backward difference method.
encoder = ce.BackwardDifferenceEncoder(cols = column_names, verbose = 1)
Data = encoder.fit_transform(Data)
```
# Helmert Encoding
```
def helmert_encode(column_names):
global Data
#Encoding the data, encoding the string values into numerical values, using helmert method.
encoder = ce.HelmertEncoder(cols = column_names, verbose = 1)
Data = encoder.fit_transform(Data)
```
# Sum Encoding
```
def sum_encode(column_names):
global Data
#Encoding the data, encoding the string values into numerical values, using sum method.
encoder = ce.SumEncoder(cols = column_names, verbose = 1)
Data = encoder.fit_transform(Data)
```
# Polynomial Encoding
```
def polynomial_encode(column_names):
global Data
#Encoding the data, encoding the string values into numerical values, using polynomial method.
encoder = ce.PolynomialEncoder(cols = column_names, verbose = 1)
Data = encoder.fit_transform(Data)
#Splitting the data into training and testing datasets
def data_split(stratify, split_size):
global Data
global test
#Stratified Split
if(stratify == True):
Data, test = train_test_split(Data, test_size = split_size, stratify = Data['y'],random_state = 0)
#Random Split
else:
Data, test = train_test_split(Data, test_size = split_size,random_state = 0)
#This function is used to convert the predictions of the base models (numpy array) into a DataFrame.
def build_data_frame(data):
data_frame = pd.DataFrame(data).T
return data_frame
```
# Gradient Boosting (XGBoost)
```
#Trains the Gradient Boosting model.
def train_gradient_boosting(train_X, train_Y, parameter_gradient_boosting):
#Hyperopt procedure, train the model with optimal paramter values
if(parameter_gradient_boosting['hyper_parameter_optimisation'] == True):
model = gradient_boosting_parameter_optimisation(train_X, train_Y, parameter_gradient_boosting, \
objective_gradient_boosting)
return model
#Train the model with the parameter values entered by the user, no need to find otimal values
else:
dtrain = xgb.DMatrix(train_X, label = train_Y)
del parameter_gradient_boosting['hyper_parameter_optimisation']
model = xgb.train(parameter_gradient_boosting, dtrain)
return model
#Defining the parameters for the XGBoost (Gradient Boosting) Algorithm.
def parameter_set_gradient_boosting(hyper_parameter_optimisation = False, eval_metric = None, booster = ['gbtree'],\
silent = [0], eta = [0.3], gamma = [0], max_depth = [6],\
min_child_weight = [1], max_delta_step = [0], subsample = [1],\
colsample_bytree = [1], colsample_bylevel = [1], lambda_xgb = [1], alpha = [0],\
tree_method = ['auto'], sketch_eps = [0.03], scale_pos_weight = [0],\
lambda_bias = [0], objective = ['reg:linear'], base_score = [0.5]):
parameter_gradient_boosting = {}
#This variable will be used to check if the user wants to perform hyper parameter optimisation.
parameter_gradient_boosting['hyper_parameter_optimisation'] = hyper_parameter_optimisation
#Setting objective and seed
parameter_gradient_boosting['objective'] = objective[0]
parameter_gradient_boosting['seed'] = 0
#If hyper parameter optimisation is false, we unlist the default values and/or the values that the user enters
#in the form of a list. Values have to be entered by the user in the form of a list, for hyper parameter
#optimisation = False, these values will be unlisted below
#Ex : booster = ['gbtree'](default value) becomes booster = 'gbtree'
#This is done beacuse for training the model, the model does not accept list type values
if(parameter_gradient_boosting['hyper_parameter_optimisation'] == False):
#Setting the parameters for the Booster, list values are unlisted (E.x - booster[0])
parameter_gradient_boosting['booster'] = booster[0]
parameter_gradient_boosting['eval_metric'] = eval_metric[0]
parameter_gradient_boosting['eta'] = eta[0]
parameter_gradient_boosting['gamma'] = gamma[0]
parameter_gradient_boosting['max_depth'] = max_depth[0]
parameter_gradient_boosting['min_child_weight'] = min_child_weight[0]
parameter_gradient_boosting['max_delta_step'] = max_delta_step[0]
parameter_gradient_boosting['subsample'] = subsample[0]
parameter_gradient_boosting['colsample_bytree'] = colsample_bytree[0]
parameter_gradient_boosting['colsample_bylevel'] = colsample_bylevel[0]
parameter_gradient_boosting['base_score'] = base_score[0]
parameter_gradient_boosting['lambda_bias'] = lambda_bias[0]
parameter_gradient_boosting['alpha'] = alpha[0]
parameter_gradient_boosting['tree_method'] = tree_method[0]
parameter_gradient_boosting['sketch_eps'] = sketch_eps[0]
parameter_gradient_boosting['scale_pos_weigth'] = scale_pos_weight[0]
parameter_gradient_boosting['lambda'] = lambda_xgb[0]
else:
#Setting parameters for the Booster which will be optimized later using hyperopt.
#The user can enter a list of values that he wants to optimize
parameter_gradient_boosting['booster'] = booster
parameter_gradient_boosting['eval_metric'] = eval_metric
parameter_gradient_boosting['eta'] = eta
parameter_gradient_boosting['gamma'] = gamma
parameter_gradient_boosting['max_depth'] = max_depth
parameter_gradient_boosting['min_child_weight'] = min_child_weight
parameter_gradient_boosting['max_delta_step'] = max_delta_step
parameter_gradient_boosting['subsample'] = subsample
parameter_gradient_boosting['colsample_bytree'] = colsample_bytree
parameter_gradient_boosting['colsample_bylevel'] = colsample_bylevel
parameter_gradient_boosting['base_score'] = base_score
parameter_gradient_boosting['lambda_bias'] = lambda_bias
parameter_gradient_boosting['alpha'] = alpha
parameter_gradient_boosting['tree_method'] = tree_method
parameter_gradient_boosting['sketch_eps'] = sketch_eps
parameter_gradient_boosting['scale_pos_weigth'] = scale_pos_weight
parameter_gradient_boosting['lambda'] = lambda_xgb
return parameter_gradient_boosting
#Using the loss values, this function picks the optimum parameter values. These values will be used
#for training the model
def gradient_boosting_parameter_optimisation(train_X, train_Y, parameter_gradient_boosting,obj):
space_gradient_boosting = assign_space_gradient_boosting(parameter_gradient_boosting)
trials = Trials()
#Best is used to otmize the objective function
best = fmin(fn = partial(obj, data_X = train_X, data_Y = train_Y\
, parameter_gradient_boosting = parameter_gradient_boosting),
space = space_gradient_boosting,
algo = tpe.suggest,
max_evals = 100,
trials = trials)
optimal_param={}
#Best is a dictionary that contains the indices of the optimal parameter values.
#The following for loop uses these indices to obtain the parameter values, these values are stored in a
#dictionary - optimal_param
for key in best:
optimal_param[key] = parameter_gradient_boosting[key][best[key]]
optimal_param['objective'] = parameter_gradient_boosting['objective']
optimal_param['eval_metric'] = parameter_gradient_boosting['eval_metric']
optimal_param['seed'] = parameter_gradient_boosting['seed']
#Training the model with the optimal parameter values
dtrain = xgb.DMatrix(train_X, label = train_Y)
model = xgb.train(optimal_param, dtrain)
return model
#This function calculates the loss for different parameter values and is used to determine the most optimum
#parameter values
def objective_gradient_boosting(space_gradient_boosting, data_X, data_Y, parameter_gradient_boosting):
#Gradient Boosting (XGBoost)
param = {}
#Setting Parameters for the Booster
param['booster'] = space_gradient_boosting['booster']
param['objective'] = 'binary:logistic'
param['eval_metric'] = parameter_gradient_boosting['eval_metric']
param['eta'] = space_gradient_boosting['eta']
param['gamma'] = space_gradient_boosting['gamma']
param['max_depth'] = space_gradient_boosting['max_depth']
param['min_child_weight'] = space_gradient_boosting['min_child_weight']
param['max_delta_step'] = space_gradient_boosting['max_delta_step']
param['subsample'] = space_gradient_boosting['subsample']
param['colsample_bytree'] = space_gradient_boosting['colsample_bytree']
param['colsample_bylevel'] = space_gradient_boosting['colsample_bylevel']
param['alpha'] = space_gradient_boosting['alpha']
param['scale_pos_weigth'] = space_gradient_boosting['scale_pos_weigth']
param['base_score'] = space_gradient_boosting['base_score']
param['lambda_bias'] = space_gradient_boosting['lambda_bias']
param['lambda'] = space_gradient_boosting['lambda']
param['tree_method'] = space_gradient_boosting['tree_method']
model = xgb.Booster()
auc_list = list()
#Performing cross validation.
skf=StratifiedKFold(data_Y, n_folds=3,random_state=0)
for train_index, cross_val_index in skf:
xgb_train_X, xgb_cross_val_X = data_X.iloc[train_index],data_X.iloc[cross_val_index]
xgb_train_Y, xgb_cross_val_Y = data_Y.iloc[train_index],data_Y.iloc[cross_val_index]
dtrain = xgb.DMatrix(xgb_train_X, label = xgb_train_Y)
model = xgb.train(param, dtrain)
predict = model.predict(xgb.DMatrix(xgb_cross_val_X, label = xgb_cross_val_Y))
auc_list.append(roc_auc_score(xgb_cross_val_Y,predict))
#Calculating the AUC and returning the loss, which will be minimised by selecting the optimum parameters.
auc = np.mean(auc_list)
return{'loss':1-auc, 'status': STATUS_OK }
#Assigning the values of the XGBoost parameters that need to be checked, for minimizing the objective (loss).
#The values that give the most optimum results will be picked to train the model.
def assign_space_gradient_boosting(parameter_gradient_boosting):
space_gradient_boosting ={
'booster': hp.choice('booster', parameter_gradient_boosting['booster']),
'eta': hp.choice('eta', parameter_gradient_boosting['eta']),
'gamma': hp.choice('gamma', parameter_gradient_boosting['gamma']),
'max_depth': hp.choice('max_depth', parameter_gradient_boosting['max_depth']),
'min_child_weight': hp.choice('min_child_weight', parameter_gradient_boosting['min_child_weight']),
'max_delta_step': hp.choice('max_delta_step', parameter_gradient_boosting['max_delta_step']),
'subsample': hp.choice('subsample', parameter_gradient_boosting['subsample']),
'colsample_bytree': hp.choice('colsample_bytree', parameter_gradient_boosting['colsample_bytree']),
'colsample_bylevel': hp.choice('colsample_bylevel', parameter_gradient_boosting['colsample_bylevel']),
'alpha': hp.choice('alpha', parameter_gradient_boosting['alpha']),
'scale_pos_weigth': hp.choice('scale_pos_weigth', parameter_gradient_boosting['scale_pos_weigth']),
'base_score': hp.choice('base_score', parameter_gradient_boosting['base_score']),
'lambda_bias': hp.choice('lambda_bias', parameter_gradient_boosting['lambda_bias']),
'lambda': hp.choice('lambda', parameter_gradient_boosting['lambda']),
'tree_method': hp.choice('tree_method', parameter_gradient_boosting['tree_method'])
}
return space_gradient_boosting
def predict_gradient_boosting(data_X, data_Y, gradient_boosting):
predicted_values = gradient_boosting.predict(xgb.DMatrix(data_X, label = data_Y))
auc = roc_auc_score(data_Y, predicted_values)
return [auc,predicted_values]
```
# Decision Tree
```
#Trains the Decision Tree model. Performing a grid search to select the optimal parameter values
def train_decision_tree(train_X, train_Y, parameters_decision_tree):
decision_tree_model = DecisionTreeClassifier()
model_gs = grid_search.GridSearchCV(decision_tree_model, parameters_decision_tree, scoring = 'roc_auc')
model_gs.fit(train_X,train_Y)
return model_gs
#Predicts the output on a set of data, the built model is passed as a parameter, which is used to predict
def predict_decision_tree(data_X, data_Y, decision_tree):
predicted_values = decision_tree.predict_proba(data_X)[:, 1]
auc = roc_auc_score(data_Y, predicted_values)
return [auc,predicted_values]
def parameter_set_decision_tree(criterion = ['gini'], splitter = ['best'], max_depth = [None],\
min_samples_split = [2], min_samples_leaf = [1], min_weight_fraction_leaf = [0.0],\
max_features = [None], random_state = [None], max_leaf_nodes = [None],\
class_weight = [None], presort = [False]):
parameters_decision_tree = {}
parameters_decision_tree['criterion'] = criterion
parameters_decision_tree['splitter'] = splitter
parameters_decision_tree['max_depth'] = max_depth
parameters_decision_tree['min_samples_split'] = min_samples_split
parameters_decision_tree['min_samples_leaf'] = min_samples_leaf
parameters_decision_tree['min_weight_fraction_leaf'] = min_weight_fraction_leaf
parameters_decision_tree['max_features'] = max_features
parameters_decision_tree['random_state'] = random_state
parameters_decision_tree['max_leaf_nodes'] = max_leaf_nodes
parameters_decision_tree['class_weight'] = class_weight
parameters_decision_tree['presort'] = presort
return parameters_decision_tree
```
# Random Forest
```
#Trains the Random Forest model. Performing a grid search to select the optimal parameter values
def train_random_forest(train_X, train_Y, parameters_random_forest):
random_forest_model = RandomForestClassifier()
model_gs = grid_search.GridSearchCV(random_forest_model, parameters_random_forest, scoring = 'roc_auc')
model_gs.fit(train_X,train_Y)
return model_gs
#Predicts the output on a set of data, the built model is passed as a parameter, which is used to predict
def predict_random_forest(data_X, data_Y, random_forest):
predicted_values = random_forest.predict_proba(data_X)[:, 1]
auc = roc_auc_score(data_Y, predicted_values)
return [auc,predicted_values]
#Parameters for random forest. To perform hyper parameter optimisation a list of multiple elements can be entered
#and the optimal value in that list will be picked using grid search
def parameter_set_random_forest(n_estimators = [10], criterion = ['gini'], max_depth = [None],\
min_samples_split = [2], min_samples_leaf = [1], min_weight_fraction_leaf = [0.0],\
max_features = ['auto'], max_leaf_nodes = [None], bootstrap = [True],\
oob_score = [False], random_state = [None], verbose = [0],warm_start = [False],\
class_weight = [None]):
parameters_random_forest = {}
parameters_random_forest['criterion'] = criterion
parameters_random_forest['n_estimators'] = n_estimators
parameters_random_forest['max_depth'] = max_depth
parameters_random_forest['min_samples_split'] = min_samples_split
parameters_random_forest['min_samples_leaf'] = min_samples_leaf
parameters_random_forest['min_weight_fraction_leaf'] = min_weight_fraction_leaf
parameters_random_forest['max_features'] = max_features
parameters_random_forest['random_state'] = random_state
parameters_random_forest['max_leaf_nodes'] = max_leaf_nodes
parameters_random_forest['class_weight'] = class_weight
parameters_random_forest['bootstrap'] = bootstrap
parameters_random_forest['oob_score'] = oob_score
parameters_random_forest['warm_start'] = warm_start
return parameters_random_forest
```
# Linear Regression
```
#Trains the Linear Regression model. Performing a grid search to select the optimal parameter values
def train_linear_regression(train_X, train_Y, parameters_linear_regression):
linear_regression_model = linear_model.LinearRegression()
train_X=StandardScaler().fit_transform(train_X)
model_gs = grid_search.GridSearchCV(linear_regression_model, parameters_linear_regression, scoring = 'roc_auc')
model_gs.fit(train_X,train_Y)
return model_gs
#Predicts the output on a set of data, the built model is passed as a parameter, which is used to predict
def predict_linear_regression(data_X, data_Y, linear_regression):
data_X = StandardScaler().fit_transform(data_X)
predicted_values = linear_regression.predict(data_X)
auc = roc_auc_score(data_Y, predicted_values)
return [auc,predicted_values]
#Parameters for random forest. To perform hyper parameter optimisation a list of multiple elements can be entered
#and the optimal value in that list will be picked using grid search
def parameter_set_linear_regression(fit_intercept = [True], normalize = [False], copy_X = [True]):
parameters_linear_regression = {}
parameters_linear_regression['fit_intercept'] = fit_intercept
parameters_linear_regression['normalize'] = normalize
return parameters_linear_regression
```
# Logistic Regression
```
#Trains the Logistic Regression model. Performing a grid search to select the optimal parameter values
def train_logistic_regression(train_X, train_Y, parameters_logistic_regression):
logistic_regression_model = linear_model.LogisticRegression()
train_X=StandardScaler().fit_transform(train_X)
model_gs = grid_search.GridSearchCV(logistic_regression_model, parameters_logistic_regression,\
scoring = 'roc_auc')
model_gs.fit(train_X,train_Y)
return model_gs
#Predicts the output on a set of data, the built model is passed as a parameter, which is used to predict
def predict_logistic_regression(data_X, data_Y, logistic_regression):
data_X = StandardScaler().fit_transform(data_X)
predicted_values = logistic_regression.predict_proba(data_X)[:,1]
auc = roc_auc_score(data_Y, predicted_values)
return [auc,predicted_values]
#Parameters for random forest. To perform hyper parameter optimisation a list of multiple elements can be entered
#And the optimal value in that list will be picked using grid search
def parameter_set_logistic_regression(penalty = ['l2'], dual = [False], tol = [0.0001], C = [1.0],\
fit_intercept = [True], intercept_scaling = [1], class_weight = [None],\
random_state = [None], solver = ['liblinear'], max_iter = [100],\
multi_class = ['ovr'], verbose = [0], warm_start = [False]):
parameters_logistic_regression = {}
parameters_logistic_regression['penalty'] = penalty
parameters_logistic_regression['dual'] = dual
parameters_logistic_regression['tol'] = tol
parameters_logistic_regression['C'] = C
parameters_logistic_regression['fit_intercept'] = fit_intercept
parameters_logistic_regression['intercept_scaling'] = intercept_scaling
parameters_logistic_regression['class_weight'] = class_weight
parameters_logistic_regression['solver'] = solver
parameters_logistic_regression['max_iter'] = max_iter
parameters_logistic_regression['multi_class'] = multi_class
parameters_logistic_regression['warm_start'] = warm_start
return parameters_logistic_regression
```
# Stacking
```
#The stacked ensmeble will be trained by using one or more of the base model algorithms
#The function of the base model algorithm that will be used to train will be passed as the
#model_function parameter and the parameters required to train the algorithm/model will be passed as the
#model_parameters parameter
def train_stack(data_X, data_Y, model_function, model_parameters):
model = model_function(data_X, data_Y, model_parameters)
return model
#Predicts the output on a set of stacked data, after the stacked model has been built by using a base model
#algorithm, hence we need the predict funcction of that base model algorithm to get the predictions
#The predict function of the base model is passed as the predict_function parameter and its respective model is
#passed as the model parameter
def predict_stack(data_X, data_Y, predict_function, model):
auc,predicted_values = predict_function(data_X, data_Y, model)
return [auc,predicted_values]
```
# Blending
```
#The blending ensmeble will be trained by using one or more of the base model algorithms
#The function of the base model algorithm that will be used to train will be passed as the
#model_function parameter and the parameters required to train the algorithm/model will be passed as the
#model_parameters parameter
def train_blend(data_X, data_Y, model_function, model_parameters):
model = model_function(blend_X, data_Y, model_parameters)
return model
#Predicts the output on a set of blended data, after the blending model has been built by using a base model
#algorithm, hence we need the predict function of that base model algorithm to get the predictions
#The predict function of the base model is passed as the predict_function parameter and its respective model is
#passed as the model parameter
def predict_blend(data_X, data_Y, predict_function, model):
auc,predicted_values = predict_function(test_blend_X, data_Y, model)
return [auc,predicted_values]
```
# Weighted Average
```
#Perfroms weighted average of the predictions of the base models. The function that calculates the optimum
# combination of weights is passsed as the get_weight_function parameter
#The weight_list parameter contains the weights associated with the model, they are either default weights or a list
#of weights. Using these weigths we either train the model or perform hyper parameter optimisation if there
#is a list of weights that need to be checked to find the optimum weights
def weighted_average(data_X, data_Y, hyper_parameter_optitmisation, weight_list):
#Checking if hyper_parameter_optimisation is true
if(hyper_parameter_optitmisation == True):
#The last element of the weight_list which indicates wether the user wants to perform hyper parameter
#optimisation is deleted
del weight_list[-1]
#Optimisation is performed by passing the weight_list we want to optimize
weight = get_optimized_weights(weight_list, data_X, data_Y)
#Is none when performing weighted average on test data, we dont need to do anything else as we already have
#the weights for performing the weighted average
elif(hyper_parameter_optitmisation == None):
weight = weight_list
else:
#The last element of the weight_list which indicates wether the user wants to perform hyper parameter
#optimisation is deleted
del weight_list[-1]
#The weight_list is now used to calculate the weighted average
weight = weight_list
weighted_avg_predictions=np.average(data_X, axis = 1, weights = weight)
auc = roc_auc_score(data_Y, weighted_avg_predictions)
return [auc,weighted_avg_predictions,weight]
#Function that finds the best possible combination of weights for performing the weighted predictions.
def get_optimized_weights(weight_list, X, Y):
space = assign_space_weighted_average(weight_list)
trials = Trials()
best = fmin(fn = partial(objective_weighted_average, data_X = X, data_Y = Y),
space = space,
algo = tpe.suggest,
max_evals = 50,
trials = trials)
best_weights = list()
#Arranging the weights in order of the respective models, and then returning the list of weights.
for key in sorted(best):
best_weights.append(best[key])
return best_weights
#Defining the objective. Appropriate weights need to be calculated to minimize the loss.
def objective_weighted_average(space, data_X, data_Y):
weight_search_space = list()
#Picking weights in the seacrh space to compute the best combination of weights
for weight in sorted(space):
weight_search_space.append(space[weight])
weighted_avg_predictions = np.average(data_X, axis = 1, weights = weight_search_space)
auc = roc_auc_score(data_Y, weighted_avg_predictions)
return{'loss':1-auc, 'status': STATUS_OK }
#Assigning the weights that need to be checked, for minimizing the objective (Loss)
def assign_space_weighted_average(weight_list):
space = {}
space_index = 0
for weight in weight_list:
#Assigning the search space, the search space is the range of weights that need to be searched for each
#base model, to find the weight of that base models predictions
space['w'+str(space_index )] = hp.choice('w'+str(space_index ), weight)
space_index = space_index + 1
return space
#The user can either use the default weights or provide their own list of values.
def assign_weights(weights = 'default',hyper_parameter_optimisation = False):
weight_list = list()
#The last element of the weight_list will indicate wether hyper parameter optimisation needs to be peroformed
if(hyper_parameter_optimisation == True):
if(weights == 'default'):
weight_list = [range(10)] * no_of_base_models
weight_list.append(True)
else:
weight_list = weights
weight_list.append(True)
else:
if(weight == 'default'):
weight_list = [1] * no_of_base_models
weight_list.append(False)
else:
weight_list = weights
weight_list.append(False)
return weight_list
```
# Setup for training and computing predictions for the models
```
#Constructing a list (train_model_list) that contains a tuple for each base model, the tuple contains the name of
#the function that trains the base model, and the paramters for training the base model.
#Constructing a list (predict_model_list) that contains a tuple for each base model, the tuple contains the name of
#the function that computes the predictions for the base model.
#In the list computed for stacking and blending, the tuples have an additional element which is the train_stack
#function or the train_blend function. This is done because different set of data (predictions of base models)
#needs to be passed to the base model algorithms. These function enable performing the above procedure
#These lists are constructed in such a way to enable the ease of use of the joblib library, i.e the parallel
#module/function
def construct_model_parameter_list(model_list, parameters_list, stack = False, blend = False):
model_functions = {'gradient_boosting' : [train_gradient_boosting,predict_gradient_boosting],
'decision_tree' : [train_decision_tree,predict_decision_tree],
'random_forest' : [train_random_forest,predict_random_forest],
'linear_regression' : [train_linear_regression,predict_linear_regression],
'logistic_regression' : [train_logistic_regression,predict_logistic_regression]
}
train_model_list = list()
predict_model_list = list()
model_parameter_index = 0
for model in model_list:
if(stack == True):
train_model_list.append((model_functions[model][0],parameters_list[model_parameter_index]\
,train_stack))
predict_model_list.append((model_functions[model][1],predict_stack))
elif(blend == True):
train_model_list.append((model_functions[model][0],parameters_list[model_parameter_index]\
,train_blend))
predict_model_list.append((model_functions[model][1],predict_blend))
else:
train_model_list.append((model_functions[model][0],parameters_list[model_parameter_index]))
predict_model_list.append(model_functions[model][1])
model_parameter_index = model_parameter_index + 1
return [train_model_list,predict_model_list]
#This function computes a list where each element is a tuple that contains the predict function of the base model
#along with the corresponding base model object. This is done so that the base model object can be passed to the
#predict function as a prameter to compute the predictions when using joblib's parallel module/function.
def construct_model_predict_function_list(model_list, models,predict_model_list):
model_index = 0
model_function_list = list()
for model in model_list:
model_function_list.append((predict_model_list[model_index],models[model_index]))
model_index = model_index + 1
return model_function_list
```
# Training base models
```
#This function calls the respective training and predic functions of the base models.
def train_base_models(model_list,parameters_list):
#Cross Validation using Stratified K Fold
train, cross_val = train_test_split(Data, test_size = 0.4, stratify = Data['y'],random_state=0)
#Training the base models, and calculating AUC on the cross validation data.
#Selecting the data (Traing Data & Cross Validation Data)
train_Y = train['y']
train_X = train.drop(['y'],axis=1)
cross_val_Y = cross_val['y']
cross_val_X = cross_val.drop(['y'],axis=1)
#The list of base models the user wants to train.
global base_model_list
base_model_list = model_list
#No of base models that user wants to train
global no_of_base_models
no_of_base_models = len(base_model_list)
#We get the list of base model training functions and predict functions. The elements of the two lists are
#tuples that have (base model training function,model parameters), (base model predict functions) respectively
[train_base_model_list,predict_base_model_list] = construct_model_parameter_list(base_model_list,\
parameters_list)
#Training the base models parallely, the resulting models are stored which will be used for cross validation.
models = (Parallel(n_jobs = -1)(delayed(function)(train_X, train_Y, model_parameter)\
for function, model_parameter in train_base_model_list))
#A list with elements as tuples containing (base model predict function, and its respective model object) is
#returned. This list is used in the next step in the predict_base_models function, the list will be used in
#joblibs parallel module/function to compute the predictions and metric scores of the base models
global base_model_predict_function_list
base_model_predict_function_list = construct_model_predict_function_list(base_model_list, models,\
predict_base_model_list)
predict_base_models(cross_val_X, cross_val_Y,mode = 'train')
```
# Predictions of base models
```
def predict_base_models(data_X, data_Y,mode):
predict_list = list()
predict_gradient_boosting = list()
predict_multi_layer_perceptron = list()
predict_decision_tree = list()
predict_random_forest = list()
predict_linear_regression = list()
predict_logistic_regression = list()
metric_linear_regression = list()
metric_logistic_regression = list()
metric_decision_tree = list()
metric_random_forest = list()
metric_multi_layer_perceptron = list()
metric_gradient_boosting = list()
auc_predict_index = 0
#Initializing a list which will contain the predictions of the base models and the variables that will
#calculate the metric score
model_predict_metric = {'gradient_boosting' : [predict_gradient_boosting, metric_gradient_boosting],
'multi_layer_perceptron' : [predict_multi_layer_perceptron, metric_multi_layer_perceptron],
'decision_tree' : [predict_decision_tree, metric_decision_tree],
'random_forest' : [predict_random_forest, metric_random_forest],
'linear_regression' : [predict_linear_regression, metric_linear_regression],
'logistic_regression' : [predict_logistic_regression, metric_logistic_regression]
}
#Computing the AUC and Predictions of all the base models on the cross validation data parallely.
auc_predict_cross_val = (Parallel(n_jobs = -1)(delayed(function)(data_X, data_Y, model)
for function, model in base_model_predict_function_list))
#Building the list which will contain all the predictions of the base models and will also display the metric
#scores of the base models
for model in base_model_list:
#Assigning the predictions and metrics computed for the respective base model
model_predict_metric[model] = auc_predict_cross_val[auc_predict_index][1],\
auc_predict_cross_val[auc_predict_index][0]
auc_predict_index = auc_predict_index + 1
if(model == 'multi_layer_perceptron'):
#This is done only for multi layer perceptron because the predictions returned by the multi layer
#perceptron model is a list of list, the below pice of code converts this nested list into a single
#list
predict_list.append(np.asarray(sum(model_predict_metric[model][0].tolist(), [])))
else:
#The below list will contain all the predictions of the base models.
predict_list.append(model_predict_metric[model][0])
#Printing the name of the base model and its corresponding metric score
print_metric(model,model_predict_metric[model][1])
if(mode == 'train'):
#Function to construct dataframes for training the second level/ensmeble models using the predictions of the
#base models on the train dataset
second_level_train_data(predict_list, data_X, data_Y)
else:
#Function to construct dataframes for testing the second level/ensmeble models using the predictions of the
#base models on the test dataset
second_level_test_data(predict_list, data_X, data_Y)
#The trained base model objects can be saved and used later for any other purpose. The models asre save using
#joblib's dump. The models are named base_model1, base_model2..so on depending on the order entered by the user
#while training these models in the train_base_model function
def save_base_models(models):
model_index = 0
for model in models:
joblib.dump(model, 'base_model'+str(model_index)+'.pkl')
model_index = model_index + 1
#This function will return the trained base model objects once they have been saved in the function above. All the
#trained models are returned in a list called models
def get_base_models():
models = list()
for model_index in range(no_of_base_models):
models.append(joblib.load('base_model'+str(model_index)+'.pkl'))
return models
```
# Training the ensemble/second level models
```
#Training the second level models parallely
def train_ensemble_models(stack_model_list = [], stack_parameters_list = [], blend_model_list = [],\
blend_parameters_list = [], perform_weighted_average = None, weights_list = None):
#This list will contain the names of the models/algorithms that have been used as second level models
#This list will be used later in the testing phase for identifying which model belongs to which ensemble
#(stacking or blending), hence the use of dictionaries as elements of the list
#Analogous to the base_model_list
global ensmeble_model_list
ensmeble_model_list = list()
#The list will be used to train the ensemble models, while using joblib's parallel
train_second_level_models = list()
#Stacking will not be done if user does not enter the list of models he wants to use for stacking
if(stack_model_list != []):
#Appending a dictionary that contians key-Stacking and its values/elements are the names of the
#models/algorithms that are used for performing the stacking procedure, this is done so that it will be easy
#to identify the models belonging to the stacking ensemble
ensmeble_model_list.append({'Stacking' : stack_model_list})
#We get the list of stacked model training functions and predict functions. The elements of the two
#lists are tuples that have(base model training function,model parameters,train_stack function),
#(base model predict functions,predict_stack function) respectively
[train_stack_model_list,predict_stack_model_list] = construct_model_parameter_list(stack_model_list,\
stack_parameters_list,
stack=True)
#Blending will not be done if user does not enter the list of models he wants to use for blending
if(blend_model_list != []):
#Appending a dictionary that contians key-Blending and its values/elements are the names of the
#models/algorithms that are used for performing the blending procedure, this is done so that it will be easy
#to identify the models belonging to the blending ensemble
ensmeble_model_list.append({'Blending' : blend_model_list})
#We get the list of blending model training functions and predict functions. The elements of the two
#lists are tuples that have(base model training function,model parameters,train_blend function),
#(base model predict functions,predict_blend function) respectively
[train_blend_model_list,predict_blend_model_list] = construct_model_parameter_list(blend_model_list,\
blend_parameters_list,\
blend=True)
#The new list contains either the stacked models or blending models or both or remain empty depending on what
#the user has decided to use
train_second_level_models = train_stack_model_list + train_blend_model_list
#If the user wants to perform a weighted average, a tuple containing (hyper parmeter optimisation = True/False,
#the lsit of weights either deafult or entered by the user, and the function that performs the weighted average)
#will be created. This tuple will be appended to the list above
#weights_list[-1] is an element of the list that indicates wwether hyper parameter optimisation needs to be
#perofrmed
if(perform_weighted_average == True):
train_weighted_average_list = (weights_list[-1], weights_list, weighted_average)
train_second_level_models.append(train_weighted_average_list)
#Training the ensmeble models parallely
models = Parallel(n_jobs = -1)(delayed(function)(stack_X, stack_Y, model, model_parameter)\
for model, model_parameter, function in train_second_level_models)
#A list with elements as tuples containing (base model predict function, its respective model object,and
#predict_stack or predict_blend functions) is returned. This list is used in the next step in the
#predict_ensemble_models function, the list will be used in
#joblibs parallel module/function to compute the predictions and metric score of the ensemble models
#Analogous to base_model_predict_function_list
global ensmeble_model_predict_function_list
ensmeble_model_predict_function_list = construct_model_predict_function_list(stack_model_list + blend_model_list,\
models, predict_stack_model_list
+ predict_blend_model_list)
if(perform_weighted_average == True):
weight = models[-1][-1]
print('Weighted Average')
print('Weight',weight)
print('Metric Score',models[-1][0])
ensmeble_model_list.append({'Weighted Average' : [str(weight)]})
ensmeble_model_predict_function_list.append(((None,weighted_average),weight))
def predict_ensemble_models(data_X, data_Y):
metric_linear_regression = list()
metric_logistic_regression = list()
metric_decision_tree = list()
metric_random_forest = list()
metric_multi_layer_perceptron = list()
metric_gradient_boosting = list()
metric_weighted_average = list()
metric_stacking = list()
metric_blending = list()
auc_predict_index = 0
#Initializing a list which will contain the predictions of the base models and the variables that will
#calculate the metric score
model_metric = {'gradient_boosting' : [metric_gradient_boosting],
'multi_layer_perceptron' : [metric_multi_layer_perceptron],
'decision_tree' : [metric_decision_tree],
'random_forest' : [metric_random_forest],
'linear_regression' : [metric_linear_regression],
'logistic_regression' : [metric_logistic_regression]
}
#Computing the AUC and Predictions of all the base models on the cross validation data parallely.
auc_predict_cross_val = (Parallel(n_jobs = -1)(delayed(function[1])(data_X, data_Y, function[0],model)
for function, model in ensmeble_model_predict_function_list))
for ensemble_models in ensmeble_model_list:
for ensemble,models in ensemble_models.items():
for model in models:
#Assigning the predictions and metrics computed for the respective base model
model_metric[model] = auc_predict_cross_val[auc_predict_index][0]
auc_predict_index = auc_predict_index + 1
#Printing the name of the base model and its corresponding metric score
print_metric(ensemble + " " + model,model_metric[model])
def test_data():
#Training the base models, and calculating AUC on the test data.
#Selecting the data (Test Data)
test_Y = test['y']
test_X = test.drop(['y'],axis=1)
predict_base_models(test_X,test_Y,mode='test')
predict_ensemble_models(test_stack_X,test_stack_Y)
def print_metric(model,metric_score):
#Printing the metric score for the corresponding model.
print (model,'\n',metric_score)
Data = pd.read_csv('/home/prajwal/Desktop/bank-additional/bank-additional-full.csv',delimiter=';',header=0)
%%time
data_import(Data)
a = parameter_set_gradient_boosting(eval_metric=['auc'],objective = ['binary:logistic'])
b = parameter_set_decision_tree()
c = parameter_set_random_forest()
d = parameter_set_linear_regression()
e = parameter_set_logistic_regression()
f = parameter_set_logistic_regression(penalty =['l1'])
g = parameter_set_gradient_boosting(eval_metric=['auc'],objective = ['binary:logistic'],booster=['gblinear'])
train_base_models(['gradient_boosting','decision_tree',\
'random_forest','linear_regression','logistic_regression',\
'logistic_regression','gradient_boosting'],[a,b,c,d,e,f,g])
w = assign_weights(weights = 'default',hyper_parameter_optimisation = True)
train_ensemble_models(['linear_regression','logistic_regression'],[d,e],['gradient_boosting','gradient_boosting'],\
[a,g],True,w)
test_data()
```
| github_jupyter |
<table class="ee-notebook-buttons" align="left">
<td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Visualization/color_by_attribute.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td>
<td><a target="_blank" href="https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/Visualization/color_by_attribute.ipynb"><img width=26px src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png" />Notebook Viewer</a></td>
<td><a target="_blank" href="https://mybinder.org/v2/gh/giswqs/earthengine-py-notebooks/master?filepath=Visualization/color_by_attribute.ipynb"><img width=58px src="https://mybinder.org/static/images/logo_social.png" />Run in binder</a></td>
<td><a target="_blank" href="https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/Visualization/color_by_attribute.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a></td>
</table>
## Install Earth Engine API
Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geehydro](https://github.com/giswqs/geehydro). The **geehydro** Python package builds on the [folium](https://github.com/python-visualization/folium) package and implements several methods for displaying Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, `Map.centerObject()`, and `Map.setOptions()`.
The magic command `%%capture` can be used to hide output from a specific cell.
```
# %%capture
# !pip install earthengine-api
# !pip install geehydro
```
Import libraries
```
import ee
import folium
import geehydro
```
Authenticate and initialize Earth Engine API. You only need to authenticate the Earth Engine API once. Uncomment the line `ee.Authenticate()`
if you are running this notebook for this first time or if you are getting an authentication error.
```
# ee.Authenticate()
ee.Initialize()
```
## Create an interactive map
This step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function.
The optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `ESRI`.
```
Map = folium.Map(location=[40, -100], zoom_start=4)
Map.setOptions('HYBRID')
```
## Add Earth Engine Python script
```
fc = ee.FeatureCollection('TIGER/2018/States')
print(fc.first().getInfo())
# Use this empty image for paint().
empty = ee.Image().byte()
palette = ['green', 'yellow', 'orange', 'red']
states = empty.paint(**{
'featureCollection': fc,
'color': 'ALAND',
})
Map.addLayer(states, {'palette': palette}, 'US States')
```
## Display Earth Engine data layers
```
Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True)
Map
```
| github_jupyter |
This notebook aims to show the effects of incorporating curvature of flow into the assessment of vertical-axis wind turbine (VAWT) calculations. To this end, a method of assessing a VAWT must be used.
The simplest methods to analyze the flow through a VAWT are streamtube models.
Parallel to the oncoming wind, the area of the VAWT is split into several streamtubes that are assumed to be independent from each other.
For each streamtube, momentum theory is used to calculate the induction at the blade and the reduction in speed in the wake.
VAWT flow is inherently more complicated than the flow through a horizontal-axis wind turbine.
There, an axis of symmetry is available and the blades are in a quasi-steady operation under locally constant angle of attack during the rotation.
No such symmetry exists in VAWT flow, and the blades see a permanent change in angle of attack.
Worse, half the time a blade is passing through the wake of the front.
Nevertheless, double multiple streamtube models [1] (DMST) are routinely used to model these machines.
These models split the streamtubes perpendicular to the flow in half, upwind and downwind, and use momentum theory for both halves.
As pointed out in [2] and other publication by the first author, the double multiple streamtube models have significant downsides:
1. They do not model induced flow perpendicular to the flow without considerable modifications.
2. They do not model any effect the wake has on the flow in the turbine, besides the aspects captured by momentum balance.
3. For different pitch angles, which change the zero-lift angle of attack, DMST models predict significantly different induced velocities that are not seen by other methods.
Especially the third point is troublesome, because flow curvature changes the camber and the effective pitch angle.
Thus the analysis of the influence of curvature using a DMST model is not possible.
However, there is a rather simple fix to the double multiple streamtube model that overcomes this limitation.
Which is presented here and which I will call **Tandem Multiple Streamtube Model** (TMST), which is a rather simple variant of the *non*-double multiple streamtube model.
This notebook is thus structured as follows:
- Part A: An introduction into the tandem multiple streamtube model and a comparison with other models and the regular double multiple streamtube model.
- Part B: A comparison of calculating the loads and torque of a VAWT using airfoil lift and drag with and without flow curvature effects.
## Part A: Tandem Multiple Streamtube Model
The problem with the DMST model is the separation of the streamtubes in upwind and downwind streamtubes, where the upwind part is unconcerned of the effect the downwind part has on the flow.
However, a VAWT acts as one flow reducing machine where the deceleration of flow on the back also induces a change in the flow at the front, both are part of the actuator that reduces flow velocity and transforms that momentum into force.
Instead of assuming equilibrium conditions and using the momentum theory twice, the TMST model uses a single momentum equation.
This is used to find the force sum the two halves take out of the flow and the velocity in the center of the VAWT.
In addition, the upwind half sees oncoming flow somewhere between the free velocity and the velocity at the center, while the downwind half sees oncoming flow between the velocity at the center and the far wake.
The implementation follows common DMST implementations, but uses a root finding algorithm instead of some iteration which has also been done in [3].
Here, it is assumed the the airfoil is pointing inwards, i.e. a positive lift point towards the center of the VAWT.
### Nomenclature
- $\lambda_0$: The ratio of flow at the center of the VAWT by free flow
- $\lambda_1$: The ratio of flow at the front of the VAWT by free flow
- $\lambda_2$: The ratio of flow at the back of the VAWT by free flow
- $\lambda_{12}$: The ratio of flow at the back of the VAWT by the far wake flow after the front actuator disk given by $(2\lambda_1-1)$
- $\theta$: The current azimuthal angle of the streamtube, negative or >180° for downwind.
- $\sigma$: VAWT solidity given by number of blades times chord divided by VAWT diameter $\sigma = \frac{N_b c}{2 R}$
- $v_t$: Tangential speed of a blade
- $w$: Free flow speed
- $TSR$: Tip-speed ratio, $v_t/w$
- $\rho$: Density of fluid
### DMST
The tangential force of a single blade is given by
$$ \frac{\rho}{2} c v_a^2 (-CD\cos\alpha+CL \sin\alpha). $$
The tangential tangential force coefficient with respect to the wind speed and VAWT area for the number of blades is then
$$ F_{t}(\theta) = N_b \frac{ \frac{\rho}{2} c v_a^2 (-CD\cos\alpha+CL \sin\alpha)}{\frac{\rho}{2} 2 R w^2} = \sigma \frac{v_a^2}{w^2} (-CD\cos\alpha+CL \sin\alpha), $$
such that
$$ c_{p} = \frac{1}{2\pi}\int_0^{2\pi}\frac{f_t v_t}{\frac{\rho}{2} 2 R w^3} \mathrm{d}\theta = \frac{TSR}{2\pi}\int_0^{2\pi} F_{t}(\theta) \mathrm{d}\theta. $$
The normal force $F_n$ and force in direction of the streamline $F_{st}$ are given by
$$ F_{n}(\lambda) = \sigma \frac{v_a^2}{w^2} ( CD\sin\alpha+CL \cos\alpha) $$
$$ F_{st}(\lambda) = -F_{t} \cos\theta+F_n\sin\theta. $$
For a single streamtube, the area per $\Delta\theta$ is given by $|\sin(\theta)|\Delta\theta$, while the force of the blades is given by $F_t\frac{\Delta\theta}{\pi}$ for a constant coefficient over $\Delta\theta$.
At every streamtube the aerodynamic force $F_{st}\frac{\Delta\theta}{\pi}$ should be equal to the force by momentum theory
$$ 4 \lambda_1 (1-\lambda_1)|\sin\theta|\pi = F_{st}(\lambda_1). $$
In the back, the free velocity is reduced to $2\lambda_1-1$ and thus
$$ 4 \lambda_{12} (1-\lambda_{12})(2\lambda_1-1)^2|\sin\theta|\pi = F_{st}((2\lambda_1-1)\lambda_{12}). $$
### TMST
With the definitions above the momentum balance states
$$ 4 \lambda_0 (1-\lambda_0)|\sin\theta|\pi = F_{st}(\lambda_1)+F_{st}(\lambda_2).$$
With $\lambda_1 = 0.5(1+\lambda_0)$ and $\lambda_2 = 0.5 (\lambda_0+1-2\lambda_0)$ one can mimic the ratios of the DMST, albeit with a single momentum balance.
By using $\lambda_1=\lambda_2=\lambda_0$ one would get the regular multiple streamtube model.
A ratio of $2/3\lambda_0$ and $1/3$ of free velocity or wake velocity, respectively, seems better then 0.5 in the below comparison.
### Discussion
The comparison shows the improvement with respect to the change in pitch on the induction factor.
All more detailed models from the reference predict insignificant changes of streamwise induction due to a change in pitch, while the DMST model predicts a significant change on the upwind half.
The TMST model does no such thing and, arguably incidentally, fits the predictions of the other methods better.
This does not fix the other issues with streamtube models, but the TMST allows a comparison of prediction with and without the inclusion of curvature.
```
import numpy as np
from numpy import pi, sin, cos, mod, sqrt, arctan2
import matplotlib.pyplot as plt
import matplotlib
%matplotlib inline
%config InlineBackend.figure_format = 'svg'
import viiflow as vf
import viiflowtools.vf_tools as vft
import viiflowtools.vf_plots as vfp
import numba as nb
from numba import njit, f8
# Blade aerodynamics
# Define using CL/CD tables
def CLCDTAB():
tabAOA = np.arange(-180.0,180.0,1.0)
tabRE = np.asarray([1000000.0])
tabCL = np.asmatrix(2*pi*1.11*sin(tabAOA*pi/180)).T
tabCD = np.asmatrix(0.0*tabAOA).T
return [tabAOA,tabRE,tabCL,tabCD]
@njit(nb.types.Tuple((f8,f8))(f8,f8,f8[:],f8[:],f8[:,:],f8[:,:]))
def CLCD(AOA,RE,tabAOA,tabRE,tabCL,tabCD):
iAOA = np.maximum(np.searchsorted(tabAOA,AOA,'right')-1,0)
iRE = np.maximum(np.searchsorted(tabRE,RE,'right')-1,0)
# Convert to unit square
AOA0 = tabAOA[iAOA]
if iAOA == len(tabAOA)-1:
jAOA = iAOA
AOA1 = tabAOA[jAOA]
DAOA = 1.0
else:
jAOA = iAOA+1
AOA1 = tabAOA[jAOA]
DAOA = AOA1-AOA0
AOA -= AOA0
AOA /= DAOA
RE0 = tabRE[iRE]
if iRE == len(tabRE)-1:
jRE = iRE
RE1 = tabRE[jRE]
DRE = 1.0
else:
jRE = iRE+1
RE1 = tabRE[jRE]
DRE = RE1-RE0
RE -= RE0
RE /= DRE
# Bilinear interpolation
CL = tabCL[iAOA,iRE]*(1-AOA)*(1-RE) + tabCL[jAOA,iRE]*AOA*(1-RE) + tabCL[iAOA,jRE]*(1-AOA)*RE + tabCL[jAOA,jRE]*AOA*RE
CD = tabCD[iAOA,iRE]*(1-AOA)*(1-RE) + tabCD[jAOA,iRE]*AOA*(1-RE) + tabCD[iAOA,jRE]*(1-AOA)*RE + tabCD[jAOA,jRE]*AOA*RE
return (CL,CD)
# Momentum function
@njit(f8(f8))
def f_momentum(lam):
if lam<0.5*sqrt(1.6):
return 1.6-4*(sqrt(1.6)-1)*lam
else:
return 4.0*lam*(1.0-lam)
# Aero function
@njit(nb.types.Tuple((f8,f8,f8,f8))(f8,f8,f8,f8,f8,f8,f8[:],f8[:],f8[:,:],f8[:,:]))
def ft_aero(lam,TSR,theta,sig,pitch,RE,tabAOA,tabRE,tabCL,tabCD):
st = sin(theta)
ct = cos(theta)
AOA = arctan2(lam*st,lam*ct+TSR)
(CL,CD) = CLCD(AOA*180/pi+pitch,RE,tabAOA,tabRE,tabCL,tabCD)
lamrsq = (TSR+ct*lam)**2+(st*lam)**2
FT = sig*lamrsq*(-cos(AOA)*CD+CL*sin(AOA))
FN = sig*lamrsq*(sin(AOA)*CD+CL*cos(AOA))
Fx = -FT*ct+FN*(st)
return (Fx,FT,FN,AOA*180/pi+pitch)
# Cp and Ct from streamtube model results
def CoefVAWT(FT,TSR):
# Torque Coefficient
# Trapezoidical rule mean value.
# Endpoints at 0,180 not part of the calculation above, but are zero. (+2)
CT = np.sum(FT)/len(FT+2)
# Power Coefficient
CP = CT*TSR
return (CP,CT)
# Solves a lambda searching problem by simple finite difference Newton method
def simpleNewton(fun, x0,maxiter):
x = x0
e = 1e-7
for k in range(maxiter):
Fx = fun(x)
if abs(Fx)<e:
return (x,True)
Fx1 = fun(x+e)
dFdx = (Fx1-Fx)/e
if dFdx == 0.0:
return (x, True)
dx = -Fx/dFdx
lam = min(1.0,0.05/abs(dx))
x +=lam*dx
if abs(dx)<e:
return (x,True)
return (x,False)
# Multiple streamtube models
def MST(TSR,sig,method,pitch,RE,tabAOA,tabRE,tabCL,tabCD):
# number of azimuthal positions
Ntheta = 80
thetav = (np.arange(0,pi,pi/(Ntheta+1))+pi/(2*Ntheta))[0:-1]
thvec = np.r_[thetav,thetav+pi]*180/pi
# result vectors
lamvec = thvec.copy()
Tvec = lamvec.copy()
Nvec = lamvec.copy()
aoavec = lamvec.copy()
lam1 = 0.5
lam2 = 0.5
lam0 = 1.0
# Shorthand for current streamtube force
def fst(lam,theta): return ft_aero(lam,TSR,theta,sig,pitch,RE,tabAOA,tabRE,tabCL,tabCD)[0]
# Go over azimuth angles
for k in range(len(thetav)):
theta = thetav[k]
st = sin(theta)
ct = cos(theta)
# Constrain multiplier at edges
stm = max(abs(st),sin(1*pi/180))
if method == 'DMST':
# Upwind
def resf(x): return f_momentum(x)*stm*pi - fst(x,theta)
(x,success) = simpleNewton(resf,lam1,100)
if not success:
(x,success) = simpleNewton(resf,1.0,50)
lam1 = x
# Downwind
veq = 2*lam1-1
def resf(x): return f_momentum(x)*stm*pi*veq**2 - fst(veq*x,-theta)
(x,success) = simpleNewton(resf,lam2,50)
if not success:
(x,success) = simpleNewton(resf,1.0,100)
lam2 = x*veq
# If either below 0.5, set to invalid
if lam1<0.5 or lam2/veq<0.5:
success = False
elif method == "TMST":
# Upwind/Downwind velocity based on mid velocity
w = 2/3
def flam1(lam0): return (1-w)+lam0*w
def flam2(lam0): return lam0*w + (1-w)*(2*lam0-1)
def resf(x): return f_momentum(x)*stm*pi - fst(flam1(x),theta) - fst(flam2(x),-theta)
(x, success) = simpleNewton(resf,lam0,50)
if not success:
(x, success) = simpleNewton(resf,1.0,100)
lam0 = x
if lam0<0.5:
success = False
lam1 = flam1(lam0)
lam2 = flam2(lam0)
else:
raise NameError('Invalid Method')
lamvec[-k-1] = lam2
lamvec[k] = lam1
# Calculate current forces and put into solution vector
(Fx1,Tvec[k], Nvec[k],aoavec[k]) = ft_aero(lam1,TSR,theta,sig,pitch,RE,tabAOA,tabRE,tabCL,tabCD)
(Fx2,Tvec[-k-1],Nvec[-k-1],aoavec[-k-1]) = ft_aero(lam2,TSR,-theta,sig,pitch,RE,tabAOA,tabRE,tabCL,tabCD)
if not success:
Tvec[k] = 0; Tvec[-k-1] = 0
Nvec[k] = 0; Nvec[-k-1] = 0
return (thvec,Tvec,Nvec,aoavec,lamvec)
# Comparison with Ferreira data.
matplotlib.rcParams['figure.figsize'] = [11, 10]
fig, ax = plt.subplots(2,2)
cmap = plt.get_cmap("tab10")
# Load and plot digitized dataset
ds = "Ferreira2014.csv"
labels = ['Actuator Disk','U2DiVA', 'CACTUS']
for k in range(3):
aSet013 = np.genfromtxt(ds,skip_header=3,delimiter=",",usecols=[0*12+2*k+0,0*12+2*k+1])
aSet010 = np.genfromtxt(ds,skip_header=3,delimiter=",",usecols=[2*12+2*k,2*12+2*k+1])
aoaSet013 = np.genfromtxt(ds,skip_header=3,delimiter=",",usecols=[0*12+6+2*k,0*12+6+2*k+1])
aoaSet010 = np.genfromtxt(ds,skip_header=3,delimiter=",",usecols=[2*12+6+2*k,2*12+6+2*k+1])
ax[0][0].plot(aSet013.T[0],aSet013.T[1],'--',color=cmap(2+k),label=labels[k])
ax[0][0].plot(aSet010.T[0],aSet010.T[1],'--',color=cmap(2+k))
ax[0][1].plot(aoaSet013.T[0],aoaSet013.T[1],'--',color=cmap(2+k))
ax[0][1].plot(aoaSet010.T[0],aoaSet010.T[1],'--',color=cmap(2+k))
aSet014 = np.genfromtxt(ds,skip_header=3,delimiter=",",usecols=[1*12+2*k,1*12+2*k+1])
aoaSet014 = np.genfromtxt(ds,skip_header=3,delimiter=",",usecols=[1*12+6+2*k,1*12+6+2*k+1])
ax[1][0].plot(aSet014.T[0],aSet014.T[1],'--',color=cmap(2+k))
ax[1][1].plot(aoaSet014.T[0],aoaSet014.T[1],'--',color=cmap(2+k))
# Calculate and plot DMST and TMST results
[tabAOA,tabRE,tabCL,tabCD] = CLCDTAB()
#print(tabAOA)
# 1. sigma=0.1 , pitch 0 or 3
TSR = 4.5
sig = 0.1
RE = 0.0 # Not relevant here
for pitch in [0,3]:
k=0
for method in ["DMST","TMST"]:
[thvec,Tvec,Nvec,aoavec,lamvec] = MST(TSR,sig,method,pitch,RE,tabAOA,tabRE,tabCL,tabCD)
lamvec
ax[0][0].plot(thvec,1-lamvec,'-',color=cmap(k), label = '%s %u°'%(method,pitch))
ax[0][1].plot(thvec,aoavec,'-',color=cmap(k))
k+=1
ax[0][0].set_title('Induction Factor, Solidity = 0.1, Pitch 0° and 3°')
ax[0][1].set_title('AOA, Solidity = 0.1, Pitch 0° and 3°')
# 2. sigma=0.14 , pitch 0
sig = 0.14
k=0
for method in ["DMST","TMST"]:
[thvec,Tvec,Nvec,aoavec,lamvec] = MST(TSR,sig,method,0,RE,tabAOA,tabRE,tabCL,tabCD)
ax[1][0].plot(thvec,1-lamvec,'-',color=cmap(k))
ax[1][1].plot(thvec,aoavec,'-',color=cmap(k))
k+=1
ax[1][0].set_title('Induction Factor, Solidity = 0.14')
ax[1][1].set_title('AOA, Solidity = 0.14')
# Grids on
for k in range(2):
for j in range(2):
ax[k][j].grid(True)
ax[0,0].legend()
```
## Part B: The effect of curvature
For the following comparison we will replace the simplistic aerodynamic model above with airfoil polars calculated with and without curvature and compare the torque and power coefficients.
To analyze the effect of high c/R ratios, experimental data with a high c/R turbine is needed.
In [5] a VAWT has been measured that has ratio of 0.4/1.25:
- Diameter: 2.5 m
- Chord length: 0.4 m
- Number of blades: 3
- Height: 3 m
- TSR: 0.3-2.2
- Wind speed: 6-16 m/s
- Airfoil: NACA0015
The most data points are available for 10 m/s and are used below.
This leads to a Reynolds Number variation of TSR $\times$ 281000.
Locally, a blade will see varying airspeed depending on the induction factor, but the calculation below disregards this variation and uses the Reynolds Number solely based on Tips-Speed ratio.
### Extrapolation and Corrections
The polars may need to be evaluated beyond the range of calculated angles of attack.
In this case the polars are commonly extrapolated by using the Viterna extrapolation[4].
The blades have a very low aspect ratio due to their high chord length.
In the context of streamtube models, e.g. by dividing the height into several streamtubes, the aerodynamic effect of this low aspect ratio is not incorporated.
Instead, we use the formulas for low aspect ratio wings to correct our blade lift and drag.
#### Drag
The induced drag of a low aspect ratio wings is given by
$$ CD_i = \frac{CL^2}{e \pi AR}.$$
The factor $e$ is the Oswald efficiency factor.
#### Lift
The lift of a rectangular wing with linear sectional lift slope is given by
$$ CL(\alpha) = 2\pi\frac{\alpha}{1+2/AR}.$$
To evaluate a rectangular wing with the airfoil characteristics calculated above one may use therefore a change in angle of attack by
$$\alpha_{AR} = \frac{(\alpha-\alpha_0)}{1+2/AR}+\alpha_0$$
using the zero-lift angle of attack $\alpha_0$ of the airfoil.
This does not capture the change in maximum lift, which should be reduced.
Below, the function is defined that interpolates from the set of polars of different Reynolds Numbers the current lift and drag and corrects the values based on the Viterna extrapolation and on the aspect ratio correction.
```
# Turbine Parameters
c = 0.4
R = 1.25
AR = 3/0.4
# For tip speed ratios of .3 to 3 at a windspeed of 10
RE1 = 281000
# Aerodynamic Analysis of NACA0015
# Load airfoil data
#airfoil = vft.repanel_spline(vft.read_selig("NACA0015.dat"),180)
airfoil = vft.repanel(vft.read_selig("NACA0015.dat"),180)
# Shift to rotate about center
airfoil[0,:]-=.5
# Put resultss in here
polar=[]
polarRot=[]
AOArange = np.arange(0,18,.5)
# Shorthand for a single evaluation
def eval_airfoil(s):
alv = []
clv = []
cdv = []
for direction in [1,-1]:
init = True
for alpha in AOArange[1::]:
s.Alpha = direction*alpha
if init:
(p,bl,x) = vf.init(airfoil,s)
init=False
[x,flag,_,_,_] = vf.iter(x,bl,p,s)
if flag:
abortcount = 0
# Insert at end or at beginning
if direction == 1:pos = len(alv)
else: pos = 0
alv.insert(pos,direction*alpha)
clv.insert(pos,p.CL)
cdv.insert(pos,bl[0].CD)
#print("Adding CL=%f,CD=%f,AOA=%f"%(p.CL,bl[0].CD,s.Alpha))
else:
abortcount+=1
init=True
if abortcount>3:
break
# Find zero lift angle of attack
(alpha0,success) = simpleNewton(lambda aoa: np.interp(aoa,np.array(alv),np.array(clv)),0,2000)
return {'AOA':np.asarray(alv), 'CL':np.array(clv), 'CD':np.asarray(cdv), 'RE':RE, 'A0': alpha0}
for RE in RE1*np.asarray([0.3, 0.5, 1, 2, 3]):
s = vf.setup(Re=RE,Ma=0.0,Ncrit=9,Alpha=AOArange[0],Itermax=100,Silent=True,PitchRate = 0)
# Analyse without rotation
polar.append(eval_airfoil(s))
# Analyse with rotation
s.PitchRate = c/R;
#print("Now with Rotation")
polarRot.append(eval_airfoil(s))
# Aspect ratio efficiency
oswald = 0.85
AR = 3/0.4
#@njit(f8(f8,f8,f8))
def ARCorrection(alpha,AOA0,AR):
return (alpha-AOA0)/(1+2/AR)+AOA0
#@njit(nb.types.Tuple((f8, f8))(f8,f8[:],f8[:],f8[:]))
def interpPolar(AOA,AOAVEC,CLVEC,CDVEC):
N = len(AOAVEC)
k1 = N-1
for k in range(N):
if AOAVEC[k]>=AOA: k1=k;break
k0 = 0
for k in range(N):
if AOAVEC[N-k-1]<=AOA: k0=N-k-1;break
if k0 == k1:
a = 1
else:
a = (AOA-AOAVEC[k0])/(AOAVEC[k1]-AOAVEC[k0])
CL = CLVEC[k0]*(1-a) + CLVEC[k1]*a
CD = CDVEC[k0]*(1-a) + CDVEC[k1]*a
return (CL,CD)
#@njit(nb.types.Tuple((f8, f8))(f8,f8[:],f8[:],f8[:],f8))
def CLCDPOL(al,AOAVEC,CLVEC,CDVEC,AOA0):
al *= pi/180
alpha = (np.mod(al+pi,2*pi)-pi)
# AR correction
alpha = ARCorrection(alpha*180/pi,AOA0,AR)/180*pi
if alpha < 0:
astall = AOAVEC[0]/180*pi
else:
astall = AOAVEC[-1]/180*pi
sgnCL = 1;
if (alpha >= 0 and alpha<astall) or (alpha<0 and alpha>astall):
alphaeval = alpha*180/pi
(CL,CD) = interpPolar(alphaeval,AOAVEC,CLVEC,CDVEC)
else:
# Viterna Extrapolation
if alpha>pi/2:
alpha = pi/2-(alpha-pi/2)
astall = 0
sgnCL = -1;
if alpha<-pi/2:
alpha = -pi/2-(alpha+pi/2)
astall = 0
sgnCL = -1;
CDmax = 1.11+0.018*AR
# Aspect ratio correction
(CLstall,CDstall) = interpPolar(astall*180/pi,AOAVEC,CLVEC,CDVEC)
sas = sin(astall); cas = cos(astall)
sa = sin(alpha); ca = cos(alpha)
A1 = CDmax/2.0; B1 = CDmax
A2 = (CLstall-CDmax*sas*cas)/cas**2*sas
B2 = (CDstall-CDmax*sas**2)/cas
CL = A1*2*ca*sa+A2*ca**2/sa
CD = B1*sa**2+B2*ca
return (sgnCL*CL,CD+1*CL**2/np.pi/AR/oswald)
# Put into tables
numRE = len(polar)
tabAOA = np.arange(-180,180,0.5)
numAOA = len(tabAOA)
tabRE = np.zeros(numRE)
tabCL = np.zeros((numAOA,numRE))
tabCD = tabCL.copy()
tabCLRot = tabCL.copy()
tabCDRot = tabCL.copy()
for kRE in range(numRE):
tabRE[kRE] = polar[kRE]["RE"]
for kAOA in range(numAOA):
(tabCL[kAOA,kRE],tabCD[kAOA,kRE]) = CLCDPOL(tabAOA[kAOA],polar[kRE]['AOA'],polar[kRE]['CL'],polar[kRE]['CD'],polar[kRE]['A0'])
(tabCLRot[kAOA,kRE],tabCDRot[kAOA,kRE]) = CLCDPOL(tabAOA[kAOA],polarRot[kRE]['AOA'],polarRot[kRE]['CL'],polarRot[kRE]['CD'],polarRot[kRE]['A0'])
matplotlib.rcParams['figure.figsize'] = [11, 8]
fig, ax = plt.subplots(1,2)
# Plot an extrapolated polar vs the pure airfoil one for maximum RE
ax[0].plot(tabAOA,tabCL[:,-1],label="Blade CL")
ax[0].plot(polar[-1]["AOA"],polar[-1]["CL"],label="Airfoil CL")
ax[0].plot(tabAOA,tabCD[:,-1],label="Blade CD")
ax[0].plot(polar[-1]["AOA"],polar[-1]["CD"],label="Airfoil CD")
ax[0].plot(tabAOA,tabCLRot[:,-1],label="Rot. Blade CL")
ax[0].plot(polarRot[-1]["AOA"],polarRot[-1]["CL"],label="Rot. Airfoil CL")
ax[0].plot(tabAOA,tabCDRot[:,-1],label="Rot. Blade CD")
ax[0].plot(polarRot[-1]["AOA"],polarRot[-1]["CD"],label="Rot. Airfoil CD")
ax[0].set_xlim(-25,25)
ax[0].set_ylim(-1.75,1.75)
# Plot all airfoil polars
for pol in polarRot:
ax[1].plot(pol['CD'],pol['CL'],label='ROT RE %u'%pol['RE'])
for pol in polar:
ax[1].plot(pol['CD'],pol['CL'],'--',label='RE %u'%pol['RE'])
for k in range(2):
ax[k].legend()
ax[k].grid(1)
ax[1].set_xlabel('CD')
ax[1].set_ylabel('CL')
ax[1].set_xlim(0,0.2);
ax[1].set_ylim(-1.75,1.75)
```
## Comparison with Experimental Data
The data in [5] is used to compare the power coefficient as calculated using the DMST and TMST with and without pitching airfoils.
Both methods capture the partial load regime between TSR=1 and TSR=1.5 equally good, with a better correlation when using the airfoil data of a pitching airfoil.
The peak power coefficient is overpredicted by both, while the optimal TSR agrees with the experiment.
Looking at the local lift coefficients at this TSR, one **might** argue that this is is explained by the not modeled loss in maximum lift due to the high aspect ratio.
However, there are a number of other reasons that might be:
- Multiple streamtube models do not work well with high solidities
- The not modeled effects in streamtube models discussed above
- If for parts of the azimuth angle there exists no viable solution (and the tangential force is set to 0), one might question the result of the rest of the azimuth angles
At very low TSR, the airfoils exhibit huge angles of attack, and the result depends strongly on the extrapolation method which might underpredict the drag at low Reynolds numbers.
At these extreme angles of attack at low Reynolds numbers the blades operate beyond stall and a streamtube approach is probably not going to model the operation of the VAWT.
Beyond partial load above TSR=1.5 the DMST behaves similar to TMST with non-pitching airfoils, but predicts further increase in $c_p$ if using the pitching airfoil data.
While the effect of pitching does not have a significant effect on optimal TSR or $c_p$ using the streamtube models, it does have an effect on the tangential and normal loads.
When using the DMST model, it seems to be necessary to shift the airfoil polar to $\alpha=0$ at $CL=0$.
```
matplotlib.rcParams['figure.figsize'] = [11, 18]
TSRrange = np.r_[np.arange(0.3,3,0.05)]
CP = TSRrange.copy()
CT = TSRrange.copy()
fig, ax = plt.subplots(3,2)
# Solidity
sig = 3*c/R/2
for Rot in [False,True]:
if Rot:
mark = '-'
exlegend = ' w/ Curvature'
else:
mark = ':'
exlegend = ''
kMethod = 0
for mode in ["DMST","TMST"]:
for k in range(len(TSRrange)):
TSR = TSRrange[k]
RE = TSR*RE1 # Reynolds Number
if Rot:
[thvec,Tvec,Nvec,aoavec,lamvec] = MST(TSR,sig,mode,0,RE,tabAOA,tabRE,tabCLRot,tabCDRot)
else:
[thvec,Tvec,Nvec,aoavec,lamvec] = MST(TSR,sig,mode,0,RE,tabAOA,tabRE,tabCL,tabCD)
(CP[k],CT[k]) = CoefVAWT(Tvec,TSR)
# Print specific TSR
axk = -1
if abs(TSR-0.8)<0.01:
axk = 1
if abs(TSR-1.6)<0.01:
axk = 2
if axk>0:
ax[axk][0].plot(thvec,Tvec,mark,color=cmap(kMethod))
CL = thvec.copy()
for k in range(len(thvec)):
if Rot:
(CL[k],CD) = CLCD(aoavec[k],RE,tabAOA,tabRE,tabCLRot,tabCDRot)
else:
(CL[k],CD) = CLCD(aoavec[k],RE,tabAOA,tabRE,tabCL,tabCD)
ax[axk][1].plot(thvec,CL,mark,color=cmap(kMethod))
ax[0][0].plot(TSRrange,CP,mark,color=cmap(kMethod),label="%s%s"%(mode,exlegend))
ax[0][1].plot(TSRrange,CT,mark,color=cmap(kMethod))
kMethod+=1
ax[0][0].set_xlabel('TSR')
ax[0][0].set_ylabel('CP')
ax[0][1].set_xlabel('TSR')
ax[0][1].set_ylabel('CT')
for j in range(2):
for k in range(2):
ax[j+1][k].set_xlabel('Azimuth')
ax[1][0].set_ylabel('FT, TSR = 0.8')
ax[2][0].set_ylabel('FT, TSR = 1.6')
ax[1][1].set_ylabel('local CL, TSR = 0.8')
ax[2][1].set_ylabel('local CL, TSR = 1.6')
for k in range(3):
for j in range(2):
ax[k][j].grid(True)
ax[0][0].set_ylim(0,0.5)
ax[0][1].set_ylim(0,None)
# Plot digitzed cp data
ds = "HCR.csv"
HCR = np.genfromtxt(ds,skip_header=1,delimiter=",",usecols=[0,1])
ax[0][0].plot(HCR.T[0],HCR.T[1],'-o',label="Experimental Data")
ax[0][0].legend()
```
[1] Paraschivoiu, Ion, and Francois Delclaux. "Double multiple streamtube model with recent improvements (for predicting aerodynamic loads and performance of Darrieus vertical axis wind turbines)." Journal of energy 7.3 (1983): 250-255.
[2] Ferreira, C. Simão, et al. "Comparison of aerodynamic models for vertical axis wind turbines." Journal of Physics: Conference Series. Vol. 524. No. 1. IOP Publishing, 2014.
[3] Saber, E., R. Afify, and H. Elgamal. "Performance of SB-VAWT using a modified double multiple streamtube model." Alexandria engineering journal 57.4 (2018): 3099-3110.
[4] Viterna, Larry A., and David C. Janetzke. Theoretical and experimental power from large horizontal-axis wind turbines. No. DOE/NASA/20320-41; NASA-TM-82944. National Aeronautics and Space Administration, Cleveland, OH (USA). Lewis Research Center, 1982.
[5] Bravo, R., S. Tullis, and S. Ziada. "Performance testing of a small vertical-axis wind turbine." Proceedings of the 21st Canadian Congress of Applied Mechanics (CANCAM07), Toronto, Canada, June. 2007.
| github_jupyter |
```
```
# author Giovambattista Vieri
# (c) 2020 all rights reserverd
# license: GPL V 2.0
#
```
!pip install numpy
!pip install beautifultable
!pip install matplotlib
!pip install GitPython
from git import Repo
from os import listdir
import csv
import os
import sys
import shutil
import argparse
import numpy as np
from beautifultable import BeautifulTable
from pandas.plotting import register_matplotlib_converters
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
import bottleneck as bn
from matplotlib.ticker import MaxNLocator
from IPython.display import Javascript
display(Javascript("google.colab.output.resizeIframeToContent()"))
from datetime import datetime
register_matplotlib_converters()
destdir="covid19"
searchdir=destdir+"/csse_covid_19_data/csse_covid_19_daily_reports"
precconfirmed=precrecovered=precdeath=0
def firstfilelayout(row):
# it will receive a row in argument: with first line (header) skipped.
confirmed=deaths=recovered=0
if len(row[3])<1: row[3]=0
if len(row[4])<1: row[4]=0
if len(row[5])<1: row[5]=0
confirmed +=int(float(row[3]))
deaths +=int(float(row[4]))
recovered +=int(float(row[5]))
return(confirmed,deaths,recovered)
def secondfilelayout(row):
# it will receive a row in argument: with first line (header) skipped.
confirmed=deaths=recovered=0
if len(row[7])<1: row[7]=0
if len(row[8])<1: row[8]=0
if len(row[9])<1: row[9]=0
confirmed +=int(float(row[7]))
deaths +=int(float(row[8]))
recovered +=int(float(row[9]))
return(confirmed,deaths,recovered)
def processafile(filename):
completefile=searchdir+"/"+filename
confirmed=deaths=recovered=0
with open(completefile,'r') as fi:
reader=csv.reader(fi)
headers=next(reader)
for row in reader:
if 'FIPS' in headers[0]:
res=secondfilelayout(row)
else:
res=firstfilelayout(row)
confirmed +=int(float(res[0]))
deaths +=int(float(res[1]))
recovered +=int(float(res[2]))
return(confirmed,deaths,recovered)
ratio =True
save =False
chart =True
grid =True
nicetable =True
win =5
logyscale =False
if os.path.isdir(destdir):
shutil.rmtree(destdir)
os.mkdir(destdir)
Repo.clone_from("https://github.com/CSSEGISandData/COVID-19",destdir)
ext='csv'
filenames=listdir(searchdir)
filenames.remove('README.md')
filenames.remove('.gitignore')
filenames.sort(key = lambda date: datetime.strptime(date[:-4],'%m-%d-%Y'))
orig_stdout=sys.stdout
if nicetable:
table=BeautifulTable(max_width=132)
if ratio:
header=["date","Confirmed","Death","Recovered","d Confirmed","d Death","d Recovered","Death/Conf", "Recovered/Conf"]
else:
header=["date","Confirmed","Death","Recovered","d Confirmed","d Death","d Recovered"]
table.column_headers=header
if save:
fo=open('out.csv','w')
sys.stdout=fo
content=[]
for filename in filenames:
if filename.endswith(ext):
r=list(processafile(filename) )
tablerow=[]
deltaconfirmed=r[0]-precconfirmed
deltadeath =r[1]-precdeath
deltarecovered=r[2]-precrecovered
precconfirmed =r[0]
precdeath =r[1]
precrecovered =r[2]
if r[1] >0:
r.append(float(r[1]/r[0]))
else:
r.append('NaN')
if r[2] >0:
r.append(float(r[2]/r[0]))
else:
r.append('NaN')
if nicetable:
if ratio:
tablerow=[filename[:-4],r[0],r[1],r[2],deltaconfirmed,deltadeath,deltarecovered,r[3],r[4]]
else:
tablerow=[filename[:-4],r[0],r[1],r[2],deltaconfirmed,deltadeath,deltarecovered]
table.append_row(tablerow)
else:
if ratio:
print("{},{},{},{},{},{},{:.3f},{:.3f}".format(filename[:-4],r[0],r[1],r[2],deltaconfirmed,deltadeath,deltarecovered,r[3],r[4]) )
else:
print("{},{},{},{},{},{}".format(filename[:-4],r[0],r[1],r[2],deltaconfirmed,deltadeath,deltarecovered) )
content.append([filename[:-4],r[0],r[1],r[2],deltaconfirmed,deltadeath,deltarecovered])
if nicetable:
print(table)
if save:
sys.stdout=orig_stdout
fo.close()
if chart:
# plt.gca().xaxis_date()
dummy=np.array(content)
d=dummy[:,0]
days=[dt.datetime.strptime(d,'%m-%d-%Y').date() for d in d]
datefile=dt.datetime.today().strftime('%Y%m%d')
###### make chart of confirmed
plt.figure()
plt.ylabel('Confirmed')
plt.title('Confirmed')
confirmed=np.array(dummy[:,1],dtype=int)
if logyscale:
plt.yscale('log')
plt.plot(days,confirmed,'r')
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
plt.gca().xaxis.set_major_locator( MaxNLocator(nbins = 10) )
plt.gca().yaxis.set_major_locator( MaxNLocator(nbins = 10) )
plt.gcf().autofmt_xdate()
if grid:
plt.grid()
plt.savefig('Confirmed'+datefile)
plt.show()
###### make chart of Deaths
death=np.array(dummy[:,2],dtype=int)
plt.figure()
plt.ylabel('Death')
plt.title('Death')
if logyscale:
plt.yscale('log')
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
plt.plot(days,death,'black')
plt.gca().xaxis.set_major_locator( MaxNLocator(nbins = 10) )
plt.gca().yaxis.set_major_locator( MaxNLocator(nbins = 10) )
plt.gcf().autofmt_xdate()
if grid:
plt.grid()
plt.savefig('Death'+datefile)
# plt.show()
###### make chart of Recoverred
recovered=np.array(dummy[:,3],dtype=int)
plt.figure()
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
plt.ylabel('Recovered')
if logyscale:
plt.yscale('log')
plt.plot(days,recovered,'g')
plt.gca().xaxis.set_major_locator( MaxNLocator(nbins = 10) )
plt.gca().yaxis.set_major_locator( MaxNLocator(nbins = 10) )
if grid:
plt.grid()
plt.gcf().autofmt_xdate()
plt.savefig('Recovered'+datefile)
# plt.show()
###### make chart of both Confirmed and Recoverred
plt.figure()
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
plt.title('Recovered and Confirmed')
plt.ylabel('Recovered')
if logyscale:
plt.yscale('log')
plt.plot(days,confirmed,'r',label='Confirmed')
plt.plot(days,recovered,'g',label='Recovered')
plt.gca().xaxis.set_major_locator( MaxNLocator(nbins = 10) )
plt.gca().yaxis.set_major_locator( MaxNLocator(nbins = 10) )
plt.legend()
if grid:
plt.grid()
plt.gcf().autofmt_xdate()
plt.savefig('Recovered'+datefile)
# plt.show()
###### make chart of both delta Confirmed Death and Recoverred
dconfirmed=np.array(dummy[:,4],dtype=int)
ddeath =np.array(dummy[:,5],dtype=int)
drecovered=np.array(dummy[:,6],dtype=int)
plt.figure()
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
plt.title('delta Confirmed Recovered and Confirmed')
if logyscale:
plt.yscale('log')
plt.plot(days,dconfirmed,'r',label='delta Confirmed')
plt.plot(days,ddeath,'black',label='delta Death')
plt.plot(days,drecovered,'g',label='delta Recovered')
plt.gca().xaxis.set_major_locator( MaxNLocator(nbins = 10) )
plt.gca().yaxis.set_major_locator( MaxNLocator(nbins = 10) )
plt.legend()
if grid:
plt.grid()
plt.gcf().autofmt_xdate()
plt.savefig('dRecDeathConf'+datefile)
# plt.show()
######################################
mvadconfirmed = bn.move_mean(dconfirmed, window=win,min_count=1)
mvaddeath = bn.move_mean(ddeath, window=win,min_count=1)
mvadrecovered = bn.move_mean(drecovered, window=win,min_count=1)
plt.figure()
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
plt.title('mva delta Confirmed Recovered and Confirmed')
if logyscale:
plt.yscale('log')
plt.plot(days,mvadconfirmed,'r',label='delta Confirmed')
plt.plot(days,mvaddeath,'black',label='delta Death')
plt.plot(days,mvadrecovered,'g',label='delta Recovered')
plt.gca().xaxis.set_major_locator( MaxNLocator(nbins = 10) )
plt.gca().yaxis.set_major_locator( MaxNLocator(nbins = 10) )
plt.legend()
if grid:
plt.grid()
plt.gcf().autofmt_xdate()
plt.savefig('dRecDeathConf'+datefile)
######################################
plt.figure()
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
plt.title('both mva delta Confirmed Recovered and Confirmed')
if logyscale:
plt.yscale('log')
plt.plot(days,mvadconfirmed,'r',linestyle='-.',label='mva delta Confirmed')
plt.plot(days,mvaddeath,'black',linestyle='-.',label='mva delta Death')
plt.plot(days,mvadrecovered,'g',linestyle='-.',label='mva delta Recovered')
plt.plot(days,dconfirmed,'r',label='dConfirmed')
plt.plot(days,ddeath,'black',label='dDeath')
plt.plot(days,drecovered,'g',label='dRecovered')
plt.gca().xaxis.set_major_locator( MaxNLocator(nbins = 10) )
plt.gca().yaxis.set_major_locator( MaxNLocator(nbins = 10) )
plt.legend()
if grid:
plt.grid()
plt.gcf().autofmt_xdate()
plt.savefig('mixmvadRecDeathConf'+datefile)
```
| github_jupyter |
# Damped Lyman Alpha absorber system towards a QSO
Figure 9.7 from Chapter 9 of *Interstellar and Intergalactic Medium* by Ryden & Pogge, 2021,
Cambridge University Press.
Plot spectrum of the damped Lyman $\alpha$ absorption (DLA) line from a cloud along the line of sight towards
QSO J021741.8-370100 ($z_{em}$=2.910). Data are from the ESO UVES spectrograph obtained from the
[ESO Science Archive Facility](http://archive.eso.org). The DLA of the QSO has a
redshift of $z_{abs}$=2.429 and a column density of $\log_{10} N_{HI}=$20.62$\pm$0.08.
The QSO was first identified as a DLA system by [Maza, J., Wischnjewsky, M., & Antezana, R. 1996, Rev. Mex. Astron. Astrophys., 32, 35](https://ui.adsabs.harvard.edu/abs/1996RMxAA..32...35M), and the column
density of the DLA was measured by
[Zafar et al., 2013, A&A 556, A140](https://ui.adsabs.harvard.edu/abs/2013A%26A...556A.140Z).
Data were selected and extracted from the ESO UVES database by Dr. Stephan Frank, who normalized the spectrum
in the region of interest and computed the damped Ly$\alpha$ absorption profile corresponding to the published
column density. These data are provided in an external file associated with this notebook.
```
%matplotlib inline
import math
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, LogLocator, NullFormatter
# for smoothing the UVES spectrum
from astropy.convolution import convolve, Box1DKernel
# suppress nuisance warnings
import warnings
warnings.filterwarnings('ignore',category=UserWarning, append=True)
warnings.filterwarnings('ignore',category=RuntimeWarning, append=True)
```
## Standard Plot Format
Setup the standard plotting format and make the plot. Fonts and resolution adopted follow CUP style.
```
figName = 'Fig9_7'
# graphic aspect ratio = width/height
aspect = 2.5
# Text width in inches - don't change, this is defined by the print layout
textWidth = 6.0 # inches
# output format and resolution
figFmt = 'png'
dpi = 600
# Graphic dimensions
plotWidth = dpi*textWidth
plotHeight = plotWidth/aspect
axisFontSize = 10
labelFontSize = 6
lwidth = 0.5
axisPad = 5
wInches = textWidth
hInches = wInches/aspect
# Plot filename
plotFile = f'{figName}.{figFmt}'
# LaTeX is used throughout for markup of symbols, Times-Roman serif font
plt.rc('text', usetex=True)
plt.rc('font', **{'family':'serif','serif':['Times-Roman'],'weight':'bold','size':'16'})
# Font and line weight defaults for axes
matplotlib.rc('axes',linewidth=lwidth)
matplotlib.rcParams.update({'font.size':axisFontSize})
# axis and label padding
plt.rcParams['xtick.major.pad'] = f'{axisPad}'
plt.rcParams['ytick.major.pad'] = f'{axisPad}'
plt.rcParams['axes.labelpad'] = f'{axisPad}'
```
## Spectral Data
Data are in a 3-column format, wavelength, relative flux units (F$_\lambda$), and flux error:
* wave - wavelength in Angstroms, observed frame
* flux_norm - continuum-normalized flux
* model - absorption line model for the DLA
The redshift of the DLA is z_abs=2.429, which we use to transform the observed wavelenghts into rest wavelength.
```
dataFile='J021741.8-370100_norm.txt'
z_abs = 2.429
data = pd.read_csv(dataFile,sep=r'\s+',comment='#')
lam = np.array(data['wave'])/(1+z_abs)
flux = np.array(data['flux_norm'])
fDLA = np.array(data['model'])
# Smooth the spectrum with a boxcar (running mean) of width 7 pixels
width = 7
smFlux = convolve(flux, Box1DKernel(width))
# Plotting Limits
xMin = 1200
xMax = 1232
yMin = -0.05 # normalized flux
yMax = 1.15
```
## Make the Plot
Spectrum as a solid black step plot, damped Ly$\alpha$ absorption line model as a dashed black line.
```
fig,ax = plt.subplots()
fig.set_dpi(dpi)
fig.set_size_inches(wInches,hInches,forward=True)
ax.set_xlim(xMin,xMax)
ax.set_ylim(yMin,yMax)
ax.tick_params('both',length=6,width=lwidth,which='major',direction='in',top='on',right='on')
ax.tick_params('both',length=3,width=lwidth,which='minor',direction='in',top='on',right='on')
ax.xaxis.set_major_locator(MultipleLocator(5.))
ax.xaxis.set_minor_locator(MultipleLocator(1.))
plt.xlabel(r'Wavelength [\AA]')
ax.yaxis.set_major_locator(MultipleLocator(0.2))
ax.yaxis.set_minor_locator(MultipleLocator(0.05))
plt.ylabel(r'Relative flux', fontsize=axisFontSize)
plt.plot(lam,smFlux,'-',ds='steps-mid',color='black',lw=0.5,zorder=10)
# Model DLA profile plus continuum (1) and zero flux (0) lines
plt.plot(lam,fDLA,'-',color='black',lw=1.0,zorder=8)
plt.hlines([0.0,1.0],xMin,xMax,ls=':',color='black',lw=0.5,zorder=5)
# make the plot
plt.plot()
plt.savefig(plotFile,bbox_inches='tight',facecolor='white')
```
| github_jupyter |
# Neural networks with PyTorch
Deep learning networks tend to be massive with dozens or hundreds of layers, that's where the term "deep" comes from. You can build one of these deep networks using only weight matrices as we did in the previous notebook, but in general it's very cumbersome and difficult to implement. PyTorch has a nice module `nn` that provides a nice way to efficiently build large neural networks.
```
# Import necessary packages
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import torch
import helper
import matplotlib.pyplot as plt
```
Now we're going to build a larger network that can solve a (formerly) difficult problem, identifying text in an image. Here we'll use the MNIST dataset which consists of greyscale handwritten digits. Each image is 28x28 pixels, you can see a sample below
<img src='assets/mnist.png'>
Our goal is to build a neural network that can take one of these images and predict the digit in the image.
First up, we need to get our dataset. This is provided through the `torchvision` package. The code below will download the MNIST dataset, then create training and test datasets for us. Don't worry too much about the details here, you'll learn more about this later.
```
### Run this cell
from torchvision import datasets, transforms
# Define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,)),
])
# Download and load the training data
trainset = datasets.MNIST('~/.pytorch/MNIST_data/', download=True, train=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)
```
We have the training data loaded into `trainloader` and we make that an iterator with `iter(trainloader)`. Later, we'll use this to loop through the dataset for training, like
```python
for image, label in trainloader:
## do things with images and labels
```
You'll notice I created the `trainloader` with a batch size of 64, and `shuffle=True`. The batch size is the number of images we get in one iteration from the data loader and pass through our network, often called a *batch*. And `shuffle=True` tells it to shuffle the dataset every time we start going through the data loader again. But here I'm just grabbing the first batch so we can check out the data. We can see below that `images` is just a tensor with size `(64, 1, 28, 28)`. So, 64 images per batch, 1 color channel, and 28x28 images.
```
dataiter = iter(trainloader)
images, labels = dataiter.next()
print(type(images))
print(images.shape)
print(labels.shape)
```
This is what one of the images looks like.
```
plt.imshow(images[1].numpy().squeeze(), cmap='Greys_r');
```
First, let's try to build a simple network for this dataset using weight matrices and matrix multiplications. Then, we'll see how to do it using PyTorch's `nn` module which provides a much more convenient and powerful method for defining network architectures.
The networks you've seen so far are called *fully-connected* or *dense* networks. Each unit in one layer is connected to each unit in the next layer. In fully-connected networks, the input to each layer must be a one-dimensional vector (which can be stacked into a 2D tensor as a batch of multiple examples). However, our images are 28x28 2D tensors, so we need to convert them into 1D vectors. Thinking about sizes, we need to convert the batch of images with shape `(64, 1, 28, 28)` to a have a shape of `(64, 784)`, 784 is 28 times 28. This is typically called *flattening*, we flattened the 2D images into 1D vectors.
Previously you built a network with one output unit. Here we need 10 output units, one for each digit. We want our network to predict the digit shown in an image, so what we'll do is calculate probabilities that the image is of any one digit or class. This ends up being a discrete probability distribution over the classes (digits) that tells us the most likely class for the image. That means we need 10 output units for the 10 classes (digits). We'll see how to convert the network output into a probability distribution next.
> **Exercise:** Flatten the batch of images `images`. Then build a multi-layer network with 784 input units, 256 hidden units, and 10 output units using random tensors for the weights and biases. For now, use a sigmoid activation for the hidden layer. Leave the output layer without an activation, we'll add one that gives us a probability distribution next.
```
## Solution
def activation(x):
return 1/(1+torch.exp(-x))
# Flatten the input images
inputs = images.view(images.shape[0], -1)
# Create parameters
w1 = torch.randn(784, 256)
b1 = torch.randn(256)
w2 = torch.randn(256, 10)
b2 = torch.randn(10)
h = activation(torch.mm(inputs, w1) + b1)
out = torch.mm(h, w2) + b2
```
Now we have 10 outputs for our network. We want to pass in an image to our network and get out a probability distribution over the classes that tells us the likely class(es) the image belongs to. Something that looks like this:
<img src='assets/image_distribution.png' width=500px>
Here we see that the probability for each class is roughly the same. This is representing an untrained network, it hasn't seen any data yet so it just returns a uniform distribution with equal probabilities for each class.
To calculate this probability distribution, we often use the [**softmax** function](https://en.wikipedia.org/wiki/Softmax_function). Mathematically this looks like
$$
\Large \sigma(x_i) = \cfrac{e^{x_i}}{\sum_k^K{e^{x_k}}}
$$
What this does is squish each input $x_i$ between 0 and 1 and normalizes the values to give you a proper probability distribution where the probabilites sum up to one.
> **Exercise:** Implement a function `softmax` that performs the softmax calculation and returns probability distributions for each example in the batch. Note that you'll need to pay attention to the shapes when doing this. If you have a tensor `a` with shape `(64, 10)` and a tensor `b` with shape `(64,)`, doing `a/b` will give you an error because PyTorch will try to do the division across the columns (called broadcasting) but you'll get a size mismatch. The way to think about this is for each of the 64 examples, you only want to divide by one value, the sum in the denominator. So you need `b` to have a shape of `(64, 1)`. This way PyTorch will divide the 10 values in each row of `a` by the one value in each row of `b`. Pay attention to how you take the sum as well. You'll need to define the `dim` keyword in `torch.sum`. Setting `dim=0` takes the sum across the rows while `dim=1` takes the sum across the columns.
```
## Solution
def softmax(x):
return torch.exp(x)/torch.sum(torch.exp(x), dim=1).view(-1, 1)
probabilities = softmax(out)
# Does it have the right shape? Should be (64, 10)
print(probabilities.shape)
# Does it sum to 1?
print(probabilities.sum(dim=1))
```
## Building networks with PyTorch
PyTorch provides a module `nn` that makes building networks much simpler. Here I'll show you how to build the same one as above with 784 inputs, 256 hidden units, 10 output units and a softmax output.
```
from torch import nn
class Network(nn.Module):
def __init__(self):
super().__init__()
# Inputs to hidden layer linear transformation
self.hidden = nn.Linear(784, 256)
# Output layer, 10 units - one for each digit
self.output = nn.Linear(256, 10)
# Define sigmoid activation and softmax output
self.sigmoid = nn.Sigmoid()
self.softmax = nn.Softmax(dim=1)
def forward(self, x):
# Pass the input tensor through each of our operations
x = self.hidden(x)
x = self.sigmoid(x)
x = self.output(x)
x = self.softmax(x)
return x
```
Let's go through this bit by bit.
```python
class Network(nn.Module):
```
Here we're inheriting from `nn.Module`. Combined with `super().__init__()` this creates a class that tracks the architecture and provides a lot of useful methods and attributes. It is mandatory to inherit from `nn.Module` when you're creating a class for your network. The name of the class itself can be anything.
```python
self.hidden = nn.Linear(784, 256)
```
This line creates a module for a linear transformation, $x\mathbf{W} + b$, with 784 inputs and 256 outputs and assigns it to `self.hidden`. The module automatically creates the weight and bias tensors which we'll use in the `forward` method. You can access the weight and bias tensors once the network once it's create at `net.hidden.weight` and `net.hidden.bias`.
```python
self.output = nn.Linear(256, 10)
```
Similarly, this creates another linear transformation with 256 inputs and 10 outputs.
```python
self.sigmoid = nn.Sigmoid()
self.softmax = nn.Softmax(dim=1)
```
Here I defined operations for the sigmoid activation and softmax output. Setting `dim=1` in `nn.Softmax(dim=1)` calculates softmax across the columns.
```python
def forward(self, x):
```
PyTorch networks created with `nn.Module` must have a `forward` method defined. It takes in a tensor `x` and passes it through the operations you defined in the `__init__` method.
```python
x = self.hidden(x)
x = self.sigmoid(x)
x = self.output(x)
x = self.softmax(x)
```
Here the input tensor `x` is passed through each operation a reassigned to `x`. We can see that the input tensor goes through the hidden layer, then a sigmoid function, then the output layer, and finally the softmax function. It doesn't matter what you name the variables here, as long as the inputs and outputs of the operations match the network architecture you want to build. The order in which you define things in the `__init__` method doesn't matter, but you'll need to sequence the operations correctly in the `forward` method.
Now we can create a `Network` object.
```
# Create the network and look at it's text representation
model = Network()
model
```
You can define the network somewhat more concisely and clearly using the `torch.nn.functional` module. This is the most common way you'll see networks defined as many operations are simple element-wise functions. We normally import this module as `F`, `import torch.nn.functional as F`.
```
import torch.nn.functional as F
class Network(nn.Module):
def __init__(self):
super().__init__()
# Inputs to hidden layer linear transformation
self.hidden = nn.Linear(784, 256)
# Output layer, 10 units - one for each digit
self.output = nn.Linear(256, 10)
def forward(self, x):
# Hidden layer with sigmoid activation
x = F.sigmoid(self.hidden(x))
# Output layer with softmax activation
x = F.softmax(self.output(x), dim=1)
return x
```
### Activation functions
So far we've only been looking at the softmax activation, but in general any function can be used as an activation function. The only requirement is that for a network to approximate a non-linear function, the activation functions must be non-linear. Here are a few more examples of common activation functions: Tanh (hyperbolic tangent), and ReLU (rectified linear unit).
<img src="assets/activation.png" width=700px>
In practice, the ReLU function is used almost exclusively as the activation function for hidden layers.
### Your Turn to Build a Network
<img src="assets/mlp_mnist.png" width=600px>
> **Exercise:** Create a network with 784 input units, a hidden layer with 128 units and a ReLU activation, then a hidden layer with 64 units and a ReLU activation, and finally an output layer with a softmax activation as shown above. You can use a ReLU activation with the `nn.ReLU` module or `F.relu` function.
```
## Solution
class Network(nn.Module):
def __init__(self):
super().__init__()
# Defining the layers, 128, 64, 10 units each
self.fc1 = nn.Linear(784, 128)
self.fc2 = nn.Linear(128, 64)
# Output layer, 10 units - one for each digit
self.fc3 = nn.Linear(64, 10)
def forward(self, x):
''' Forward pass through the network, returns the output logits '''
x = self.fc1(x)
x = F.relu(x)
x = self.fc2(x)
x = F.relu(x)
x = self.fc3(x)
x = F.softmax(x, dim=1)
return x
model = Network()
model
```
### Initializing weights and biases
The weights and such are automatically initialized for you, but it's possible to customize how they are initialized. The weights and biases are tensors attached to the layer you defined, you can get them with `model.fc1.weight` for instance.
```
print(model.fc1.weight)
print(model.fc1.bias)
```
For custom initialization, we want to modify these tensors in place. These are actually autograd *Variables*, so we need to get back the actual tensors with `model.fc1.weight.data`. Once we have the tensors, we can fill them with zeros (for biases) or random normal values.
```
# Set biases to all zeros
model.fc1.bias.data.fill_(0)
# sample from random normal with standard dev = 0.01
model.fc1.weight.data.normal_(std=0.01)
```
### Forward pass
Now that we have a network, let's see what happens when we pass in an image.
```
# Grab some data
dataiter = iter(trainloader)
images, labels = dataiter.next()
# Resize images into a 1D vector, new shape is (batch size, color channels, image pixels)
images.resize_(64, 1, 784)
# or images.resize_(images.shape[0], 1, 784) to automatically get batch size
# Forward pass through the network
img_idx = 0
ps = model.forward(images[img_idx,:])
img = images[img_idx]
helper.view_classify(img.view(1, 28, 28), ps)
```
As you can see above, our network has basically no idea what this digit is. It's because we haven't trained it yet, all the weights are random!
### Using `nn.Sequential`
PyTorch provides a convenient way to build networks like this where a tensor is passed sequentially through operations, `nn.Sequential` ([documentation](https://pytorch.org/docs/master/nn.html#torch.nn.Sequential)). Using this to build the equivalent network:
```
# Hyperparameters for our network
input_size = 784
hidden_sizes = [128, 64]
output_size = 10
# Build a feed-forward network
model = nn.Sequential(nn.Linear(input_size, hidden_sizes[0]),
nn.ReLU(),
nn.Linear(hidden_sizes[0], hidden_sizes[1]),
nn.ReLU(),
nn.Linear(hidden_sizes[1], output_size),
nn.Softmax(dim=1))
print(model)
# Forward pass through the network and display output
images, labels = next(iter(trainloader))
images.resize_(images.shape[0], 1, 784)
ps = model.forward(images[0,:])
helper.view_classify(images[0].view(1, 28, 28), ps)
```
The operations are availble by passing in the appropriate index. For example, if you want to get first Linear operation and look at the weights, you'd use `model[0]`.
```
print(model[0])
model[0].weight
```
You can also pass in an `OrderedDict` to name the individual layers and operations, instead of using incremental integers. Note that dictionary keys must be unique, so _each operation must have a different name_.
```
from collections import OrderedDict
model = nn.Sequential(OrderedDict([
('fc1', nn.Linear(input_size, hidden_sizes[0])),
('relu1', nn.ReLU()),
('fc2', nn.Linear(hidden_sizes[0], hidden_sizes[1])),
('relu2', nn.ReLU()),
('output', nn.Linear(hidden_sizes[1], output_size)),
('softmax', nn.Softmax(dim=1))]))
model
```
Now you can access layers either by integer or the name
```
print(model[0])
print(model.fc1)
```
In the next notebook, we'll see how we can train a neural network to accuractly predict the numbers appearing in the MNIST images.
| github_jupyter |
# D1 - 01 - Variables and Data Structures
## Content
- How do I use a jupyter notebook?
- What are variables and what can I do with them?
- Which data structures are available?
## Jupyter notebooks...
... are a single environment in which you can run code interactively, visualize results, and even add formatted documentation. This text for example lies in a **Markdown**-type cell. To run the currently highlighted cell, hold <kbd>⇧ Shift</kbd> and press <kbd>⏎ Enter</kbd>.
## Variables
Let's have a look at a code cell which will show us how to handle variables:
```
a = 1
b = 1.5
```
Click with you mouse pointer on the above cell and run it with <kbd>⇧</kbd>+<kbd>⏎</kbd>. You now a assigned the value $1$ to the variable `a` and $1.5$ to the variable `b`. By running the next cell, we print out the contents of both variables along with their type:
```
print(a, type(a))
print(b, type(b))
```
`a=1` represents an **integer** while `b=1.5` is a **floating point number**.
Next, we try to add, subtract, multiply and divide `a` and `b` and print out the result and its type:
```
c = a + b
print(c, type(c))
c = a - b
print(c, type(c))
c = a * b
print(c, type(c))
c = a / b
print(c, type(c))
```
Python can handle very small floats...
```
c = 1e-300
print(c, type(c))
```
...as well as very big numbers:
```
c = int(1e20)
print(c, type(c))
```
Note that, in the last cell, we have used a type conversion: `1e20` actually is a `float` which we cast as an `int` using the same-named function. Let's try thsi again to convert between floats and integers:
```
c = float(1)
print(c, type(c))
c = int(1.9)
print(c, type(c))
```
We observe that a `float` can easily be made into an `int` but in the reverse process, trailing digits are cut off without propper rounding.
Here is another example how Python handles rounding: we can choose between two division operators with different behavior.
```
c = 9 / 5
print(c, type(c))
c = 9 // 5
print(c, type(c))
```
The first version performs a usual floating point division, even for integer arguments. The second version performs an integer division and, like before, trailing digits are cut.
The last division-related operation is the modulo division:
```
c = 3 % 2
print(c, type(c))
```
For exponentiation, Python provides the `**` operator:
```
c = 2**3
print(c, type(c))
```
If we want to "update" to content of a variable, e.g. add a constant, we could write
```Python
c = c + 3
```
For such cases, however, Python provides a more compact syntax:
```
c += 3
print(c)
```
The versions `-=`, `*=`, `/=`, `//=`, `%=`, and `**=` are also available.
Now we shall see how Python stores variables. We create a variable `a` and assign its value to another variable `b`:
```
a = 1
b = a
print(a, id(a))
print(b, id(b))
```
When we now `print` the values and `id`s of both variables, we see that `a` and `b` share the same address: both are referencing the same **object**.
```
a += 1
print(a, id(a))
print(b, id(b))
```
If, however, we modify `a`, we see that `a` changes its avlues as well as its address while `b` remains unchanged. This is because the built-in data types `float` and `int` are **immutable**: you cannot change a `float`, you can only create a new one.
Here is a nice property of Python that allows easy swapping of variables:
```
print(a, b)
```
If we want to swap `a` and `b`, we do not need a third (swapping) variable as we can use two or even more variables on the left of the assignment operator `=`:
```
a, b = b, a
print(a, b)
```
Finally: text. A variable containing text has the type `str` (**string**). We use either single `'` or double `"` quotes.
```
a = 'some text...'
print(a, type(a))
```
When we add two strings, they are simply concatenated:
```
b = a + " and some more"
print(b)
```
### Playground: variables
Time to get creative! Create some variables, add or subtract them, cast them into other types, and get a feeling for their behavior...
## Data structures
Apart from the basic data types `int`, `float`, and `str`, Python provides more complex data types to store more than one value. There are several types of such structures which may seem very similar but differ significantly in their behavior:
```
a = ['one', 'two', 'three', 'four']
b = ('one', 'two', 'three', 'four')
c = {'one', 'two', 'three', 'four'}
print(a, id(a), type(a))
print(b, id(b), type(b))
print(c, id(c), type(c))
```
Now, we have created a `list`, a `tuple`, and a `set`; each containing four strings.
We create a new variable `d` from the `list` in `a` and modify the first element of `d`:
```
d = a
print(d[0])
d[0] = 'ONE'
print(a, id(a), type(a))
```
The `print` statement tells us that the change of `d`did change the content of `a`, but not its address. This means, a `list` is **mutable** and `a` and `d` are both pointing to the same, changeable object.
```
d += ['five']
print(a, id(a), type(a))
```
We can also add another `list` via `+` ...
```
d.append('six')
print(a, id(a), type(a))
```
... or another element via the `append()` method.
#### Exercise
What is the difference between adding two lists and using the `append` method?
#### Exercise
Can you access the first element of a `set` like we did for a `list`?
#### Exercise
Can you modify the first element of a tuple like we did for a `list`?
A set can be modified by adding new elements with the `add()` method; the `+` operator does not work:
```
c.add('five')
print(c, id(c), type(c))
```
We also observe that the address does not change: `set`s are, like `list`s, mutable. Why should we use a `set` instead of a list if we cannot access elements by index? Let's see how `list`s and `set`s behave for non-unique elements:
```
d = ['one', 'one', 'one', 'two']
print(d)
d = {'one', 'one', 'one', 'two'}
print(d)
```
While a `list` (like a `tuple`) exactly preserves all elements in order, a `set` contains only one for each different element. Thus, a `set` does not care how often an element is given but only if it is given at all.
Finally: a `tuple` is like a `list`, but **immutable**.
What is the mater with **mutable** and **immutable** objects?
- A **mutable** object is cheap to change but lookups of individual elements are expensive.
- An **immutable** object cannot be changed (only remade which is expensive) but lookups of elements is cheap.
`list`s, `tuple`s, and `set`s can be converted into each other:
```
a_tuple = ('one', 'two', 'three')
print(a_tuple, type(a_tuple))
a_list = list(a_tuple)
print(a_list, type(a_list))
a_tuple = ('one', 'two', 'three')
print(a_tuple, type(a_tuple))
a_set = set(a_tuple)
print(a_set, type(a_set))
a_list = ['one', 'two', 'three']
print(a_list, type(a_list))
a_set = set(a_list)
print(a_set, type(a_set))
a_list = ['one', 'two', 'three']
print(a_list, type(a_list))
a_tuple = tuple(a_list)
print(a_tuple, type(a_tuple))
```
#### Exercise
Take the given list and remove all multiple occurences of elements, i.e., no element may occur more than once. It is not important to preserve the order of elements.
```
a_list = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
```
Let's have a closer look at indexing for `list`s and `tuple`s:
```
a = list(range(10))
b = tuple(range(10))
print(a, type(a))
print(b, type(b))
```
In both cases, we access the first element by appending `[0]` to the variable name...
```
print(a[0], b[0])
```
... and the second element by appending `[1]`:
```
print(a[1], b[1])
```
Likewise, we access the last or second to last element using `[-1]` or `[-2]`:
```
print(a[-1], b[-1])
print(a[-2], b[-2])
```
Using `[:5]` we get all elements up to the index $5$ (excluded)...
```
print(a[:5])
```
... or starting from index $5$ until the end:
```
print(a[5:])
```
We can give both a start and end index to access any range...
```
print(a[2:7])
```
... and if we add another `:` and a number $>1$, this acts as a step size:
```
print(a[2:7:2])
```
A negative step size (and inverted start end indices) allows us to select a backwards defined range:
```
print(a[7:2:-2])
```
This always follows the same pattern: `start:end:step`.
With this `slicing`, we can easily reverse an entire `list`:
```
print(a[::-1])
```
#### Exercise
Coinvince yourself that the above indexing patterns also work for a `tuple`.
A remark on strings: `str`-type objects behave like a tuple...
```
c = 'this is a sentence'
print(c, type(c))
print(c[::-1])
```
... the are immutable but elements can be (read-)accessed by index and `sclicing`.
Let us now revisit `set`s:
```
a = set('An informative Python tutorial')
b = set('Nice spring weather')
print(a)
print(b)
```
Each `set` stores all letters used in the above sentences (but not the number of occurences). To make things easier to read, we pass each `set` through the `sorted()` function which sorts the sequence of letters:
```
print(sorted(a))
print(sorted(b))
```
A very nice feature of `set`s that `list`s and `tuple`s do not have is that we can use them with the bitwise operators `&`(logical and), `|` (logical or), and `^` (logical xor).
Thus, we can easily get the intersection of two sets...
```
print(sorted(a & b))
```
... their union...
```
print(sorted(a | b))
```
... or all letters which appear in only one of the two sentences:
```
print(sorted(a ^ b))
```
There is a fourth type of data structure, a `dict` (dictionary), which has some resemblance to `set`s. A `dict` contains pairs of `keys` and `values`, and for the `keys`, a `dict` behave like a `set`; i.e. no `key` may appear more than once. The `values` can then be accessed by their `keys` instead of indices. You can create a `dict` either with the same-named function...
```
a = dict(one=1, two=2, three=3)
print(a, type(a))
```
... or with a `set`-like syntax:
```
b = {'four': 4, 'five': 5, 'six': 6}
print(b, type(b))
```
We convince ourselfs that `dict`s are mutable...
```
c = a
c.update(zero=0)
print(a, type(a))
```
... and see how we can access an element by key:
```
print(a['two'])
```
To get all `keys` of a `dict` we can use the `keys()` method:
```
print(a.keys())
```
To repeat what we have done three cells before: we can add more `key`-`value` pairs with the `update()` method which accepts the same syntax as the `dict` function as well as entire `dict` objects:
```
a.update(b)
print(a)
```
A very useful feature of Python is that `list`s, `tuple`s, and `dict`s can be nested:
```
a = [0, 1, 2, ('one', 'two'), {5, 5, 5}]
print(a)
b = dict(some_key=list(range(10)))
print(b)
```
And, while a tuple itself is immutable, any mutable object within can be changed:
```
c = ('one', list(range(10)))
print(c)
c[1].append(10)
print(c)
```
#### Exercise
Build your own nested structure of all the data types shown in this notebook. Can you create a set which contains another set, list, tuple or dictionary?
| github_jupyter |
```
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
# Metadata saved to output plots
METADATA = {
"Contributor": "Alexander Gude",
"Rights": "CC-BY-SA 4.0"
}
# Show plots inline
%matplotlib inline
```
# Helper functions
```
# We should be able to just set rcParams, expect Jupyter has a bug:
# https://github.com/jupyter/notebook/issues/3385
#
# So we have to call this function every time we want to plot.
def setup_plot(title=None, xlabel=None, ylabel=None):
"""Set up a simple, single pane plot with custom configuration.
Args:
title (str, optional): The title of the plot.
xlabel (str, optional): The xlabel of the plot.
ylabel (str, optional): The ylabel of the plot.
Returns:
(fig, ax): A Matplotlib figure and axis object.
"""
# Plot Size
plt.rcParams["figure.figsize"] = (12, 7) # (Width, height)
# Text Size
SMALL = 12
MEDIUM = 16
LARGE = 20
HUGE = 28
plt.rcParams["axes.titlesize"] = HUGE
plt.rcParams["figure.titlesize"] = HUGE
plt.rcParams["axes.labelsize"] = LARGE
plt.rcParams["legend.fontsize"] = LARGE
plt.rcParams["xtick.labelsize"] = MEDIUM
plt.rcParams["ytick.labelsize"] = MEDIUM
plt.rcParams["font.size"] = SMALL
# Legend
plt.rcParams["legend.frameon"] = True
plt.rcParams["legend.framealpha"] = 1
plt.rcParams["legend.facecolor"] = "white"
plt.rcParams["legend.edgecolor"] = "black"
# Figure output
plt.rcParams["savefig.dpi"] = 300
# Make the plol
fig, ax = plt.subplots()
ax.set_title(title)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
return fig, ax
# https://stackoverflow.com/questions/19073683/matplotlib-overlapping-annotations-text
def draw_left_legend(ax, nudges=None, fontsize=20):
"""Draw legend labels at the end of each line.
Args:
ax (matplotlib axis): The axis to draw on.
nudges (Dict[str, float], default None): An optional mapping of line label
to y adjustment for the label. Useful for preventing overlap. If a key
is missing then that line is not adjusted.
fontsize (int, default 20): A fontsize understood by matplotlib. Either an
int or a size string.
Returns: None
"""
ax.get_legend().remove()
for line in ax.lines:
label = line.get_label()
color = line.get_color()
y = line.get_ydata()[-1]
x = line.get_xdata()[-1]
nudge_y = 0
if nudges is not None:
nudge_y = nudges.get(label, 0)
ax.annotate(
s=label,
xy=(x, y),
xytext=(10, 0+nudge_y),
textcoords='offset points',
color=color,
size=fontsize,
weight="bold",
va="center"
)
def plot_time_series(df, ax, date_col, category_col, resample_frequency=None, aggfunc="size", linewidth=3):
"""Draws a timeseries for each distinct item in the category column
Args:
df (Pandas DataFrame): The dataframe of data, containing `date_col` and
`category_col`.
ax (matplotlib axis): The axis to draw on.
date_col (str): The name of the column containing datetime objects.
Converted to a DatetimeIndex with `pandas.to_datetime()`.
category_col (str): The name of the column containing the categorical
variable to plot. Will draw one time series per value.
resample_frequency (str, default None): A frequency string understood
by `pandas.DataFrame.resample`. If not provided uses the natural
frequency of the data.
aggfunc (string or function, default 'size'): Any object understood by
`pandas.pivot_table(aggfunc=...)`, used to aggregate rows in time.
linewidth (int, default 3): Width of the lines to draw.
Returns: None
"""
# Save label because it will be over-writen by Pandas
xlabel = ax.get_xlabel()
tmp_df = df.set_index(date_col)
tmp_df.index = pd.to_datetime(tmp_df.index)
pivot = tmp_df.pivot_table(
index=tmp_df.index,
columns="vehicle_make",
aggfunc=aggfunc,
fill_value=0,
)
if resample_frequency is not None:
pivot = pivot.resample(resample_frequency).sum()
pivot.plot(ax=ax, linewidth=linewidth)
# Restore the label
ax.set_xlabel(xlabel)
```
# Plots
```
pd.concat((
df[df['vehicle_make']=="Honda"].sample(2),
df[df['vehicle_make']=="Other"].sample(2),
df[df['vehicle_make']=="Toyota"].sample(2),
))
fig, ax = setup_plot(title="Collisions by Make")
pivot = plot_time_series(df, ax, date_col=DATE_COL, category_col="vehicle_make", resample_frequency="W")
nudges = {"Toyota": 15, "Honda": -8}
draw_left_legend(ax, nudges=nudges, fontsize=25)
sns.despine(trim=True)
save_plot(fig, "/tmp/make_collision_in_time.svg")
```
| github_jupyter |
```
from pathlib import Path #Object-oriented filesystem paths
import pandas as pd #Python Data Analysis Library
import wget #Package to retrieve content from web servers
import time #Time access and conversions module
```
#### Example 1: One year data per file
This code is part of 'ESM2.3 CMIP6 data download using python for a single-model'<br>
https://youtu.be/jf1-AXhFSkU<br>
##### Learning objectives:<br>
* Data source (i.e., ESGF, CEDA)
* Make directory if does not exist
* for loop
* passing variables to string
* download file with url address using wget
```
# #Download from
node='http://esgf-data1.llnl.gov/thredds/fileServer/css03_data/'
mdir='CMIP6/HighResMIP/EC-Earth-Consortium/EC-Earth3P/hist-1950/r2i1p2f1/Omon/zos/gn/v20190812/'
#Download to
path=r'\\wsl$/Ubuntu/home/aelshall/NCO/Gmap/zos/EC-Earth3P/hist-1950/'
Path(path).mkdir(parents=True, exist_ok=True)
#Loop for all files
for year in range(1990,1991):
file='zos_Omon_EC-Earth3P_hist-1950_r2i1p2f1_gn_{}01-{}12.nc'.format(str(year),str(year))
#path to download from and to
dwf=node+mdir+file
dwt=path+file
print(dwf); print(dwt)
#start timer
start = time.time()
#Download file
wget.download(dwf,dwt)
#stop timer
print('\n'+'Download time: {:.1f} sec'.format(time.time() - start))
```
### Example 2: Dynamic time range
This code is part of 'ESM2.3 CMIP6 data download using python for a single-model'<br>
https://youtu.be/jf1-AXhFSkU<br>
##### Learning objectives:<br>
* iterate over two variables simultaneously (or their combination) using zip
* for loop with step
* if condition
* if condition for the last iteration
```
#Download from
serv='http://esgf-data3.ceda.ac.uk/thredds/fileServer/esg_cmip6/'
mdir='CMIP6/HighResMIP/NERC/HadGEM3-GC31-HH/hist-1950/r1i1p1f1/Omon/zos/gn/v20200514/'
#Download to
path=r'\\wsl$/Ubuntu/home/aelshall/NCO/Gmap/zos/HadGEM3-GC31-HH/hist-1950/'
#Path(path).mkdir(parents=True, exist_ok=True)
#file
year_step=1 #e.g., 1,5,10,25,65 years
month_flag=2
if month_flag==1:
MM1=['01']
MM2=['12']
elif month_flag==2:
MM1=['01','04','07','10']
MM2=['03','06','09','12']
for yyyy in range(1950,1952,year_step):
for mm1, mm2 in zip(MM1,MM2):
yyyy2=yyyy+year_step-1
if yyyy2>2014:
yyyy2=2014
#file='zos_Omon_HadGEM3-GC31-HH_hist-1950_r1i1p1f1_gn_199001-199003.nc'
file='zos_Omon_HadGEM3-GC31-HH_hist-1950_r1i1p1f1_gn_{}{}-{}{}.nc'.format(str(yyyy),mm1,str(yyyy2),mm2)
print(file)
```
### Example 3: Single-model ensemble
This code is part of 'ESM2.4 CMIP6 data download using python for a single-model ensemble'<br>
https://youtu.be/QS_RwPOz6Jg<br>
##### Learning objectives:<br>
* functions
```
def download(institution_ID,source_ID,experiment_ID,member_IDs,versions,period,year_step,month_flag,disp_flag):
for member_ID, version in zip(member_IDs,versions):
#Download from
node='http://esgf-data3.ceda.ac.uk/thredds/fileServer/esg_cmip6/'
mdir='CMIP6/HighResMIP/{}/{}/{}/{}/Omon/zos/gn/{}/'.format(institution_ID,source_ID,experiment_ID,member_ID,version)
#Download to
path=r'\\wsl$/Ubuntu/home/aelshall/NCO/Gmap/zos/{}/{}/'.format(source_ID,experiment_ID)
Path(path).mkdir(parents=True, exist_ok=True)
#Monthly steps
if month_flag==1:
MM1=['01']
MM2=['12']
elif month_flag==2:
MM1=['01','04','07','10']
MM2=['03','06','09','12']
#File download
for yyyy1 in range(period[0],period[1],year_step):
for mm1, mm2 in zip(MM1,MM2):
#Correct for last year of historical simulations
yyyy2=yyyy1+year_step-1
if yyyy2>2014:
yyyy2=2014
#Create file name
file='zos_Omon_{}_{}_{}_gn_{}{}-{}{}.nc'.format(source_ID,experiment_ID,member_ID,str(yyyy1),mm1,str(yyyy2),mm2)
if disp_flag>0:
print(file)
##download file
dwf=node+mdir+file
if disp_flag>1:
print(dwf)
dwt=path+file
if disp_flag>2:
print(dwt)
#wget.download(dwf,dwt)
#ECMWF-IFS-HR_hist-1950
period=[1950,1952]
institution_ID='ECMWF'
source_ID='ECMWF-IFS-HR'
experiment_ID='hist-1950'
member_IDs=['r1i1p1f1','r2i1p1f1','r3i1p1f1']
versions=['v20170101','v20180101','v20190101']
year_step=1
month_flag=1
disp_flag=2
download(institution_ID,source_ID,experiment_ID,member_IDs,versions,period,year_step,month_flag,disp_flag)
```
### Example 4: Multi-model ensemble
This code is part of 'ESM2.5 CMIP6 data download using python for multi-model ensemble'<br>
https://youtu.be/xpFkw5ba_Ew<br>
##### Learning objectives:<br>
* read csv_file into pandas dataFrame
* Selecting data by label/position
* Multiple if conditions
```
def download(SI,period,disp_flag,dw_flag,df):
#Simulation information
activity=df.loc[SI, 'activity']
institution_ID=df.loc[SI, 'institution_ID']
source_ID=df.loc[SI, 'source_ID']
experiment_ID=df.loc[SI, 'experiment_ID']
member_ID=df.loc[SI, 'member_ID']
grid_label=df.loc[SI, 'grid_label']
version=df.loc[SI, 'version']
serv=df.loc[SI, 'url']
start_count=df.loc[SI, 'start_count']
year_step=df.loc[SI, 'year_step']
num_files=df.loc[SI, 'number_of_files']
size_files=df.loc[SI, 'size']
#Simulation information
print('Downloading data of {}_{}_{} that has {} files of size {:.0f} MB'.\
format(source_ID,experiment_ID,member_ID,num_files,size_files/1e6))
#Download from
mdir='CMIP6/{}/{}/{}/{}/{}/Omon/zos/{}/{}/'.format(activity,institution_ID,source_ID,experiment_ID,member_ID,grid_label,version)
#Download to
path=r'\\wsl$/Ubuntu/home/aelshall/NCO/Gmap/zos/{}/{}/'.format(source_ID,experiment_ID)
#Path(path).mkdir(parents=True, exist_ok=True)
#Monthly steps
if source_ID=='HadGEM3-GC31-HH':
MM1=['01','04','07','10']
MM2=['03','06','09','12']
else:
MM1=['01']
MM2=['12']
#File download
for yyyy1 in range(period[0],period[1],year_step):
for mm1, mm2 in zip(MM1,MM2):
#Account for model group counting from one instead of zero
yyyy1=yyyy1+start_count
#Correct for last year of historical simulations
yyyy2=yyyy1+year_step-1
if yyyy2>2014:
yyyy2=2014
#Correct for single file
if year_step==65:
yyyy1=1950
yyyy2=2014
elif year_step==165:
yyyy1=1850
yyyy2=2014
##Special Case(1): AWI hist-1950 ends at 201012
if (institution_ID=='AWI' and experiment_ID=='hist-1950' and yyyy2>2010):
print('AWI-CM-1-1-HR_hist-1950 ends at 201012')
return
##Special Case(2): AWI historical has extra file for year 185001-185012 (hist-1950 ignored this year!)
if (institution_ID=='AWI' and experiment_ID=='historical' and yyyy1==1851):
file='zos_Omon_{}_{}_{}_gn_{}{}-{}{}.nc'.format(source_ID,experiment_ID,member_ID,str(1850),mm1,str(1850),mm2)
dwf=serv+mdir+file
print(dwf)
if dw_flag ==1:
wget.download(dwf,dwt)
#Create file name
file='zos_Omon_{}_{}_{}_gn_{}{}-{}{}.nc'.format(source_ID,experiment_ID,member_ID,str(yyyy1),mm1,str(yyyy2),mm2)
if disp_flag>0:
size_file=size_files/num_files/1e6
print('{} ({:.0f} MB)'.format(file,size_file))
##Special Case(3): HadGEM3-GC31-MM_historical has irregular date range starting from 1970
if (source_ID=='HadGEM3-GC31-MM' and experiment_ID=='historical' and yyyy1>1930):
print('HadGEM3-GC31-MM_historical has irregular date range starting from 1970')
#zos_Omon_HadGEM3-GC31-MM_historical_r1i1p1f3_gn_195001-196912.nc
#zos_Omon_HadGEM3-GC31-MM_historical_r1i1p1f3_gn_197001-198712.nc
#zos_Omon_HadGEM3-GC31-MM_historical_r1i1p1f3_gn_198801-198912.nc
#zos_Omon_HadGEM3-GC31-MM_historical_r1i1p1f3_gn_199001-200912.nc
#zos_Omon_HadGEM3-GC31-MM_historical_r1i1p1f3_gn_201001-201412.nc
dates=['197001-198712', '198801-198912','199001-200912','201001-201412']
for date in dates:
file='zos_Omon_{}_{}_{}_gn_{}.nc'.format(source_ID,experiment_ID,member_ID,date)
if disp_flag>0:
size_file=size_files/num_files/1e6
print('{} ({:.0f} MB)'.format(file,size_file))
dwf=serv+mdir+file
if disp_flag>1:
print(dwf)
if dw_flag ==1:
wget.download(dwf,dwt)
return
##download file
dwf=serv+mdir+file
if disp_flag>1:
print(dwf)
dwt=path+file
if disp_flag>2:
print(dwt)
if dw_flag ==1:
wget.download(dwf,dwt)
df=pd.read_csv('zos_data.csv')
period=[1950, 1952] #Download data from to
disp_flag=1 #[0] no display, [1] simple display, [2] full display
dw_flag=0 #[0] print file name and do not download file, [1] download file
#SI range for different models is the "sim_idx" column in zos_data.csv
for SI in range(27,30):
download(SI,period,disp_flag,dw_flag,df)
```
| github_jupyter |
```
import hoomd
import numpy
```
# Setting initial conditions in python
You can set initial conditions for HOOMD using arbitrary python code via a snapshot. Use this to generate random initial conditions within a job script, provide customizable parameters for the initial conditions, or read from a custom file format.
## Make Snapshot
The first step is to make a snapshot to hold the particles. `N` is the number of particles to create, `box` is the simulation box, and `particle_types` is a list of the particle type names. This only demonstrates the syntax you can use.
```
hoomd.context.initialize("");
snap = hoomd.data.make_snapshot(N=4, box=hoomd.data.boxdim(L=10), particle_types=['A', 'B']);
```
The snapshot object contains [numpy](http://www.numpy.org/) arrays with all of the particle properties.
```
print(snap.particles.position)
print(snap.particles.diameter)
print(snap.particles.velocity)
```
As you can see, all particles are initialized with default properties.
## Populate snapshot
The next step is to populate the snapshot with your desired initial condition. This can be created by any code, or assigned by hand. Make sure to assign positions for all particles.
```
snap.particles.position[0] = [1,2,3];
snap.particles.position[1] = [-1,-2,-3];
snap.particles.position[2] = [3,2,1];
snap.particles.position[3] = [-3,-2,-1];
```
You must assign elements of the arrays in the snapshot (particles.position[...] = ...), not the arrays themselves (particles.position = array). You can copy an existing numpy array with the [:] syntax.
```
numpy.random.seed(10);
my_velocity = numpy.random.random((4,3)) * 2 - 1;
snap.particles.velocity[:] = my_velocity[:];
print(snap.particles.velocity)
```
We assigned `particle_types=['A', 'B']` above. This makes the type id of 0 identify particle type 'A', and type id 1 identify particle type 'B'. The type id is just the index of the name in the list. Make the first three particles 'B' and the last one 'A':
```
snap.particles.typeid[:] = [1,1,1,0];
```
## Initialize from snapshot
The snapshot object `snap` stores a self-contained version of the system configuration. It is not connected with the rest of HOOMD. You can store as many snapshot objects as you can fit in memory, all with different properties. Use `hoomd.init.read_snapshot` to initialize a HOOMD simulation from a snapshot.
```
hoomd.init.read_snapshot(snap);
```
Now HOOMD is ready for pair forces, integrators, and other commands to configure the simulation run.
| github_jupyter |
```
from azureml.core import Workspace, Datastore, Dataset
from azureml.core import Experiment
import pandas as pd
import os
from azureml.core.compute import ComputeTarget
from azureml.contrib.automl.pipeline.steps import AutoMLPipelineBuilder
from azureml.pipeline.core import Pipeline
import shutil
import sys
from scripts.helper import get_forecasting_output
ws= Workspace.from_config()
dstore = ws.get_default_datastore()
experiment = Experiment(ws, 'manymodels-forecasting-pipeline-pandas-data')
filedst_10_models = Dataset.get_by_name(ws, name='MMSA_Sample_inference')
filedst_10_models_input = filedst_10_models.as_named_input('MMSA_Sample_inference')
compute = ComputeTarget(ws, 'compute-cluster')
training_experiment_name = "manymodels-training-pipeline-pandas-data"
training_pipeline_run_id = "your-run-id"
partition_column_names = ['Store']
inference_steps = AutoMLPipelineBuilder.get_many_models_batch_inference_steps(experiment=experiment,
inference_data=filedst_10_models_input,
compute_target=compute,
node_count=4,
process_count_per_node=4,
run_invocation_timeout=300,
output_datastore=dstore,
train_experiment_name=training_experiment_name,
train_run_id=training_pipeline_run_id,
partition_column_names=partition_column_names,
time_column_name="Date",
target_column_name="Sales")
pipeline = Pipeline(workspace = ws, steps=inference_steps)
run = experiment.submit(pipeline)
run.wait_for_completion(show_output=True)
published_pipeline = pipeline.publish(name = 'automl_score_many_models_pandas',
description = 'MMSA Solution using x data',
version = '1',
continue_on_step_failure = False)
forecasting_results_name = "forecasting_results"
forecasting_output_name = "many_models_inference_output"
forecast_file = get_forecasting_output(run, forecasting_results_name, forecasting_output_name)
df = pd.read_csv(forecast_file, delimiter=" ", header=None)
df.columns = ["Date", "Store", "Sales", "Predicted" ]
print("Prediction has ", df.shape[0], " rows. Here the first 10.")
df.head(10)
# from azureml.pipeline.core import Schedule, ScheduleRecurrence
# forecasting_pipeline_id = published_pipeline.id
# recurrence = ScheduleRecurrence(frequency="Month", interval=1, start_time="2020-01-01T09:00:00")
# recurring_schedule = Schedule.create(ws, name="automl_forecasting_recurring_schedule",
# description="Schedule Forecasting Pipeline to run on the first day of every week",
# pipeline_id=forecasting_pipeline_id,
# experiment_name=experiment.name,
# recurrence=recurrence)
```
| github_jupyter |
# <span style="color:Maroon">Hurst Exponent Analysis
__Summary:__ <span style="color:Blue">Explore the hurst exponent for various window sizes on given data
```
# Import required libraries
import warnings
warnings.filterwarnings('ignore')
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import hurst as hs
import os
np.random.seed(0)
# User defined names
index = "S&P500"
filename = index+".csv"
date_col = "Date"
hurst_windows = [100, 150, 200, 250, 300, 400]
# Get current working directory
mycwd = os.getcwd()
print(mycwd)
# Change to data directory
os.chdir("..")
os.chdir(str(os.getcwd()) + "\\Data")
# Read the data
df = pd.read_csv(filename, index_col=date_col)
df.index = pd.to_datetime(df.index)
df.head()
```
## <span style="color:Maroon">Functions
```
def Calculate_Hurst(df, var, window_size, ser_type):
"""
Calculates the hurst exponent for the var:variable in df:dataset for given rolling window size
ser_type: gives the type of series. It can be of three types:
'change': a series is just random values (i.e. np.random.randn(...))
'random_walk': a series is a cumulative sum of changes (i.e. np.cumsum(np.random.randn(...)))
'price': a series is a cumulative product of changes (i.e. np.cumprod(1+epsilon*np.random.randn(...))
"""
hurst = [np.nan] * (window_size-1)
var_values = list(df[var])
for i in range(0, len(var_values)-(window_size-1)):
H, c, data = hs.compute_Hc(var_values[i:i+window_size], kind=ser_type, simplified=True)
hurst.append(H)
df['hurst_'+str(window_size)] = hurst
return df
```
## <span style="color:Maroon">Hurst Exponent time Plots
```
# Change to Images directory
os.chdir("..")
os.chdir(str(os.getcwd()) + "\\Images")
# Calculate hurst exponents for given window sizes
for i in range(0, len(hurst_windows)):
df = Calculate_Hurst(df, 'Adj Close', hurst_windows[i], 'price')
var_names = ['hurst_'+str(x) for x in hurst_windows]
# Plot hurst exponents
plt.figure(figsize=(20,10))
plt.subplot(3,2,1)
plt.plot(df[var_names[0]].dropna(), 'b-', alpha=0.5)
plt.xlabel("Date", fontsize=12)
plt.ylabel("Hurst Exponent", fontsize=12)
plt.title("Window Size: {}".format(hurst_windows[0]), fontsize=16)
plt.grid()
plt.subplot(3,2,2)
plt.plot(df[var_names[1]].dropna(), 'b-', alpha=0.5)
plt.xlabel("Date", fontsize=12)
plt.ylabel("Hurst Exponent", fontsize=12)
plt.title("Window Size: {}".format(hurst_windows[1]), fontsize=16)
plt.grid()
plt.subplot(3,2,3)
plt.plot(df[var_names[2]].dropna(), 'b-', alpha=0.5)
plt.xlabel("Date", fontsize=12)
plt.ylabel("Hurst Exponent", fontsize=12)
plt.title("Window Size: {}".format(hurst_windows[2]), fontsize=16)
plt.grid()
plt.subplot(3,2,4)
plt.plot(df[var_names[3]].dropna(), 'b-', alpha=0.5)
plt.xlabel("Date", fontsize=12)
plt.ylabel("Hurst Exponent", fontsize=12)
plt.title("Window Size: {}".format(hurst_windows[3]), fontsize=16)
plt.grid()
plt.subplot(3,2,5)
plt.plot(df[var_names[4]].dropna(), 'b-', alpha=0.5)
plt.xlabel("Date", fontsize=12)
plt.ylabel("Hurst Exponent", fontsize=12)
plt.title("Window Size: {}".format(hurst_windows[4]), fontsize=16)
plt.grid()
plt.subplot(3,2,6)
plt.plot(df[var_names[5]].dropna(), 'b-', alpha=0.5)
plt.xlabel("Date", fontsize=12)
plt.ylabel("Hurst Exponent", fontsize=12)
plt.title("Window Size: {}".format(hurst_windows[5]), fontsize=16)
plt.grid()
plt.tight_layout()
plt.savefig('Hurst Exponent for different window size for ' + str(index) +'.png')
plt.show()
plt.close()
```
__Comments:__ <span style="color:Blue"> Window size 100 gives a volatile Hurst, but the plot for Hurst with window sizes 200, 300 and 400 is very similar. With higher window sizes the trend smoothens
## <span style="color:Maroon">Save the Data
```
os.chdir("..")
os.chdir(str(os.getcwd()) + "\\Data")
df.to_csv(index +"_hurst"+".csv", index=True)
```
| github_jupyter |
<a href="https://www.bigdatauniversity.com"><img src="https://ibm.box.com/shared/static/cw2c7r3o20w9zn8gkecaeyjhgw3xdgbj.png" width="400" align="center"></a>
<h1><center>K-Nearest Neighbors</center></h1>
In this Lab you will load a customer dataset, fit the data, and use K-Nearest Neighbors to predict a data point. But what is **K-Nearest Neighbors**?
**K-Nearest Neighbors** is an algorithm for supervised learning. Where the data is 'trained' with data points corresponding to their classification. Once a point is to be predicted, it takes into account the 'K' nearest points to it to determine it's classification.
### Here's an visualization of the K-Nearest Neighbors algorithm.
<img src="https://ibm.box.com/shared/static/mgkn92xck0z05v7yjq8pqziukxvc2461.png">
In this case, we have data points of Class A and B. We want to predict what the star (test data point) is. If we consider a k value of 3 (3 nearest data points) we will obtain a prediction of Class B. Yet if we consider a k value of 6, we will obtain a prediction of Class A.
In this sense, it is important to consider the value of k. But hopefully from this diagram, you should get a sense of what the K-Nearest Neighbors algorithm is. It considers the 'K' Nearest Neighbors (points) when it predicts the classification of the test point.
<h1>Table of contents</h1>
<div class="alert alert-block alert-info" style="margin-top: 20px">
<ol>
<li><a href="#about_dataset">About the dataset</a></li>
<li><a href="#visualization_analysis">Data Visualization and Analysis</a></li>
<li><a href="#classification">Classification</a></li>
</ol>
</div>
<br>
<hr>
Lets load required libraries
```
import itertools
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter
import pandas as pd
import numpy as np
import matplotlib.ticker as ticker
from sklearn import preprocessing
%matplotlib inline
```
<div id="about_dataset">
<h2>About the dataset</h2>
</div>
Imagine a telecommunications provider has segmented its customer base by service usage patterns, categorizing the customers into four groups. If demographic data can be used to predict group membership, the company can customize offers for individual prospective customers. It is a classification problem. That is, given the dataset, with predefined labels, we need to build a model to be used to predict class of a new or unknown case.
The example focuses on using demographic data, such as region, age, and marital, to predict usage patterns.
The target field, called __custcat__, has four possible values that correspond to the four customer groups, as follows:
1- Basic Service
2- E-Service
3- Plus Service
4- Total Service
Our objective is to build a classifier, to predict the class of unknown cases. We will use a specific type of classification called K nearest neighbour.
Lets download the dataset. To download the data, we will use !wget to download it from IBM Object Storage.
```
!wget -O teleCust1000t.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/teleCust1000t.csv
```
__Did you know?__ When it comes to Machine Learning, you will likely be working with large datasets. As a business, where can you host your data? IBM is offering a unique opportunity for businesses, with 10 Tb of IBM Cloud Object Storage: [Sign up now for free](http://cocl.us/ML0101EN-IBM-Offer-CC)
### Load Data From CSV File
```
df = pd.read_csv('teleCust1000t.csv')
df.head()
```
<div id="visualization_analysis">
<h2>Data Visualization and Analysis</h2>
</div>
#### Let’s see how many of each class is in our data set
```
df['custcat'].value_counts()
```
#### 281 Plus Service, 266 Basic-service, 236 Total Service, and 217 E-Service customers
You can easily explore your data using visualization techniques:
```
df.hist(column='income', bins=50)
```
### Feature set
Lets define feature sets, X:
```
df.columns
```
To use scikit-learn library, we have to convert the Pandas data frame to a Numpy array:
```
X = df[['region', 'tenure','age', 'marital', 'address', 'income', 'ed', 'employ','retire', 'gender', 'reside']] .values #.astype(float)
X[0:5]
```
What are our labels?
```
y = df['custcat'].values
y[0:5]
```
## Normalize Data
Data Standardization give data zero mean and unit variance, it is good practice, especially for algorithms such as KNN which is based on distance of cases:
```
X = preprocessing.StandardScaler().fit(X).transform(X.astype(float))
X[0:5]
```
### Train Test Split
Out of Sample Accuracy is the percentage of correct predictions that the model makes on data that that the model has NOT been trained on. Doing a train and test on the same dataset will most likely have low out-of-sample accuracy, due to the likelihood of being over-fit.
It is important that our models have a high, out-of-sample accuracy, because the purpose of any model, of course, is to make correct predictions on unknown data. So how can we improve out-of-sample accuracy? One way is to use an evaluation approach called Train/Test Split.
Train/Test Split involves splitting the dataset into training and testing sets respectively, which are mutually exclusive. After which, you train with the training set and test with the testing set.
This will provide a more accurate evaluation on out-of-sample accuracy because the testing dataset is not part of the dataset that have been used to train the data. It is more realistic for real world problems.
```
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=4)
print ('Train set:', X_train.shape, y_train.shape)
print ('Test set:', X_test.shape, y_test.shape)
```
<div id="classification">
<h2>Classification</h2>
</div>
<h3>K nearest neighbor (KNN)</h3>
#### Import library
Classifier implementing the k-nearest neighbors vote.
```
from sklearn.neighbors import KNeighborsClassifier
```
### Training
Lets start the algorithm with k=4 for now:
```
k = 4
#Train Model and Predict
neigh = KNeighborsClassifier(n_neighbors = k).fit(X_train,y_train)
neigh
```
### Predicting
we can use the model to predict the test set:
```
yhat = neigh.predict(X_test)
yhat[0:5]
```
### Accuracy evaluation
In multilabel classification, __accuracy classification score__ is a function that computes subset accuracy. This function is equal to the jaccard_similarity_score function. Essentially, it calculates how closely the actual labels and predicted labels are matched in the test set.
```
from sklearn import metrics
print("Train set Accuracy: ", metrics.accuracy_score(y_train, neigh.predict(X_train)))
print("Test set Accuracy: ", metrics.accuracy_score(y_test, yhat))
```
## Practice
Can you build the model again, but this time with k=6?
```
# write your code here
model = KNeighborsClassifier(n_neighbors=7)
model.fit(X_train, y_train)
print(model)
print()
y_pred = model.predict(X_train)
print("Train set Accuracy: ", metrics.accuracy_score(y_train, y_pred))
y_pred = model.predict(X_test)
print("Test set Accuracy: ", metrics.accuracy_score(y_test, y_pred))
```
Double-click __here__ for the solution.
<!-- Your answer is below:
k = 6
neigh6 = KNeighborsClassifier(n_neighbors = k).fit(X_train,y_train)
yhat6 = neigh6.predict(X_test)
print("Train set Accuracy: ", metrics.accuracy_score(y_train, neigh6.predict(X_train)))
print("Test set Accuracy: ", metrics.accuracy_score(y_test, yhat6))
-->
#### What about other K?
K in KNN, is the number of nearest neighbors to examine. It is supposed to be specified by the User. So, how can we choose right value for K?
The general solution is to reserve a part of your data for testing the accuracy of the model. Then chose k =1, use the training part for modeling, and calculate the accuracy of prediction using all samples in your test set. Repeat this process, increasing the k, and see which k is the best for your model.
We can calculate the accuracy of KNN for different Ks.
```
Ks = 11
mean_acc = np.zeros((Ks-1))
std_acc = np.zeros((Ks-1))
ConfustionMx = [];
for n in range(1,Ks):
#Train Model and Predict
neigh = KNeighborsClassifier(n_neighbors = n).fit(X_train,y_train)
yhat=neigh.predict(X_test)
mean_acc[n-1] = metrics.accuracy_score(y_test, yhat)
std_acc[n-1]=np.std(yhat==y_test)/np.sqrt(yhat.shape[0])
print(mean_acc)
print(std_acc)
```
#### Plot model accuracy for Different number of Neighbors
```
plt.plot(range(1,Ks),mean_acc,'g')
plt.fill_between(range(1,Ks),mean_acc - 1 * std_acc,mean_acc + 1 * std_acc, alpha=0.10)
plt.legend(('Accuracy ', '+/- 3xstd'))
plt.ylabel('Accuracy ')
plt.xlabel('Number of Nabors (K)')
plt.tight_layout()
plt.show()
print( "The best accuracy was with", mean_acc.max(), "with k=", mean_acc.argmax()+1)
```
<h2>Want to learn more?</h2>
IBM SPSS Modeler is a comprehensive analytics platform that has many machine learning algorithms. It has been designed to bring predictive intelligence to decisions made by individuals, by groups, by systems – by your enterprise as a whole. A free trial is available through this course, available here: <a href="http://cocl.us/ML0101EN-SPSSModeler">SPSS Modeler</a>
Also, you can use Watson Studio to run these notebooks faster with bigger datasets. Watson Studio is IBM's leading cloud solution for data scientists, built by data scientists. With Jupyter notebooks, RStudio, Apache Spark and popular libraries pre-packaged in the cloud, Watson Studio enables data scientists to collaborate on their projects without having to install anything. Join the fast-growing community of Watson Studio users today with a free account at <a href="https://cocl.us/ML0101EN_DSX">Watson Studio</a>
<h3>Thanks for completing this lesson!</h3>
<h4>Author: <a href="https://ca.linkedin.com/in/saeedaghabozorgi">Saeed Aghabozorgi</a></h4>
<p><a href="https://ca.linkedin.com/in/saeedaghabozorgi">Saeed Aghabozorgi</a>, PhD is a Data Scientist in IBM with a track record of developing enterprise level applications that substantially increases clients’ ability to turn data into actionable knowledge. He is a researcher in data mining field and expert in developing advanced analytic methods like machine learning and statistical modelling on large datasets.</p>
<hr>
<p>Copyright © 2018 <a href="https://cocl.us/DX0108EN_CC">Cognitive Class</a>. This notebook and its source code are released under the terms of the <a href="https://bigdatauniversity.com/mit-license/">MIT License</a>.</p>
| github_jupyter |
# KNN & DTW
```
# -*- coding: utf-8 -*-
class Dtw(object):
def __init__(self, seq1, seq2,
patterns = [(-1,-1), (-1,0), (0,-1)],
weights = [{(0,0):2}, {(0,0):1}, {(0,0):1}],
band_r=0.015): #EDIT HERE
self._seq1 = seq1
self._seq2 = seq2
self.len_seq1 = len(seq1)
self.len_seq2 = len(seq2)
self.len_pattern = len(patterns)
self.sum_w = [sum(ws.values()) for ws in weights]
self._r = int(len(seq1)*band_r)
assert len(patterns) == len(weights)
self._patterns = patterns
self._weights = weights
def get_distance(self, i1, i2):
return abs(self._seq1[i1] - self._seq2[i2])
def calculate(self):
g = list([float('inf')]*self.len_seq2 for i in range(self.len_seq1))
cost = list([0]*self.len_seq2 for i in range(self.len_seq1))
g[0][0] = 2*self.get_distance(0, 0)
for i in range(self.len_seq1):
for j in range(max(0,i-self._r), min(i+self._r+1, self.len_seq2)):
for pat_i in range(self.len_pattern):
coor = (i+self._patterns[pat_i][0], j+self._patterns[pat_i][1])
if coor[0]<0 or coor[1]<0:
continue
dist = 0
for w_coor_offset, d_w in self._weights[pat_i].items():
w_coor = (i+w_coor_offset[0], j+w_coor_offset[1])
dist += d_w*self.get_distance(w_coor[0], w_coor[1])
this_val = g[coor[0]][coor[1]] + dist
this_cost = cost[coor[0]][coor[1]] + self.sum_w[pat_i]
if this_val < g[i][j]:
g[i][j] = this_val
cost[i][j] = this_cost
return g[self.len_seq1-1][self.len_seq2-1]/cost[self.len_seq1-1][self.len_seq2-1], g, cost
def print_table(self, tb):
print(' '+' '.join(["{:^7d}".format(i) for i in range(self.len_seq2)]))
for i in range(self.len_seq1):
str = "{:^4d}: ".format(i)
for j in range(self.len_seq2):
str += "{:^7.3f} ".format(tb[i][j])
print (str)
def print_g_matrix(self):
_, tb, _ = self.calculate()
self.print_table(tb)
def print_cost_matrix(self):
_, _, tb = self.calculate()
self.print_table(tb)
def get_dtw(self):
ans, _, _ = self.calculate()
return ans
import csv
import random
import math
import operator
import numpy as np
def loadDataset(filename, data=[]):
with open(filename, 'rb') as csvfile:
lines = csv.reader(csvfile,delimiter=' ')
dataset = list(lines)
for x in range(len(dataset)):
dataset[x] = filter(None, dataset[x])
dataset[x] = list(map(float, dataset[x]))
data.append(dataset[x])
def euclideanDistance(instance1, instance2, length):
distance = 0
for x in range(length):
if x == 0:
continue
distance += pow((instance1[x] - instance2[x]), 2)
return math.sqrt(distance)
def getNeighbors(trainingSet, testInstance, k, pattern, weight):
distances = []
length = len(testInstance)
for x in range(len(trainingSet)):
# z-normalization
d = Dtw(testInstance[1:], trainingSet[x][1:], pattern, weight)
dist = d.get_dtw()
# dist = euclideanDistance(testInstance, trainingSet[x], length)
distances.append((trainingSet[x], dist))
distances.sort(key=operator.itemgetter(1))
# print "dist >>>> ",distances
neighbors = []
for x in range(k):
neighbors.append(distances[x][0])
return neighbors
def getResponse(neighbors):
classVotes = {}
for x in range(len(neighbors)):
response = neighbors[x][0]
if response in classVotes:
classVotes[response] += 1
else:
classVotes[response] = 1
sortedVotes = sorted(classVotes.iteritems(), key=operator.itemgetter(1), reverse=True)
return sortedVotes[0][0]
def getAccuracy(testSet, predictions):
correct = 0
for x in range(len(testSet)):
if testSet[x][0] == predictions[x]:
correct += 1
return (correct/float(len(testSet))) * 100.0
def knn(trainingSet, testSet, k, pattern, weight):
# generate predictions
predictions=[]
for x in range(len(testSet)):
# print ">>",testSet[x]
neighbors = getNeighbors(trainingSet, testSet[x], k, pattern, weight)
# print "neighbors >>", neighbors
result = getResponse(neighbors)
# print "result >>", result
predictions.append(result)
# print('> predicted=' + repr(result) + ', actual=' + repr(testSet[x][0]))
accuracy = getAccuracy(testSet, predictions)
return accuracy
def prepareData(train_data, test_data):
# prepare data
rawTrainingSet=[]
rawTestSet=[]
testSet=[]
trainingSet=[]
loadDataset(train_data, rawTrainingSet)
loadDataset(test_data, rawTestSet)
for x in rawTrainingSet:
newTS = np.append(x[0], ( np.array(x[1:])-np.mean(x[1:]) )/np.std(x[1:]) )
trainingSet.append(newTS)
for x in rawTestSet:
newTS = np.append(x[0], ( np.array(x[1:])-np.mean(x[1:]) )/np.std(x[1:]) )
testSet.append(newTS)
# print 'Train set: ' + repr(len(trainingSet))
# print trainingSet
# print 'Test set: ' + repr(len(testSet))
# print testSet
return trainingSet, testSet
```
# Main
```
PATTERNS_1 = [(0,-1), (-1,-1), (-1,0)]
WEIGHTS_SYM_1 = [{(0,0):1}, {(0,0):2}, {(0,0):1}]
COUNT = 10
weights = []
for i in range(COUNT+1):
for j in range(COUNT-i+1):
k = COUNT - j - i
weights.append([{(0,0):i}, {(0,0):j}, {(0,0):k}])
# EDIT HERE
TRAIN_DATA = 'dataset/Beef_TRAIN'
TEST_DATA = 'dataset/Beef_TEST'
OUTPUT_FILE = 'acc_beef_0.03band_no-dup-normalize.csv'
trainingSet, testSet = prepareData(TRAIN_DATA, TEST_DATA)
knn(trainingSet, testSet, 1, PATTERNS_1, WEIGHTS_SYM_1)
with open(OUTPUT_FILE, "w") as myfile:
myfile.write("i,j,k,accuracy\n")
for weight in weights:
i = weight[0][(0,0)]
j = weight[1][(0,0)]
k = weight[2][(0,0)]
print "i:", i, "j:", j,"k:", k
acc = knn(trainingSet, testSet, 1, PATTERNS_1, weight)
print acc
with open(OUTPUT_FILE, "a") as myfile:
myfile.write(str(i)+","+str(j)+","+str(k)+","+str(acc)+"\n")
```
| github_jupyter |
# COMP9417 19T2 Homework 2: Applying and Implementing Machine Learning
_Mon Jul 29 09:18:30 AEST 2019_
The aim of this homework is to enable you to:
- **apply** parameter search for machine learning algorithms implemented in the Python [scikit-learn](http://scikit-learn.org/stable/index.html) machine learning library
- answer questions based on your **analysis** and **interpretation** of the empirical results of such applications, using your knowledge of machine learning
- **complete** an implementation of a different version of a learning algorithm you have previously seen
After completing this homework you will be able to:
- set up a simple grid search over different hyper-parameter settings based on $k$-fold cross-validation to obtain performance measures on different datasets
- compare the performance measures of different algorithm settings
- propose properties of algorithms and their hyper-parameters, or datasets, which
may lead to performance differences being observed
- suggest reasons for actual observed performance differences in terms of
properties of algorithms, parameter settings or datasets.
- read and understand incomplete code for a learning algorithm to the point of being able to complete the implementation and run it successfully on a dataset.
There are a total of *10 marks* available.
Each homework mark is worth *0.5 course mark*, i.e., homework marks will be scaled
to a **course mark out of 5** to contribute to the course total.
Deadline: 17:59:59, Monday August 5, 2019.
Submission will be via the CSE *give* system (see below).
Late penalties: one mark will be deducted from the total for each day late, up to a total of five days. If six or more days late, no marks will be given.
Recall the guidance regarding plagiarism in the course introduction: this applies to this homework and if evidence of plagiarism is detected it may result in penalties ranging from loss of marks to suspension.
### Format of the questions
There are 2 questions in this homework. Question 1 requires answering some multiple-choice questions in the file [*answers.txt*](http://www.cse.unsw.edu.au/~cs9417/19T2/hw2/answers.txt). Both questions require you to copy and paste text into the file [*answers.txt*](http://www.cse.unsw.edu.au/~cs9417/19T2/hw2/answers.txt). This file **MUST CONTAIN ONLY PLAIN TEXT WITH NO SPECIAL CHARACTERS**.
This file will form your submission.
In summary, your submission will comprise a single file which should be named as follows:
```
answers.txt
```
Please note: files in any format other than plain text **cannot be accepted**.
Submit your files using ```give```. On a CSE Linux machine, type the following on the command-line:
```
$ give cs9417 hw2 answers.txt
```
Alternatively, you can submit using the web-based interface to ```give```.
### Datasets
You can download the datasets required for the homework [here](http://www.cse.unsw.edu.au/~cs9417/hw2/datasets.zip).
Note: you will need to ensure the dataset files are in the same directory from which you are running this notebook.
**Please Note**: this homework uses some datasets in the Attribute-Relation File Format (.arff). To load datasets from '.arff' formatted files, you will need to have installed the ```liac-arff``` package. You can do this using ```pip``` at the command-line, as follows:
```
$ pip install liac-arff
```
## Question 1 – Overfitting avoidance [Total: 3 marks]
Dealing with noisy data is a key issue in machine learning. Unfortunately, even algorithms that have noise-handling mechanisms built-in, like decision trees, can overfit noisy data, unless their "overfitting avoidance" or *regularization* hyper-parameters are set properly.
You will be using datasets that have had various amounts of "class noise" added
by randomly changing the actual class value to a different one for a
specified percentage of the training data.
Here we will specify three arbitrarily chosen levels of noise: low
($20\%$), medium ($50\%$) and high ($80\%$).
The learning algorithm must try to "see through" this noise and learn
the best model it can, which is then evaluated on test data *without*
added noise to evaluate how well it has avoided fitting the noise.
We will also let the algorithm do a limited _grid search_ using cross-validation
for the best *over-fitting avoidance* parameter settings on each training set.
### Running the classifiers
**1(a). [1 mark]**
Run the code section in the notebook cells below. This will generate a table of results, which you should copy and paste **WITHOUT MODIFICATION** into the file [*answers.txt*](http://www.cse.unsw.edu.au/~cs9417/19T2/hw2/answers.txt)
as your answer for "Question 1(a)".
The output of the code section is a table, which represents the percentage accuracy of classification for the decision tree algorithm. The first column contains the result of the "Default" classifier, which is the decision tree algorithm with default parameter settings running on each of the datasets which have had $50\%$ noise added. From the second column on, in each column the results are obtained by running the decision tree algorithm on $0\%$, $20\%$, $50\%$ and $80\%$ noise added to each of the datasets, and in the parentheses is shown the result of a [grid search](http://en.wikipedia.org/wiki/Hyperparameter_optimization) that has been applied to determine the best value for a basic parameter of the decision tree algorithm, namely [min_samples_leaf](http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html) i.e., the minimum number of examples that can be used to make a prediction in the tree, on that dataset.
### Result interpretation
Answer these questions in the file called [*answers.txt*](http://www.cse.unsw.edu.au/~cs9417/19T2/hw2/answers.txt). Your answers must be based on the results table you saved in "Question 1(a)".
**1(b). [1 mark]** Refer to [*answers.txt*](http://www.cse.unsw.edu.au/~cs9417/19T2/hw2/answers.txt).
**1(c). [1 mark]** Refer to [*answers.txt*](http://www.cse.unsw.edu.au/~cs9417/19T2/hw2/answers.txt).
### Code for question 1
It is only necessary to run the following code to answer the question, but you should also go through it to make sure you know what is going on.
```
# Code for question 1
import arff, numpy as np
import pandas as pd
from sklearn.base import TransformerMixin
from sklearn import tree
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn import svm, datasets
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
import sys
import warnings
# fixed random seed
np.random.seed(1)
def warn(*args, **kwargs):
pass
def label_enc(labels):
le = preprocessing.LabelEncoder()
le.fit(labels)
return le
def features_encoders(features,categorical_features='all'):
n_samples, n_features = features.shape
label_encoders = [preprocessing.LabelEncoder() for _ in range(n_features)]
X_int = np.zeros_like(features, dtype=np.int)
for i in range(n_features):
feature_i = features[:, i]
label_encoders[i].fit(feature_i)
X_int[:, i] = label_encoders[i].transform(feature_i)
enc = preprocessing.OneHotEncoder(categorical_features=categorical_features)
return enc.fit(X_int),label_encoders
def feature_transform(features,label_encoders, one_hot_encoder):
n_samples, n_features = features.shape
X_int = np.zeros_like(features, dtype=np.int)
for i in range(n_features):
feature_i = features[:, i]
X_int[:, i] = label_encoders[i].transform(feature_i)
return one_hot_encoder.transform(X_int).toarray()
warnings.warn = warn
a = numpy.zeros((3, 3))
a
a[:,0:2] =9
a
class DataFrameImputer(TransformerMixin):
def fit(self, X, y=None):
self.fill = pd.Series([X[c].value_counts().index[0]
if X[c].dtype == np.dtype('O') else X[c].mean() for c in X],
index=X.columns)
return self
def transform(self, X, y=None):
return X.fillna(self.fill)
def load_data(path):
dataset = arff.load(open(path, 'r'))
data = np.array(dataset['data'])
data = pd.DataFrame(data)
data = DataFrameImputer().fit_transform(data).values
attr = dataset['attributes']
# mask categorical features
masks = []
for i in range(len(attr)-1):
if attr[i][1] != 'REAL':
masks.append(i)
return data, masks
def preprocess(data,masks, noise_ratio):
# split data
train_data, test_data = train_test_split(data,test_size=0.3,random_state=0)
# test data
test_features = test_data[:,0:test_data.shape[1]-1]
test_labels = test_data[:,test_data.shape[1]-1]
# training data
features = train_data[:,0:train_data.shape[1]-1]
print(features)
labels = train_data[:,train_data.shape[1]-1]
classes = list(set(labels))
# categorical features need to be encoded
if len(masks):
one_hot_enc, label_encs = features_encoders(data[:,0:data.shape[1]-1],masks)
test_features = feature_transform(test_features,label_encs,one_hot_enc)
features = feature_transform(features,label_encs,one_hot_enc)
le = label_enc(data[:,data.shape[1]-1])
labels = le.transform(train_data[:,train_data.shape[1]-1])
test_labels = le.transform(test_data[:,test_data.shape[1]-1])
# add noise
np.random.seed(1234)
noise = np.random.randint(len(classes)-1, size=int(len(labels)*noise_ratio))+1
noise = np.concatenate((noise,np.zeros(len(labels) - len(noise),dtype=np.int)))
labels = (labels + noise) % len(classes)
return features,labels,test_features,test_labels
# load data
paths = ['./datasets/balance-scale','./datasets/primary-tumor',
'./datasets/glass','./datasets/heart-h']
noise = [0,0.2,0.5,0.8]
scores = []
params = []
for path in paths:
score = []
param = []
path += '.arff'
data, masks = load_data(path)
# training on data with 50% noise and default parameters
features, labels, test_features, test_labels = preprocess(data, masks, 0.5)
tree = DecisionTreeClassifier(random_state=0,min_samples_leaf=2, min_impurity_decrease=0)
tree.fit(features, labels)
tree_preds = tree.predict(test_features)
tree_performance = accuracy_score(test_labels, tree_preds)
score.append(tree_performance)
param.append(tree.get_params()['min_samples_leaf'])
# training on data with noise levels of 0%, 20%, 50% and 80%
for noise_ratio in noise:
features, labels, test_features, test_labels = preprocess(data, masks, noise_ratio)
param_grid = {'min_samples_leaf': np.arange(2,30,5)}
grid_tree = GridSearchCV(DecisionTreeClassifier(random_state=0), param_grid,cv=10,return_train_score=True)
grid_tree.fit(features, labels)
estimator = grid_tree.best_estimator_
tree_preds = grid_tree.predict(test_features)
tree_performance = accuracy_score(test_labels, tree_preds)
score.append(tree_performance)
param.append(estimator.get_params()['min_samples_leaf'])
scores.append(score)
params.append(param)
# print the results
header = "{:^112}".format("Decision Tree Results") + '\n' + '-' * 112 + '\n' + \
"{:^15} | {:^16} | {:^16} | {:^16} | {:^16} | {:^16} |".format("Dataset", "Default", "0%", "20%", "50%", "80%") + \
'\n' + '-' * 112 + '\n'
# print result table
print(header)
for i in range(len(scores)):
#scores = score_list[i][1]
print("{:<16}".format(paths[i]),end="")
for j in range(len(params[i])):
print("| {:>6.2%} ({:>2}) " .format(scores[i][j],params[i][j]),end="")
print('|\n')
print('\n')
```
## Question 2 – Implementation of a simple RNN [Total: 7 marks]
In this question, you will implement a simple recurrent neural network (RNN).
Recurrent neural networks are commonly used when the input data has temporal dependencies among consecutive observations, for example time series and text data. With such data, having knowledge of the previous data points in addition to the current helps in prediction.
## Recurrent neural networks
RNNs are suitable in such scenarios because they keep a state derived from all previously seen data, which in combination with the current input is used to predict the output.
In general, recurrent neural networks work like the following:

_(Image credit: Goodfellow, Bengio & Courville (2015) - Deep Learning)_
Here, $x$ is the input, and $h$ is the hidden state maintained by the RNN. For each input in the sequence, the RNN takes both the previous state $h_{t-1}$ and the current input $x_t$ to do the prediction.
Notice there is only one set of weights in the RNN, but this set of weights is used for the whole sequence of input. In effect, the RNN is chained with itself a number of times equalling the length of the input.
Thus for the purpose of training the RNN, a common practice is to unfold the computational graph, and run the standard back-propagation thereon. This technique is also known as back-propagation through time.
## Your task
Given a dataset of partial words (words without the last character), your task is to implement an RNN to predict the last character in the word. Specifically, your RNN will have the first 9 characters of a word as its input, and you need to predict the 10th character. If there are fewer than 10 characters in a word, spaces are used to pad it.
Most of the code needed is provided below, what you need to do is to implement the back-propagation through time section in ```NeuralNetwork.fit()```.
There are four sections marked ```TO DO: ``` where you need to add your own code to complete a working implementation.
**HINT:** review the implementation of the ```backpropagate``` method of the ```NeuralNetwork``` class in the code in the notebook for Lab6 on "Neural Learning". That should give you a starting point for your implementation.
Ensure that you have the following files you need for training and testing in the directory in which you run this notebook:
```
training_input.txt
training_label.txt
testing_input.txt
testing_label.txt
```
**HINT:** if your implementation is correct your output should look something like the following:

## Submission
Submit a text file ```RNN_solutions.txt```, containing only the four sections (together with the comments)
Sample submission:
```
# setup for the current step
layer_input = []
weight = []
# calculate gradients
gradients, dW, db = [], [], []
# update weights
self.weights[0] += 0
self.biases[0] += 0
# setup for the next step
previous_gradients = []
layer_output = []
```
## Marking
If your implementation runs and obtains a testing accuracy of more than 0.5 then your submission will be given full marks.
Otherwise, each submitted correct section of your code will receive some part of the total marks, as follows:
```
# setup for the current step [2 marks]
layer_input = []
weight = []
# calculate gradients [1 mark]
gradients, dW, db = [], [], []
# update weights [2 marks]
self.weights[0] += 0
self.biases[0] += 0
# setup for the next step [2 marks]
previous_gradients = []
layer_output = []
```
**NOTE:** it is OK to split your code for each section over multiple lines.
```
import time
import numpy
# helper functions to read data
def read_data(file_name, encoding_function, expected_length):
with open(file_name, 'r') as f:
return numpy.array([encoding_function(row) for row in f.read().split('\n') if len(row) == expected_length])
def encode_string(s):
return [one_hot_encode_character(c) for c in s]
def one_hot_encode_character(c):
base = [0] * 26
index = ord(c) - ord('a')
if index >= 0 and index <= 25:
base[index] = 1
return base
def reverse_one_hot_encode(v):
return chr(numpy.argmax(v) + ord('a')) if max(v) > 0 else ' '
# functions used in the neural network
def sigmoid(x):
return 1 / (1 + numpy.exp(-x))
def sigmoid_derivative(x):
return (1 - x) * x
def argmax(x):
return numpy.argmax(x, axis=1)
training_input = read_data("./datasets/training_input.txt", encode_string, 9)
training_input
training_label = read_data("./datasets/training_label.txt", one_hot_encode_character, 1)
# print(training_label)
model = NeuralNetwork()
model.fit(training_input, training_label)
class NeuralNetwork:
def __init__(self, learning_rate=2, epochs=5000, input_size=9, hidden_layer_size=64):
# activation function and its derivative to be used in backpropagation
self.activation_function = sigmoid
self.derivative_of_activation_function = sigmoid_derivative
self.map_output_to_prediction = argmax
# parameters
self.learning_rate = learning_rate
self.epochs = epochs
self.input_size = input_size
self.hidden_layer_size = hidden_layer_size
# initialisation
numpy.random.seed(77)
def fit(self, X, y):
# reset timer
timer_base = time.time()
# initialise the weights of the NN
input_dim = X.shape[2] + self.hidden_layer_size
output_dim = y.shape[1]
self.weights, self.biases = [], []
previous_layer_size = input_dim
for current_layer_size in [self.hidden_layer_size, output_dim]:
print( current_layer_size )
# random initial weights and zero biases
weights_of_current_layer = numpy.random.randn(previous_layer_size, current_layer_size)
bias_of_current_layer = numpy.zeros((1, current_layer_size))
self.weights.append(weights_of_current_layer)
self.biases.append(bias_of_current_layer)
previous_layer_size = current_layer_size
# train the NN
self.accuracy_log = []
for epoch in range(self.epochs + 1):
outputs = self.forward_propagate(X)
prediction = outputs.pop()
if epoch % 100 == 0:
accuracy = self.evaluate(prediction, y)
print(f"In iteration {epoch}, training accuracy is {accuracy}.")
self.accuracy_log.append(accuracy)
# first step of back-propagation
dEdz = y - prediction
layer_input = outputs.pop()
layer_output = prediction
# calculate gradients
dEds, dW, db = self.derivatives_of_last_layer(dEdz, layer_output, layer_input)
# print(dW.shape)
# print(self.weights[1].shape)
# update weights
self.weights[1] += self.learning_rate / X.shape[0] * dW
self.biases[1] += self.learning_rate / X.shape[0] * db
# setup for the next step
previous_gradients = dEds
layer_output = layer_input
# back-propagation through time (unrolled)
# print(self.input_size)
# print(len(outputs))
# back-propagation through time (unrolled)
for step in range(self.input_size - 1, -1, -1):
# TO DO: setup for the current step
layer_input = numpy.concatenate((outputs[step], X[:,step, :]), axis=1)
if step == self.input_size -1:
weight = self.weights[1][:64,:]
else:
weight = self.weights[0][:64,:]
# TO DO: calculate gradients
gradients, dW, db = self.derivatives_of_hidden_layer(previous_gradients, layer_output, layer_input, weight)
# TO DO: update weights
# print(dW.shape)
# print( len(self.weights))
# print( len(self.biases))
# print(dW.T.shape)
# print(self.weights[0].shape)
self.weights[0] += self.learning_rate * dW
self.biases[0] += self.learning_rate * db
# TO DO: setup for the next step
previous_gradients = gradients
layer_output = outputs[step]
print(f"Finished training in {time.time() - timer_base} seconds")
def test(self, X, y, verbose=True):
predictions = self.forward_propagate(X)[-1]
if verbose:
for index in range(len(predictions)):
prefix = ''.join(reverse_one_hot_encode(v) for v in X[index])
print(f"Expected {prefix + reverse_one_hot_encode(y[index])}, predicted {prefix + reverse_one_hot_encode(predictions[index])}")
print(f"Testing accuracy: {self.evaluate(predictions, y)}")
def evaluate(self, predictions, target_values):
successful_predictions = numpy.where(self.map_output_to_prediction(predictions) == self.map_output_to_prediction(target_values))
return successful_predictions[0].shape[0] / len(predictions) if successful_predictions else 0
def forward_propagate(self, X):
# initial states
current_state = numpy.zeros((X.shape[0], self.hidden_layer_size))
outputs = [current_state]
# forward propagation through time (unrolled)
for step in range(self.input_size):
x = numpy.concatenate((current_state, X[:, step, :]), axis=1)
current_state = self.apply_neuron(self.weights[0], self.biases[0], x)
outputs.append(current_state)
# the last layer
output = self.apply_neuron(self.weights[1], self.biases[1], current_state)
outputs.append(output)
return outputs
def apply_neuron(self, w, b, x):
return self.activation_function(numpy.dot(x, w) + b)
def derivatives_of_last_layer(self, dEdz, layer_output, layer_input):
dEds = self.derivative_of_activation_function(layer_output) * dEdz
dW = numpy.dot(layer_input.T, dEds)
db = numpy.sum(dEds, axis=0, keepdims=True)
return dEds, dW, db
def derivatives_of_hidden_layer(self, layer_difference, layer_output, layer_input, weight):
gradients = self.derivative_of_activation_function(layer_output) * numpy.dot(layer_difference, weight.T)
dW = numpy.dot(layer_input.T, gradients)
db = numpy.sum(gradients, axis=0, keepdims=True)
return gradients, dW, db
training_input = read_data("./datasets/training_input.txt", encode_string, 9)
training_input
training_label = read_data("./datasets/training_label.txt", one_hot_encode_character, 1)
# print(training_label)
model = NeuralNetwork()
model.fit(training_input, training_label)
testing_input = read_data("./datasets/testing_input.txt", encode_string, 9)
testing_label = read_data("./datasets/testing_label.txt", one_hot_encode_character, 1)
model.test(testing_input, testing_label, verbose=True)
```
| github_jupyter |
# 矩阵运算
### 矩阵加法 Plus
矩阵加法: 参与运算的矩阵必须是大小一样的(n,m都一样)
$$
\left[
\begin{matrix}
1 & 2 \\
3 & 4
\end{matrix}
\right]
+
\left[
\begin{matrix}
1 & 2 \\
3 & 4
\end{matrix}
\right]
=
\left[
\begin{matrix}
2 & 4 \\
6 & 8
\end{matrix}
\right]
$$
- 交换律:A+B=B+A
- 结合律:(A+B)+C=A+(B+C)
### 代码
```
import numpy as np
def plus(x: np.ndarray, y: np.ndarray) -> np.ndarray:
""" 矩阵相加"""
if x.shape == y.shape:
return x + y
a = np.array([
[1, 2],
[2, 3]
])
b = np.copy(a)
c = plus(a, b)
c
```
### 矩阵乘法 Multiply
- 矩阵A(m*p) X 矩阵B(p*n) 结论为C(m*n) 公式如下
$$
( AB )_{ij} = \sum^{p}_{k=1} A_{ik}b_{kj} = a_{i1}b_{1j} + a_{i2}b_{2j}+...+ a_{ip}b_{pj}
$$
- 例子
$$
\left[
\begin{matrix}
1 & 2 & 3 \\
4 & 5 & 6
\end{matrix}
\right]
*
\left[
\begin{matrix}
1 & 4 \\
2 & 5 \\
3 & 6
\end{matrix}
\right]
=
\left[
\begin{matrix}
1*1+2*2+3*3 & 1*4+2*5+3*6 \\
4*1+5*2+6*3 & 4*4+5*5+6*6
\end{matrix}
\right]
= \left[
\begin{matrix}
14 & 32 \\
32 & 77
\end{matrix}
\right]
$$
### 代码
```
def multiply(x: np.ndarray, y) -> np.ndarray:
"""矩阵乘法"""
return x.dot(y)
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([
[1, 4],
[2, 5],
[3, 6],
])
multiply(a,b)
```
### 哈达马乘积 Hadamard product
哈达马乘积: 参与运算的矩阵必须是大小一样的(n,m都一样)
$$
\left[
\begin{matrix}
1 & 4 \\
2 & 5
\end{matrix}
\right]*
\left[
\begin{matrix}
1 & 4 \\
2 & 5
\end{matrix}
\right]
=\left[
\begin{matrix}
1*1 & 4*4 \\
2*2 & 5*5
\end{matrix}
\right]
=\left[
\begin{matrix}
1 & 16 \\
4 & 25
\end{matrix}
\right]
$$
### 代码
```
a = np.array([
[1, 4],
[2, 5]
])
a.dot(a)
```
### 转置 Transpose
设A为m×n阶矩阵(即m行n列),第i 行j 列的元素是a(i,j)
$$
\left[
\begin{matrix}
1 & 4 \\
2 & 5 \\
3 & 6
\end{matrix}
\right]^T
= \
\left[
\begin{matrix}
1 & 2 & 3 \\
4 & 5 & 6
\end{matrix}
\right]
$$
### 代码
```
def transpose(x: np.ndarray) -> np.ndarray:
"""矩阵转置"""
return x.T
b = np.array([
[1, 4],
[2, 5],
[3, 6],
])
transpose(b)
def transpose2(x: np.ndarray) -> np.ndarray:
"""矩阵转置"""
return x.transpose()
transpose2(b)
```
### 矩阵的行列式 Determinant
**行列式的计算必须是n*n的矩阵**
#### 2x2矩阵
$$
det(
\left[
\begin{matrix}
a & b \\
c & d
\end{matrix}
\right]) = ad-bc
$$
### 代码
```
def det(x: np.ndarray) -> np.ndarray:
"""行列式"""
return np.linalg.det(x)
a = np.array([
[1, 2],
[3, 4],
])
det(a)
```
### 逆矩阵 Inverse
### 代码
```
def inv(x: np.ndarray) -> np.ndarray:
"""矩阵求逆"""
return np.linalg.inv(x)
a = np.array([
[1, 2],
[3, 4],
])
inv(a)
def inv2(x: np.ndarray) -> np.ndarray:
"""矩阵求逆"""
# np.matrix()废弃
return np.matrix(x).I
a = np.array([
[1, 2],
[3, 4],
])
inv2(a)
```
### 矩阵的秩 Rank
### 代码
```
def rank(x: np.ndarray):
return np.linalg.matrix_rank(x)
a = np.array([
[1, 2],
[3, 4],
])
rank(a)
```
### 迹 Trace
### 代码
```
def trace(x: np.ndarray):
"""矩阵trace"""
return np.trace(x)
a = np.array([
[1, 2],
[3, 4],
])
trace(a)
```
| github_jupyter |
<a href="https://colab.research.google.com/github/JSJeong-me/2021-K-Digital-Training/blob/main/Probabilistic_Layers_Regression.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
##### Copyright 2019 The TensorFlow Probability Authors.
Licensed under the Apache License, Version 2.0 (the "License");
```
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# TFP Probabilistic Layers: Regression
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/probability/examples/Probabilistic_Layers_Regression"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/probability/blob/master/tensorflow_probability/examples/jupyter_notebooks/Probabilistic_Layers_Regression.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/probability/blob/master/tensorflow_probability/examples/jupyter_notebooks/Probabilistic_Layers_Regression.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/probability/tensorflow_probability/examples/jupyter_notebooks/Probabilistic_Layers_Regression.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
In this example we show how to fit regression models using TFP's "probabilistic layers."
### Dependencies & Prerequisites
```
#@title Import { display-mode: "form" }
from pprint import pprint
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import tensorflow.compat.v2 as tf
tf.enable_v2_behavior()
import tensorflow_probability as tfp
sns.reset_defaults()
#sns.set_style('whitegrid')
#sns.set_context('talk')
sns.set_context(context='talk',font_scale=0.7)
%matplotlib inline
tfd = tfp.distributions
```
### Make things Fast!
Before we dive in, let's make sure we're using a GPU for this demo.
To do this, select "Runtime" -> "Change runtime type" -> "Hardware accelerator" -> "GPU".
The following snippet will verify that we have access to a GPU.
```
if tf.test.gpu_device_name() != '/device:GPU:0':
print('WARNING: GPU device not found.')
else:
print('SUCCESS: Found GPU: {}'.format(tf.test.gpu_device_name()))
```
Note: if for some reason you cannot access a GPU, this colab will still work. (Training will just take longer.)
## Motivation
Wouldn't it be great if we could use TFP to specify a probabilistic model then simply minimize the negative log-likelihood, i.e.,
```
negloglik = lambda y, rv_y: -rv_y.log_prob(y)
```
Well not only is it possible, but this colab shows how! (In context of linear regression problems.)
```
#@title Synthesize dataset.
w0 = 0.125
b0 = 5.
x_range = [-20, 60]
def load_dataset(n=150, n_tst=150):
np.random.seed(43)
def s(x):
g = (x - x_range[0]) / (x_range[1] - x_range[0])
return 3 * (0.25 + g**2.)
x = (x_range[1] - x_range[0]) * np.random.rand(n) + x_range[0]
eps = np.random.randn(n) * s(x)
y = (w0 * x * (1. + np.sin(x)) + b0) + eps
x = x[..., np.newaxis]
x_tst = np.linspace(*x_range, num=n_tst).astype(np.float32)
x_tst = x_tst[..., np.newaxis]
return y, x, x_tst
y, x, x_tst = load_dataset()
```
### Case 1: No Uncertainty
```
# Build model.
model = tf.keras.Sequential([
tf.keras.layers.Dense(1),
tfp.layers.DistributionLambda(lambda t: tfd.Normal(loc=t, scale=1)),
])
# Do inference.
model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.01), loss=negloglik)
model.fit(x, y, epochs=1000, verbose=False);
# Profit.
[print(np.squeeze(w.numpy())) for w in model.weights];
yhat = model(x_tst)
assert isinstance(yhat, tfd.Distribution)
#@title Figure 1: No uncertainty.
w = np.squeeze(model.layers[-2].kernel.numpy())
b = np.squeeze(model.layers[-2].bias.numpy())
plt.figure(figsize=[6, 1.5]) # inches
#plt.figure(figsize=[8, 5]) # inches
plt.plot(x, y, 'b.', label='observed');
plt.plot(x_tst, yhat.mean(),'r', label='mean', linewidth=4);
plt.ylim(-0.,17);
plt.yticks(np.linspace(0, 15, 4)[1:]);
plt.xticks(np.linspace(*x_range, num=9));
ax=plt.gca();
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
#ax.spines['left'].set_smart_bounds(True)
#ax.spines['bottom'].set_smart_bounds(True)
plt.legend(loc='center left', fancybox=True, framealpha=0., bbox_to_anchor=(1.05, 0.5))
plt.savefig('/tmp/fig1.png', bbox_inches='tight', dpi=300)
```
### Case 2: Aleatoric Uncertainty
```
# Build model.
model = tf.keras.Sequential([
tf.keras.layers.Dense(1 + 1),
tfp.layers.DistributionLambda(
lambda t: tfd.Normal(loc=t[..., :1],
scale=1e-3 + tf.math.softplus(0.05 * t[...,1:]))),
])
# Do inference.
model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.01), loss=negloglik)
model.fit(x, y, epochs=1000, verbose=False);
# Profit.
[print(np.squeeze(w.numpy())) for w in model.weights];
yhat = model(x_tst)
assert isinstance(yhat, tfd.Distribution)
#@title Figure 2: Aleatoric Uncertainty
plt.figure(figsize=[6, 1.5]) # inches
plt.plot(x, y, 'b.', label='observed');
m = yhat.mean()
s = yhat.stddev()
plt.plot(x_tst, m, 'r', linewidth=4, label='mean');
plt.plot(x_tst, m + 2 * s, 'g', linewidth=2, label=r'mean + 2 stddev');
plt.plot(x_tst, m - 2 * s, 'g', linewidth=2, label=r'mean - 2 stddev');
plt.ylim(-0.,17);
plt.yticks(np.linspace(0, 15, 4)[1:]);
plt.xticks(np.linspace(*x_range, num=9));
ax=plt.gca();
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
#ax.spines['left'].set_smart_bounds(True)
#ax.spines['bottom'].set_smart_bounds(True)
plt.legend(loc='center left', fancybox=True, framealpha=0., bbox_to_anchor=(1.05, 0.5))
plt.savefig('/tmp/fig2.png', bbox_inches='tight', dpi=300)
```
### Case 3: Epistemic Uncertainty
```
# Specify the surrogate posterior over `keras.layers.Dense` `kernel` and `bias`.
def posterior_mean_field(kernel_size, bias_size=0, dtype=None):
n = kernel_size + bias_size
c = np.log(np.expm1(1.))
return tf.keras.Sequential([
tfp.layers.VariableLayer(2 * n, dtype=dtype),
tfp.layers.DistributionLambda(lambda t: tfd.Independent(
tfd.Normal(loc=t[..., :n],
scale=1e-5 + tf.nn.softplus(c + t[..., n:])),
reinterpreted_batch_ndims=1)),
])
# Specify the prior over `keras.layers.Dense` `kernel` and `bias`.
def prior_trainable(kernel_size, bias_size=0, dtype=None):
n = kernel_size + bias_size
return tf.keras.Sequential([
tfp.layers.VariableLayer(n, dtype=dtype),
tfp.layers.DistributionLambda(lambda t: tfd.Independent(
tfd.Normal(loc=t, scale=1),
reinterpreted_batch_ndims=1)),
])
# Build model.
model = tf.keras.Sequential([
tfp.layers.DenseVariational(1, posterior_mean_field, prior_trainable, kl_weight=1/x.shape[0]),
tfp.layers.DistributionLambda(lambda t: tfd.Normal(loc=t, scale=1)),
])
# Do inference.
model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.01), loss=negloglik)
model.fit(x, y, epochs=1000, verbose=False);
# Profit.
[print(np.squeeze(w.numpy())) for w in model.weights];
yhat = model(x_tst)
assert isinstance(yhat, tfd.Distribution)
#@title Figure 3: Epistemic Uncertainty
plt.figure(figsize=[6, 1.5]) # inches
plt.clf();
plt.plot(x, y, 'b.', label='observed');
yhats = [model(x_tst) for _ in range(100)]
avgm = np.zeros_like(x_tst[..., 0])
for i, yhat in enumerate(yhats):
m = np.squeeze(yhat.mean())
s = np.squeeze(yhat.stddev())
if i < 25:
plt.plot(x_tst, m, 'r', label='ensemble means' if i == 0 else None, linewidth=0.5)
avgm += m
plt.plot(x_tst, avgm/len(yhats), 'r', label='overall mean', linewidth=4)
plt.ylim(-0.,17);
plt.yticks(np.linspace(0, 15, 4)[1:]);
plt.xticks(np.linspace(*x_range, num=9));
ax=plt.gca();
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
#ax.spines['left'].set_smart_bounds(True)
#ax.spines['bottom'].set_smart_bounds(True)
plt.legend(loc='center left', fancybox=True, framealpha=0., bbox_to_anchor=(1.05, 0.5))
plt.savefig('/tmp/fig3.png', bbox_inches='tight', dpi=300)
```
### Case 4: Aleatoric & Epistemic Uncertainty
```
# Build model.
model = tf.keras.Sequential([
tfp.layers.DenseVariational(1 + 1, posterior_mean_field, prior_trainable, kl_weight=1/x.shape[0]),
tfp.layers.DistributionLambda(
lambda t: tfd.Normal(loc=t[..., :1],
scale=1e-3 + tf.math.softplus(0.01 * t[...,1:]))),
])
# Do inference.
model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.01), loss=negloglik)
model.fit(x, y, epochs=1000, verbose=False);
# Profit.
[print(np.squeeze(w.numpy())) for w in model.weights];
yhat = model(x_tst)
assert isinstance(yhat, tfd.Distribution)
#@title Figure 4: Both Aleatoric & Epistemic Uncertainty
plt.figure(figsize=[6, 1.5]) # inches
plt.plot(x, y, 'b.', label='observed');
yhats = [model(x_tst) for _ in range(100)]
avgm = np.zeros_like(x_tst[..., 0])
for i, yhat in enumerate(yhats):
m = np.squeeze(yhat.mean())
s = np.squeeze(yhat.stddev())
if i < 15:
plt.plot(x_tst, m, 'r', label='ensemble means' if i == 0 else None, linewidth=1.)
plt.plot(x_tst, m + 2 * s, 'g', linewidth=0.5, label='ensemble means + 2 ensemble stdev' if i == 0 else None);
plt.plot(x_tst, m - 2 * s, 'g', linewidth=0.5, label='ensemble means - 2 ensemble stdev' if i == 0 else None);
avgm += m
plt.plot(x_tst, avgm/len(yhats), 'r', label='overall mean', linewidth=4)
plt.ylim(-0.,17);
plt.yticks(np.linspace(0, 15, 4)[1:]);
plt.xticks(np.linspace(*x_range, num=9));
ax=plt.gca();
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
#ax.spines['left'].set_smart_bounds(True)
#ax.spines['bottom'].set_smart_bounds(True)
plt.legend(loc='center left', fancybox=True, framealpha=0., bbox_to_anchor=(1.05, 0.5))
plt.savefig('/tmp/fig4.png', bbox_inches='tight', dpi=300)
```
### Case 5: Functional Uncertainty
```
#@title Custom PSD Kernel
class RBFKernelFn(tf.keras.layers.Layer):
def __init__(self, **kwargs):
super(RBFKernelFn, self).__init__(**kwargs)
dtype = kwargs.get('dtype', None)
self._amplitude = self.add_variable(
initializer=tf.constant_initializer(0),
dtype=dtype,
name='amplitude')
self._length_scale = self.add_variable(
initializer=tf.constant_initializer(0),
dtype=dtype,
name='length_scale')
def call(self, x):
# Never called -- this is just a layer so it can hold variables
# in a way Keras understands.
return x
@property
def kernel(self):
return tfp.math.psd_kernels.ExponentiatedQuadratic(
amplitude=tf.nn.softplus(0.1 * self._amplitude),
length_scale=tf.nn.softplus(5. * self._length_scale)
)
# For numeric stability, set the default floating-point dtype to float64
tf.keras.backend.set_floatx('float64')
# Build model.
num_inducing_points = 40
model = tf.keras.Sequential([
tf.keras.layers.InputLayer(input_shape=[1]),
tf.keras.layers.Dense(1, kernel_initializer='ones', use_bias=False),
tfp.layers.VariationalGaussianProcess(
num_inducing_points=num_inducing_points,
kernel_provider=RBFKernelFn(),
event_shape=[1],
inducing_index_points_initializer=tf.constant_initializer(
np.linspace(*x_range, num=num_inducing_points,
dtype=x.dtype)[..., np.newaxis]),
unconstrained_observation_noise_variance_initializer=(
tf.constant_initializer(np.array(0.54).astype(x.dtype))),
),
])
# Do inference.
batch_size = 32
loss = lambda y, rv_y: rv_y.variational_loss(
y, kl_weight=np.array(batch_size, x.dtype) / x.shape[0])
model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.01), loss=loss)
model.fit(x, y, batch_size=batch_size, epochs=1000, verbose=False)
# Profit.
yhat = model(x_tst)
assert isinstance(yhat, tfd.Distribution)
#@title Figure 5: Functional Uncertainty
y, x, _ = load_dataset()
plt.figure(figsize=[6, 1.5]) # inches
plt.plot(x, y, 'b.', label='observed');
num_samples = 7
for i in range(num_samples):
sample_ = yhat.sample().numpy()
plt.plot(x_tst,
sample_[..., 0].T,
'r',
linewidth=0.9,
label='ensemble means' if i == 0 else None);
plt.ylim(-0.,17);
plt.yticks(np.linspace(0, 15, 4)[1:]);
plt.xticks(np.linspace(*x_range, num=9));
ax=plt.gca();
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
#ax.spines['left'].set_smart_bounds(True)
#ax.spines['bottom'].set_smart_bounds(True)
plt.legend(loc='center left', fancybox=True, framealpha=0., bbox_to_anchor=(1.05, 0.5))
plt.savefig('/tmp/fig5.png', bbox_inches='tight', dpi=300)
```
| github_jupyter |
# Helpful Basics <a class="anchor" id="top"></a>
- **Prepared by:**
- [Yalin Li](https://qsdsan.readthedocs.io/en/latest/authors/Yalin_Li.html)
- [Joy Zhang](https://qsdsan.readthedocs.io/en/latest/authors/Joy_Zhang.html)
- **Covered topics:**
- [1. Python and Jupyter Notebook](#s1)
- [2. import qsdsan](#s2)
- **Video demo:**
- [Yalin Li](https://qsdsan.readthedocs.io/en/latest/authors/Yalin_Li.html)
To run tutorials in your browser, go to this [Binder page](https://mybinder.org/v2/gh/QSD-Group/QSDsan/main?filepath=%2Fdocs%2Fsource%2Ftutorials).
You can also watch a video demo on [YouTube](https://www.youtube.com/watch?v=g8mXWycdi4E) (subscriptions & likes appreciated!).
## 1. Python and Jupyter Notebook <a class="anchor" id="s1"></a>
- Launching Python through Jupyter Notebook
- Tutorial from [Software Carpentry](https://swcarpentry.github.io/python-novice-inflammation/setup.html)
- For people who are using PyCharm, follow this [post](https://www.caitlincasar.com/post/pycharm/) to install and run Jupyter Notebook (either in PyCharm or in your browser)
- You can certainly [install Jupyter Notebook individually](https://jupyter.org/install), but you might need to adjust your system path to ensure packages can be properly loaded.
- Make new notebooks
- Code vs. Markdown cells
- Edit/escape, copy/cut, insert, delete
- Simple Markdown syntax
- For more cheatsheets on Markdown (and markup languages), check out the Supplementary Material module of [QSDedu](https://github.com/QSD-Group/QSDedu)
- Close notebook and quit Jupyter Notebook
---
### Note
It's OK if you don't have Jupyter Notebook, you can launch Python through IDEs like PyCharm or [Spyder](http://spyder-ide.org) (or just terminal/command prompt if you prefer) and follow the tutorials.
---
[Back to top](#top)
## 2. import qsdsan <a class="anchor" id="#s2"></a>
```
# When I do `import qsdsan`, how does Python know where to look for qsdsan?
# This is the same as `import qsdsan`, then `qs1 = qsdsan`
import qsdsan as qs1
print(f'Path for the first qsdsan package is {qs1.__path__}.')
```
---
### Tip
The 'f' prefix stands for "fancy print", it allows the plain print function to look nicer. It's a feature of newer Python, before this, you either have to do:
```
info = 'Path for the first qsdsan package is ' + str(qs1.__path__) + '.'
print(info)
# `print('Path for the first qsdsan package is', qs1.__path__, '.')` works as well
```
Or use something like this:
```
print('Path for the first qsdsan package is {}.'.format(qs1.__path__))
```
Or this:
```
print('Path for the first qsdsan package is %s.' % qs1.__path__)
```
---
```
# When doing importing, Python will look into the directories (i.e., folders) in the order of the `sys.path` list
import os, sys
print(sys.path)
# That's way too ugly, let's do it in a nicer way
for i in sys.path:
print(i)
# If Python cannot find the package from any of those directories, it will complain something like
# uncomment the following to try
# import happy_wednesday
```
If you're a developer of qsdsan, you probably have cloned the qsdsan repository on Github to a local folder (let's say, `cloned_path`). So if you want to import the cloned/local version of qsdsan (i.e., the one you're developing rather than the stable version released on [pypi](https://pypi.org/project/qsdsan/)), you need to ensure that:
1. `cloned_path` is in `sys.path`
2. `cloned_path` is of higher priority (e.g., in front of) the pip-installed path, which is usually the one that has "site-packages")
```
# Currently cloned_path is not in `sys.path`, so we will use the `insert` function to insert it
# but what if I don't know how to use that function?
# then try this
sys.path.insert?
# Or this (which is more verbose)
help(sys.path.insert)
```
---
### Tip
If you look closer, you'll find that the help info says "insert(index, object, /) method of **builtins.list** instance", not "insert(index, object, /) method of **sys.path**".
This is because `sys.path` is an instance of the `list` class, and so it automatically "inherits" all the methods (i.e., functions) that are associated with a `list` object, and that is (imo) one of the biggest feature/advantage of object orientated programming (OOP).
You may note that I sometimes refer list as a "class" but sometimes as an "object". Both are correct, because in OOP languages everything is an object.
But "instance" and "class" cannot be used interchangably, "instance" is, as the name suggests, a practical example of the "class".
E.g., you can think of me as a postdoc, since I have the common attributes of a postdoc (have a Ph.D. degree thus permanent head damage, etc.), but you cannot equate me to the entire postdoc "class".
There is much more to "class", e.g., one subclass (and instances of that subclass) can inherit attributes from all of its super classes (sub/super sometimes referred to as child/parent). Just like I can also belong to another class called "cat-owner", the "instances" (i.e., member) of which all have cat(s) and suffer from grumpy litter-generator creatures like this:
```
from IPython.display import Image
Image(url='https://upload.wikimedia.org/wikipedia/commons/d/dc/Grumpy_Cat_%2814556024763%29_%28cropped%29.jpg', width=200)
# So how do I know `sys.path` is a list?
type(sys.path)
# And another built-in function we often use in `if` statement is
isinstance(sys.path, list)
# E.g.
if isinstance(sys.path, list):
print('sys.path is a list.')
else:
print('sys path is NOT a list')
# To make it fancier, (and show off some advanced Python tips), we can change it to a one-liner,
# this is exactly the same as the `if... else...` statement above
info = 'sys.path is a list.' if isinstance(sys.path, list) else 'sys.path is NOT a list.'
print(info)
# Since we have gone into the rabbit hole, why not use fancy print?
print(f'The statement that "sys.path is a list" is {isinstance(sys.path, list)}.')
```
Then there are another whole set of issues related to method resolution order (`mro`, i.e., which of the super classes' attributes take priority over others), etc., but that's for advanced Python, and we'll skip this topic now.
---
**Note:**
We need to restart the kernel at this moment, or the already imported, pip-installed `qsdsan` will always be there.
```
# Now I'll attempt to import another qsdsan (cloned the GitHub version) on my computer,
# firstly you need to figure out where that is (i.e., where you cloned it to)
# demo on how to find it
cloned_path = '/Users/yalinli_cabbi/onedrive/coding/qs'
# Then let's insert the cloned path into our system path
# remember to restart the kernel
import sys
sys.path.insert(0, cloned_path)
sys.path
```
You can see that the first path is the cloned path
```
# So now let's try this importing again
import qsdsan as qs2
print(f'Path for the second qsdsan package is {qs2.__path__}.')
```
So we successfully import qsdsan from another place
**Note:**
The changes to `sys.path` is temporary, so if we restart the kernel and recheck the path:
```
# Our previous added cloned_path is gone
import sys
sys.path
# If we try to import again
import qsdsan as qs3
qs3
```
We are now back to the pip-installed `qsdsan` :)
```
# Finally, if you want to see which version of the qsdsan you are running
qs3.__version__
```
[Back to top](#top)
| github_jupyter |
<img src="https://raw.githubusercontent.com/Qiskit/qiskit-tutorials/master/images/qiskit-heading.png" alt="Note: In order for images to show up in this jupyter notebook you need to select File => Trusted Notebook" width="500 px" align="left">
## _*Quantum Battleships with partial NOT gates*_
The latest version of this notebook is available on https://github.com/qiskit/qiskit-tutorial.
***
### Contributors
James R. Wootton, University of Basel
***
This program aims to act as an introduction to qubits, and to show how single-qubit operations can be used. Specifically, we'll use them to implement a game.
The game is based on the Japanese version of 'Battleships'. In this, each ship takes up only a single location.
Each player will place three ships in the following five possible locations, which correspond to the five qubits of the ibmqx4 device.
<pre>
4 0
|\ /|
| \ / |
| \ / |
| 2 |
| / \ |
| / \ |
|/ \|
3 1
</pre>
The players then fire bombs at each other's grids until one player loses all their ships.
The first ship placed by each player takes 1 bomb to destroy. The second ship takes 2, and the third takes 3.
The game mechanic is realized on a quantum computer by using a qubit for each ship, and using partial NOT gates (rotations around the Y axis) as the bombs. A full NOT is applied when the right number of bombs have hit a given ship, rotating the qubit/ship from 0 (undamaged) to 1 (destroyed).
Some details on implementation can be found in the Markdown cells. A full tutorial for how to program the game can be found at
https://medium.com/@decodoku/how-to-program-a-quantum-computer-982a9329ed02
If you are using the real device, here is a simple description of the game you can read while waiting for the jobs to finish.
https://medium.com/@decodoku/quantum-computation-in-84-short-lines-d9c7c74be0d0
If you just want to play, then select 'Restart & Run All' from the Kernel menu.
<br>
<br>
First we import what we'll need to run set up and run the quantum program.
```
from qiskit import IBMQ
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit import execute
```
Next we need to import *Qconfig*, which is found in the parent directory of this tutorial. Note that this will need to be set up with your API key if you haven't done so already.
After importing this information, it is used to register with the API. Then we are good to go!
```
# Load the saved IBMQ account
IBMQ.load_account()
```
Any quantum computation will really be a mixture of parts that run on a quantum device, and parts that run on a conventional computer. In this game, the latter consists of jobs such as getting inputs from players, and displaying the grid. The scripts for these are kept in a separate file, which we will import now.
```
import sys
sys.path.append('game_engines')
from battleships_engine import *
```
Now it's time for a title screen.
```
title_screen()
```
The player is now asked to choose whether to run on the real device (input *y* to do so).
The real device is awesome, of course, but you'll need to queue behind other people sampling its awesomeness. So for a faster experience, input *n* to simulate everything on your own (non-quantum) device.
```
device = ask_for_device()
```
The first step in the game is to get the players to set up their boards. Player 1 will be asked to give positions for three ships. Their inputs will be kept secret. Then the same for player 2.
```
shipPos = ask_for_ships()
```
The heart of every game is the main loop. For this game, each interation starts by asking players where on the opposing grid they want to bomb. The quantum computer then calculates the effects of the bombing, and the results are presented to the players. The game continues until all the ships of one player are destroyed.
```
# the game variable will be set to False once the game is over
game = True
# the variable bombs[X][Y] will hold the number of times position Y has been bombed by player X+1
bomb = [ [0]*5 for _ in range(2)] # all values are initialized to zero
# set the number of samples used for statistics
shots = 1024
# the variable grid[player] will hold the results for the grid of each player
grid = [{},{}]
while (game):
# ask both players where they want to bomb, and update the list of bombings so far
bomb = ask_for_bombs( bomb )
# now we create and run the quantum programs that implement this on the grid for each player
qc = []
for player in range(2):
# now to set up the quantum program to simulate the grid for this player
# set up registers and program
q = QuantumRegister(5)
c = ClassicalRegister(5)
qc.append( QuantumCircuit(q, c) )
# add the bombs (of the opposing player)
for position in range(5):
# add as many bombs as have been placed at this position
for n in range( bomb[(player+1)%2][position] ):
# the effectiveness of the bomb
# (which means the quantum operation we apply)
# depends on which ship it is
for ship in [0,1,2]:
if ( position == shipPos[player][ship] ):
frac = 1/(ship+1)
# add this fraction of a NOT to the QASM
qc[player].u3(frac * math.pi, 0.0, 0.0, q[position])
# Finally, measure them
for position in range(5):
qc[player].measure(q[position], c[position])
# compile and run the quantum program
job = execute(qc, backend=device, shots=shots)
if not device.configuration().to_dict()['simulator']:
print("\nWe've now submitted the job to the quantum computer to see what happens to the ships of each player\n(it might take a while).\n")
else:
print("\nWe've now submitted the job to the simulator to see what happens to the ships of each player.\n")
# and extract data
for player in range(2):
grid[player] = job.result().get_counts(qc[player])
game = display_grid ( grid, shipPos, shots )
```
## <br>
<br>
If you are reading this while running the game, you might be wondering where all the action has gone. Try clicking on the white space to the left of the output in the cell above to open it up.
```
keywords = {'Topics': ['Games', 'NOT gates'], 'Commands': ['`u3`']}
```
| github_jupyter |
## Univariate Analysis vs Bivariate Analysis vs Multivariate Analysis
- Please refer below youtube Link for in depth explanation
https://youtu.be/w_Tm-H-emRo
**What question(s) are we trying to solve?**
predicts which passengers survived in the Titanic shipwreck.
Dataset is Titanic Datset. > https://www.kaggle.com/c/titanic/data
```
#Survived Survived (1) or died (0)
#Pclass Passenger’s class
#Name Passenger’s name
#Sex Passenger’s sex
#Age Passenger’s age
#SibSp Number of siblings/spouses aboard
#Parch Number of parents/children aboard
#Ticket Ticket number
#Fare Fare
#Cabin Cabin
#Embarked Port of embarkation
```
- Variable Identification
- Univariate Analysis
- Bivariate Analysis
- Multivariate Analysis
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style(style="darkgrid")# "whitegrid")
%matplotlib inline
# use this command so that your plots appear inline in your notebook
from platform import python_version
print("python",python_version())
print('\n'.join(f'{m.__name__} {m.__version__}' for m in globals().values() if getattr(m, '__version__', None)))
## Lets First Load the Train
df_train = pd.read_csv("https://raw.githubusercontent.com/atulpatelDS/Data_Files/master/Titanic/titanic_train.csv")
df_train.head()
## Use PassengerId as Index
df_train = df_train.set_index("PassengerId")
df_train.head()
```
### Variable Identification
**1. First, identify Predictor (Input) and Target (output) variables**
```
# We have to predict whether the passenger is survived or not so our target(Output) variable will be "Survived"
# and remaiming columns will be Predictors(Input variables)
y = targets = labels = output_var = df_train["Survived"]
X = predictors = input_var = df_train.loc[:,df_train.columns != "Survived"]
y.head()
X.head()
# Print the Target and Input Variables
print("Input Variables", list(X.columns))
print("Output Variable", "['Survived']")
```
**2. Identify the data type of the variables.**
```
df_train.info()
datatype = df_train.dtypes
#col = datatype[(datatype == 'object') | (datatype == 'int64')| (datatype == 'float64')].index.tolist()
num_col = datatype[(datatype == 'float64') | (datatype == 'int64')].index.tolist()
cat_col = datatype[(datatype == 'object')].index.tolist()
print("Categorical Columns :",cat_col)
print("Numerical Columns :",num_col)
df_train.head(2)
```
## Univariate Analysis
1. We explore variables one by one.
2. Method to perform uni-variate analysis will depend on whether the variable type is categorical or continuous.
**Continuous Variable Analysis**
- Measure of central tendency(Mean, Median, Mode) of the variable.
- Measure of spread(Range,IQR, Variance,Standard Deviation) of the variable.
- Measure of Shape(Symmetrical Distribution e.g. Normal Distribution,Asymmetrical Distribution (Left or Right Skewed Distribution),Kurtosis(shape of the of the distribution in terms of height or flatness)
**Categorical Variable Analysis**
- For categorical variables, we will use frequency distribution of each category.e.g Bar Chart, Pie Chart
```
# Run discriptive statistics of numerical datatypes.
df_train.describe(include = ['float64','int64'])
# Lets Analysis the Target Variable "Survived"
# Calculate the percentage of people who Survived and Not Survived
df_train["Survived"].value_counts()
per_sur_nonsur = (df_train["Survived"].value_counts()/df_train.shape[0]*100).round(2)
per_sur_nonsur
# 0 > not-Survived
# 1 > Survived
```
**A count plot can be thought of as a histogram across a categorical, instead
of quantitative, variable.**
```
# Lets plot the graph who are survided and not survied as per the column data
sns.countplot(data=df_train,x="Survived")
# Lets Display Count on top of countplot
fig, ax1 = plt.subplots(figsize=(5,5))
graph = sns.countplot(ax=ax1,x='Survived', data=df_train)
graph.set_xticklabels(graph.get_xticklabels(),rotation=90)
for p in graph.patches:
height = p.get_height()
graph.text(p.get_x()+p.get_width()/2., height + 0.1,height ,ha="center")
# If we want to display the percentage
from matplotlib.pyplot import show
titanic = df_train
total = float(len(titanic)) # one person per row
#ax = sns.barplot(x="class", hue="who", data=titanic)
#ax = sns.countplot(x="class", hue="who", data=titanic) # for Seaborn version 0.7 and more
ax = sns.countplot(x="Survived", data=titanic) # for Seaborn version 0.7 and more
for p in ax.patches:
height = p.get_height()
ax.text(p.get_x()+p.get_width()/2.,
height + 3,
'{:1.2f}'.format(height/total),
ha="center")
show()
df_train.info()
df_train.Pclass.unique()
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning) # supress future warning
# Combined univariate analysis of each variables
fig,axes = plt.subplots(2,4, figsize=(16,10))
sns.countplot('Survived',data=df_train,ax=axes[0,0])
sns.countplot('Pclass',data=df_train,ax=axes[0,1])
sns.countplot('Sex',data=df_train,ax=axes[0,2])
sns.countplot('SibSp',data=df_train,ax=axes[0,3])
sns.countplot('Parch',data=df_train,ax=axes[1,0])
sns.countplot('Embarked',data=df_train,ax=axes[1,1])
#sns.distplot(df_train['Fare'], kde=True,ax=axes[1,2])
sns.histplot(data=df_train,x="Fare",ax=axes[1,2])
sns.histplot(data=df_train,x="Age",ax=axes[1,3] )
```
Univariate analysis is also used to highlight missing and outlier values. We will look at methods to handle missing and outlier values when we will perform the Data Cleaning part.
## Bivariate Analysis
1. We perform bi-variate analysis with 2 variables for any combination of categorical and continuous variables.
3. The combination can be: Categorical & Categorical, Categorical & Continuous and Continuous & Continuous.
4. Different methods are used to tackle these combinations during analysis process.
```
# Lets more elaborate survived data with sex and we will use catplot or countplot
'''
fig, ax1 = plt.subplots(figsize=(5,5))
graph = sns.countplot(ax=ax1,x='Sex',hue="Survived",data=df_train)
graph.set_xticklabels(graph.get_xticklabels(),rotation=90)
for p in graph.patches:
height = p.get_height()
graph.text(p.get_x()+p.get_width()/2., height + 0.1,height ,ha="center")
'''
sns.catplot(x="Sex",col="Survived",data=df_train, kind="count",height=4, aspect=.7)
```
We can clearly see that male survial rates is around 19% where as female survial rate is about 75% which suggests that gender has a strong relationship with the survival rates.
```
sns.catplot(x='Survived',hue="Sex",data=df_train,kind = "count")
# Lets more elaborate survived data with Pclass
#sns.countplot(data=df_train,x = "Survived",hue="Pclass",palette="rainbow")
fig, ax1 = plt.subplots(figsize=(8,5))
graph = sns.countplot(ax=ax1,data=df_train,x = "Survived",hue="Pclass",palette="rainbow")
graph.set_xticklabels(graph.get_xticklabels(),rotation=90)
for p in graph.patches:
height = p.get_height()
graph.text(p.get_x()+p.get_width()/2., height + 0.1,height ,ha="center")
# Lets more elaborate survived data with Pclass and we will use countplot
fig, ax1 = plt.subplots(figsize=(8,5))
graph = sns.countplot(ax=ax1,data=df_train,x = "Pclass",hue="Survived",palette="rainbow")
graph.set_xticklabels(graph.get_xticklabels(),rotation=90)
for p in graph.patches:
height = p.get_height()
graph.text(p.get_x()+p.get_width()/2., height + 0.1,height ,ha="center")
```
There is also a clear relationship between Pclass and the survival by referring to above plot. Passengers on Pclass1 has a better survial rate of approx 62% whereas passengers on pclass3 had the worst survial rate of approx 25%
```
##display Sibling with sex data
#sns.catplot(data=df_train,x="SibSp",hue = "Sex", kind = "count",height=4)
g = sns.catplot(data=df_train,x="SibSp",hue = "Sex", kind = "count",height=4,legend=True)
g.fig.set_size_inches(12,8)
g.fig.subplots_adjust(top=0.81,right=0.86)
ax = g.facet_axis(0,0)
for p in ax.patches:
ax.text(p.get_x() - 0.01,
p.get_height() * 1.02,
'{0:.0f}'.format(p.get_height()),
color='red',
rotation='horizontal',
size='large')
## Lets analyse survided corresponding to Age
df_train.boxplot(column="Age",by="Survived")
# Plotting a boxplot between 'Survived' and 'Fare' Columns
import matplotlib.patheffects as path_effects
fig, ax1 = plt.subplots(figsize=(10,7))
def main():
sns.set_style("whitegrid")
tips = df_train
# optionally disable fliers
showfliers = True
# plot data and create median labels
box_plot = sns.boxplot(ax=ax1, x='Survived', y='Fare',
#hue='Sex',
data=df_train,
showfliers=showfliers)
create_median_labels(box_plot.axes, showfliers)
plt.show()
def create_median_labels(ax, has_fliers):
lines = ax.get_lines()
# depending on fliers, toggle between 5 and 6 lines per box
lines_per_box = 5 + int(has_fliers)
# iterate directly over all median lines, with an interval of lines_per_box
# this enables labeling of grouped data without relying on tick positions
for median_line in lines[4:len(lines):lines_per_box]:
# get center of median line
mean_x = sum(median_line._x) / len(median_line._x)
mean_y = sum(median_line._y) / len(median_line._y)
# print text to center coordinates
text = ax.text(mean_x, mean_y, f'{mean_y:.1f}',
ha='center', va='center',
fontweight='bold', size=10, color='white')
# create small black border around white text
# for better readability on multi-colored boxes
text.set_path_effects([
path_effects.Stroke(linewidth=3, foreground='black'),
path_effects.Normal(),
])
if __name__ == '__main__':
main()
```
There is also a marginal relationship between the fare and survial rate
**Continous Variable vs Continous Variable**
```
## Plot Fare Distribution Across Age usinf scatter plot
sns.scatterplot(x = df_train["Age"],y = df_train["Fare"])
## Plot Fare Distribution Across Age usinf Joint plot
sns.jointplot(x="Age",y="Fare",data=df_train)
```
## Multivariate Analysis
1. We perform multivariate analysis with more than 2 variables for any combination of categorical and continuous variables.
2. The combination can be: Categorical & Categorical, Categorical & Continuous and Continuous & Continuous.
3. Different methods are used to tackle these combinations during analysis process.
```
fig, ax1 = plt.subplots(figsize=(8,5))
testPlot = sns.boxplot(ax=ax1, x='Pclass', y='Age', hue='Sex', data=df_train)
import matplotlib.patheffects as path_effects
fig, ax1 = plt.subplots(figsize=(10,7))
def main():
sns.set_style("whitegrid")
tips = df_train
# optionally disable fliers
showfliers = True
# plot data and create median labels
box_plot = sns.boxplot(ax=ax1, x='Pclass', y='Age', hue='Sex', data=df_train,
showfliers=showfliers)
create_median_labels(box_plot.axes, showfliers)
plt.show()
def create_median_labels(ax, has_fliers):
lines = ax.get_lines()
# depending on fliers, toggle between 5 and 6 lines per box
lines_per_box = 5 + int(has_fliers)
# iterate directly over all median lines, with an interval of lines_per_box
# this enables labeling of grouped data without relying on tick positions
for median_line in lines[4:len(lines):lines_per_box]:
# get center of median line
mean_x = sum(median_line._x) / len(median_line._x)
mean_y = sum(median_line._y) / len(median_line._y)
# print text to center coordinates
text = ax.text(mean_x, mean_y, f'{mean_y:.1f}',
ha='center', va='center',
fontweight='bold', size=10, color='white')
# create small black border around white text
# for better readability on multi-colored boxes
text.set_path_effects([
path_effects.Stroke(linewidth=3, foreground='black'),
path_effects.Normal(),
])
if __name__ == '__main__':
main()
# Lets more elaborate survived data with Pclass and sex and we will use catplot
sns.catplot(data=df_train,col = "Survived",x = "Sex", hue="Pclass",kind = "count")
g = sns.catplot(data=df_train,col = "Survived",x = "Sex", hue="Pclass",kind = "count",legend=True)
g.fig.set_size_inches(8,5)
g.fig.subplots_adjust(top=0.81,right=0.86)
ax = g.facet_axis(0,0)
for p in ax.patches:
ax.text(p.get_x() - 0.01,
p.get_height() * 1.02,
'{0:.1f}'.format(p.get_height()),
color='red',
rotation='horizontal',
size='large')
## Co-relation matrix
fig,ax = plt.subplots(figsize = (10,6))
corr = df_train.corr()
sns.heatmap(corr,annot=True)
```
From the above grapg we can say that there is a positve coorelation between Fare and Survived and a negative coorelation between Pclass and Surived. Also there is a negative coorelation between Fare and Pclass, Age and Plcass.
```
sns.pairplot(df_train)
```
### Data Cleaning
**1. Handling Dulicate Data**
```
# If you use the method sum() along with it, then it will return the total number of the duplicates in the dataset
df_train.duplicated().sum()
```
**2. Handling missing value (Categorical Data and Numerical Data)**
```
#df_train.isnull()
sns.heatmap(df_train.isnull(),yticklabels=False,cbar=False, cmap="viridis")
# From the below graph it is cleary visible that most of the null values are available in colun AGE and CABIN
# lets find out the percentage of misssing vale in each column
percent_missing = df_train.isnull().sum() * 100 / len(df_train)
missing_value_df = pd.DataFrame({'column_name': df_train.columns,
'percent_missing': percent_missing})
missing_value_df
```
As we see from above that AGE data is only mising around 20% and we have to find that can we replace these Nan value
with some other value . So we need to find how can we replace these?.
```
# Now we will drop these missing value
df_train1=df_train.dropna(subset=["Age","Embarked"],axis=0).copy()
df_train1.shape
percent_missing = df_train1.isnull().sum() * 100 / len(df_train1)
missing_value_df1 = pd.DataFrame({'column_name': df_train1.columns,
'percent_missing': percent_missing})
missing_value_df1
df_train1.drop("Cabin",axis=1,inplace=True)
df_train1.head(2)
percent_missing = df_train1.isnull().sum() * 100 / len(df_train1)
missing_value_df1 = pd.DataFrame({'column_name': df_train1.columns,
'percent_missing': percent_missing})
missing_value_df1
```
**3. Handling Outliers**
```
df_train1["Age"].describe()
fig, (ax1, ax2) = plt.subplots(ncols=2, sharey=True,figsize = (20,4))
sns.boxplot(x="Age",data=df_train1,ax=ax1)
sns.boxplot(x="Fare",data=df_train1,ax=ax2)
from scipy.stats import norm
f, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw= {"height_ratios": (0.5, 1)})
median=df_train1.Age.median()
mean=df_train1.Age.mean()
std = df_train1.Age.std()
upper_limit = mean + std*3
lower_limit = mean - std*3
print("upper_limit : ", upper_limit)
print("lower_limit : ",lower_limit)
sns.boxplot(df_train1["Age"], ax=ax_box)
ax_box.axvline(mean, color='b', linestyle='--')
sns.distplot(df_train1["Age"], ax=ax_hist,kde=False,norm_hist=True)
ax_hist.axvline(lower_limit, color='r', linestyle='--')
ax_hist.axvline(mean, color='b', linestyle='-')
ax_hist.axvline(upper_limit, color='r', linestyle='--')
plt.legend({'Mean':mean})
ax_box.set(xlabel='')
x = np.linspace(mean - 3*std, mean + 3*std, 100)
plt.plot(x, norm.pdf(x, mean, std))
plt.legend({"lower_limit":lower_limit,'Mean':mean,'upper_limit':upper_limit})
print("Mean Value : ",mean)
print("Median Value : ",median)
print("1st Standard Deviation : ",std)
plt.show()
df_train1_Age_outlier = df_train1[(df_train1.Age>upper_limit) | (df_train1.Age<lower_limit)]
df_train1_Age_outlier
#assigning nan to the outliers
df_train1['Age'].values[df_train1['Age'] > upper_limit] = np.nan
df_train1['Age'].values[df_train1['Age'] < lower_limit] = np.nan
df_train1.isnull().sum()
#imputing nan values with mean value
#df_train1['Age']=df_train1.Age.fillna(df_train1.Age.mean())
# As we are preparing our base model and outlier values are also very few so we will delete these outlier values
df_train1.dropna(inplace=True)
df_train1.isnull().sum()
df_train1.shape
```
| github_jupyter |
# Live Analysis of Performance in Cricket Matches
### A tutorial by Avi Ganguli
## Introduction
Cricket is a sport with a surprising but profound connection with the United States. To the surprise of many cricket fans around the world and sports fans in the United States, the first international match in cricket history was held in Bloomingdale Park in New York in the Fall of 1844. However, since then, cricket in the United States has lost its way and instead been replaced by a conceptually similar yet fundamentally different sport in baseball. It may be helpful to look at the Wikipedia page for cricket, https://en.wikipedia.org/wiki/Cricket.
Cricket is a sport which generates a large amount of statistics each match. Matches can last upto 5 days and involve a rotation of several roles (batting, bowling and fielding) each with it's own distinct set of independent parameters to judge by. This data is then very well tabulated and recorded by a group of cricket sites which provide an excellent online coverage of cricket while their commentators also combine useful match insights and statistics with ball by ball coverage and description of match action. Perhaps, the foremost of these websites, ESPN Cricinfo is the site we will be using to gather data for this demonstration. However, much of the statistical analysis of the game is done after the conclusion of a match or the end of the day. Here, we aim to combine existing data and live data to make meaningful inferences about the result of the game and the performance of both teams. The API that we will be using to do this, `python-espncricinfo`, fetches the data on ESPN Cricinfo and presents it in a easy-to-use manner.
## Getting Started
First, let's try to install the API so we can get started. To install `python-espncricinfo` (not in Anaconda by default): `pip install python-espncricinfo`
You may have to remove the following lines in the match.py file:
`from espncricinfo.exceptions import MatchNotFoundError, NoScorecardError`
and the following lines in the get_json method:
`if r.status_code == 404:
raise MatchNotFoundError
elif 'Scorecard not yet available' in r.text:
raise NoScorecardError`
Now, let's get acquainted with the API by getting some basic data. The API has three basic classes that should be introduced first.
```
from espncricinfo.player import Player
from espncricinfo.summary import Summary
from espncricinfo.match import Match
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn # or alternatively plt.style.use('ggplot') for a similar look
import numpy as np
import math
from textwrap import fill
matplotlib.rc("figure", figsize=(8,6))
matplotlib.rc("axes", labelsize=16, titlesize=16)
matplotlib.rc("xtick", labelsize=14)
matplotlib.rc("ytick", labelsize=14)
matplotlib.rc("legend", fontsize=14)
matplotlib.rc("font", size=14)
```
## Overview of ESPNCricinfo API
These three classes are rather self-explanatory. The Player class contains highly detailed information about a specific player and thus contains many different attributes of which we will only be using a select few. The Summary class provides information about live/recent matches and allows us to make insights about on-going/recently concluded matches. The Matches class gives us detailed information about a given match and also containts a myriad of attributes, most of which will not be used here.
Let us take a look at some basic features these classes provide.
```
major_countries = set(["Australia", "Sri Lanka", "West Indies", "Zimbabwe", "New Zealand",
"India", "Pakistan", "Bangladesh", "South Africa", "England"])
```
The above 10 countries represent the countries with teams that are considered to compete at the highest level.
```
#gets on-going matches that involve one of the major teams defined above
def get_major_current_matches():
summary = Summary()
major_matches = []
for match in summary.all_matches:
if match["team1_name"] in major_countries or match["team2_name"] in major_countries:
major_matches.append(match)
return major_matches
current_major_matches = get_major_current_matches()
print current_major_matches
```
The above code looks in the current matches being played avaliable through the Summary object and finds all those that involve the countries we defined to be major. Note that this data is live. As we can see above, there is a match going on now between Pakistan and West Indies that we have got the data for. Let's try to do something more interesting with this.
```
#parses the given url and obtains match id
def parse_url(summary_dict):
url = summary_dict["url"]
parsed_url_arr = url.rsplit('/', 1)
parsed_w_ext = parsed_url_arr[-1]
parsed_w_ext_arr = parsed_w_ext.split('.')
parsed_url = parsed_w_ext_arr[0]
return parsed_url
```
Now that we have a helper function that allows us to get the match id from the url, we can use the Match object to get some more detailed information about the current major matches.
```
#gets match objects from list of summary dictionaries
def get_matches(summary_matches):
result = []
for match_dict in summary_matches:
match_id = parse_url(match_dict)
try: #account for errors in API
match = Match(match_id)
result.append(match)
except:
continue
return result
#gets rosters for teams playing in match
def get_rosters(match):
return ([player["card_long"] for player in match.team_1["player"]],
[player["card_long"] for player in match.team_2["player"]])
matches = get_matches(current_major_matches)
for match in matches:
match_info = match.description
match_class = match.match_class
rosterA, rosterB = get_rosters(match)
print "Team 1: " + match.team_1["team_name"] + "\n" + "\n".join(rosterA)
print "Team 2: " + match.team_2["team_name"] + "\n" + "\n".join(rosterB)
print "Location: " + match.ground_name + ", " + match.town_name
print "Series: " + match.series[0]["series_name"]
#Consider one match for now
match = matches[0]
rosterA, rosterB = get_rosters(matches[0])
```
Now, we have a list match objects and a plethora of information as we see above where we obtained the team rosters, location and series name. However, let's analyze the most recent match for now. We haven't really gotten into the in-depth quantitiative data yet. The Player class helps us do that as shown below.
```
#returns player data for given name and team if available
def get_Player(playerName, team):
for player in team["player"]:
if player["card_long"] == playerName:
pid = player["object_id"]
try:
#data not available at moment : API problem
result = Player(pid)
except:
result = None
return result
return None
#populate teams with available player data
def populate_team(roster, team, objects):
result = []
for name in roster:
player = get_Player(name, team)
if player!=None: #no data: API error
objects.append(player)
player_name = player.name
role = player.playing_role
if role!=None: #no role data available'
role = player.playing_role
else:
role = "Not available"
result.append((player_name, role))
return result
teamA_objects = []
teamB_objects = []
teamA_players = populate_team(rosterA, match.team_1, teamA_objects)
teamB_players = populate_team(rosterB, match.team_2, teamB_objects)
print teamA_players, len(teamA_players)
print teamB_players, len(teamB_players)
```
## Classification
Now, that we have the player objects and we've seen what they can do, we saw that we can get some useful information about them. Just the player names and roles can give us a starting point for analysis. Let's go through some basic things first though as you'll be seeing these terms throughout the analysis. There are three major roles in cricket: Batsmen, Bowler and Allrounder. These represent the two major parts of cricket and where they specialize in, batting and bowling or in the case of allrounders both. These roles are the second element of the list of tuples we see above. As you may have read in the wikipedia article, cricket is a game of 11 members per team so you may be surprised why we have less than 11. The answer is rather tame: we simply do not have data for these players due to inadequacies in the API. Let's get back to the discussion on roles. For batting, we will be considering one major metric for every player, their average which determines how many runs they score every match. For bowlers, we look at both the runs they conceded and balls they bowl before they succeed in getting a batsmen out. As allrounders are a unique case, we use the difference between their batting average and bowling average as a measure of their skill. Now, let's classify try to show this in the data we collected.
```
#guess role when role data is absent
def guess_role(player):
count = 0
bat_avg = 0
bowl_avg = 0
for data in player.batting_fielding_averages:
for level, average in data.iteritems():
bat_avg+=float(average[5][1]) #average is in the 6th index
count+=1
bat_avg/= count if count > 0 else 1
count = 0
for data in player.bowling_averages:
for level, average in data.iteritems():
bowl_avg+=float(average[7][1]) #average is in the 7th index
count+=1
bowl_avg/= count if count > 0 else 1
if bat_avg > 20 and bowl_avg < 40:
return "allrounder"
if bowl_avg < 40:
return "bowler"
if bat_avg > 20:
return "batsman"
else:
return "allrounder"
#classifies all players and divides them into classifications
def classify_players(player_objects):
batsmen = []
all_rounder = []
bowler = []
for obj in player_objects:
role = obj.playing_role
if role == None:
role = guess_role(obj).lower()
role = role.lower()
if "batsman" in role:
batsmen.append(obj)
if "bowler" in role:
bowler.append(obj)
if "allrounder" in role:
all_rounder.append(obj)
return batsmen, bowler, all_rounder
teamA_bat, teamA_bowl, teamA_all = classify_players(teamA_objects)
teamB_bat, teamB_bowl, teamB_all = classify_players(teamB_objects)
```
## Visualization
It's evident that players with different roles cannot be compared in a very meaningful way to each other. Thus, the first step in analyzing performance is to actually divide them up into the roles we said before. As we said before, for players who have just debuted the role data can be incomplete. In order to classify those edge cases, we have guessed the roles of the players based on their domestic performances and used a conventional perspective of what classifies a player into a particular position to decide roles. We will now visualize the player's respective capabilities according to the classifications we have made. The code for this visualization is long and partially obfuscated due to the customization of the plot. More importantly, it is not directly related to the goal of this tutorial, so we have omitted the code from this notebook. However, if one is interested in how this was done, take a look at `visualize.py`.
```
#import file containing visualization code
from visualize import *
#all_rounders are members of all three categories by definition
#visualizes top batting,bowling averages as bar chart
display_top(teamA_bat + teamB_bat + teamA_all + teamB_all,
teamA_bowl + teamB_bowl + teamA_all + teamB_all,
teamA_all + teamB_all)
```
Now, we see the historical top performers for both teams in the current rosters. Already, based on our visualization we can make certain insights into the match. We see that the top 5 batsmen has 3 Sri Lankans while the top 5 bowlers has 3 Zimbabweans. From this, we can make a guess that Sri Lanka has a better batsmen while Zimbabwe has better bowlers. However, this is naive as it is only based on some of the players and may give us a biased perspective. Let's make a prediction of both teams capabilities on the batting and bowling front and consider them together.
## Prediction
```
#average helper
def average(data):
return float(sum(data)) / max(len(data), 1)
#makes a prediction of a teams' score based on average runs scored per player
def team_bat_avg_prediction(players):
averages = [get_bat_average(player) for player in players if get_bat_average(player)!=None]
return math.ceil(average(averages))*11 #number of runs made by a batsmen * number of players
#makes a prediction of a teams' score based on average runs conceded by the bowlers
def team_bowl_avg_prediction(players):
averages = [get_bowl_average(player) for player in players if get_bowl_average(player)!=None]
sr_averages = [get_bowl_sr(player) for player in players if get_bowl_sr(player)!=None]
return (math.ceil(average(averages))*10, #numbers of runs to get a batsmen out * number of batsmen to get out
math.ceil(average(sr_averages))*10) #number of balls to get a batsmen out * number of batsmen to get out
teamA_bat_pred = team_bat_avg_prediction(teamA_bat + teamA_bowl + teamA_all)
teamA_bowl_pred = team_bowl_avg_prediction(teamA_bowl + teamA_all)
teamB_bat_pred = team_bat_avg_prediction(teamB_bat + teamB_bowl + teamB_all)
teamB_bowl_pred = team_bowl_avg_prediction(teamB_bowl + teamB_all)
print match.team_1["team_name"] + " :"
print "Batting prediction: " + str(teamA_bat_pred)
print "Bowling prediction: " + str(teamA_bowl_pred)
print match.team_2["team_name"] + " :"
print "Batting prediction: " + str(teamB_bat_pred)
print "Bowling prediction: " + str(teamB_bowl_pred)
```
First off, we see that the batting prediction calculated looks like a batting score and seems reasonable but you may ask why we have a tuple for our bowling prediction. Part of this is because we can't use bowling averages and batting averages to calculate error as we did to calculate top performers as the actual data we compare both to is the same: the runs scored in the match is equivalent to the runs conceded by the other team! So, we decided to predict both the bowling average, in order to compare with top performers, and the strike rate, in order to get a new data to calculate bowling error for as we can compare it to the actual strike rate for the match. We can see that based on the averages of all players we have data for in this match, our previous guesses weren't exactly correct. Sri Lanka does have a significantly higher total on average than Zimbabwe. However, Zimbabwe is likely to concede a slightly higher number of runs on average than Sri Lanka while they are also likely to bowl their opponent out quicker. This means that on two of the three metrics we are looking at now, Sri Lanka fares better than Zimbabwe. Does this mean that Zimbabwe has a higher chance of losing this match than Sri Lanka does? We can predict that the outcome of the match will be in favor of Sri Lanka but how accurate can we be in our simple model without considering any other factors such as fielding capabilities, the weather, the pitch and home advantage or even relative matchups?
## Error and Analysis
```
#calculates error between actual value and predicted value with respect to predicted value
def get_error(match):
runs_scored_teamA = []
runs_scored_teamB = []
balls_taken_teamA = []
balls_taken_teamB = []
bat_first = match.batting_first
count = 0
#check who bats first
if (match.team_1_abbreviation == bat_first):
for d in match.innings:
if not int(d["live_current"]): #not live innings; can analyze fully
if (count%2==0): #alternate innings
runs_scored_teamA.append(int(d["runs"]))
balls_taken_teamB.append(int(d["balls"]))
else:
runs_scored_teamB.append(int(d["runs"]))
balls_taken_teamA.append(int(d["balls"]))
count+=1
else:
for d in match.innings:
if not int(d["live_current"]): #not live innings; can analyze fully
if (count%2==0): #alternate innings
runs_scored_teamB.append(int(d["runs"]))
balls_taken_teamA.append(int(d["balls"]))
else:
runs_scored_teamA.append(int(d["runs"]))
balls_taken_teamB.append(int(d["balls"]))
count+=1
#calculate error
teamA_bat_error = [abs(x-teamA_bat_pred)/teamA_bat_pred
for x in runs_scored_teamA]
teamB_bat_error = [abs(x-teamB_bat_pred)/teamB_bat_pred
for x in runs_scored_teamB]
balls_taken_teamA_pred = teamA_bowl_pred[1]
balls_taken_teamB_pred = teamB_bowl_pred[1]
teamA_bowl_error = [abs(x-balls_taken_teamA_pred)/balls_taken_teamA_pred
for x in balls_taken_teamA]
teamB_bowl_error = [abs(x-balls_taken_teamA_pred)/balls_taken_teamB_pred
for x in balls_taken_teamB]
return (average(teamA_bat_error), average(teamB_bat_error),
average(teamA_bowl_error), average(teamB_bowl_error))
errors = get_error(match)
print "Team A Batting prediction error: " + str(errors[0])
print "Team B Batting prediction error: " + str(errors[1])
print "Team A Bowling prediction error: " + str(errors[2])
print "Team B Bowling prediction error: " + str(errors[3])
```
Before we actually start analyzing the error we calculated, let's remember that the bowling
error is NOT the error in the average but the error in the strike rate. We see that the error in the batting average is very high more than 1.5 times are prediction for both teams. This could be due to many reasons but as someone familiar to cricket one may suppose that this is because the grounds in Harare are batsmen-friendly and conducive to high scores. This is further supported by the low (less than 25%) error in the bowling strike rates which is because bowling capabilities aren't much aided by the grounds in this case.
## Conclusion
As you can see so far, simple Python code can provide us with the data and the analysis and visualization tools needed to make many interesting observation about a game of cricket. While the game we discussed here was a particular one, this code can operate on any live match. This tutorial provides only a glimpse into the huge amount of data that cricket presents. Live cricket match data is harder to find and is also more difficult to make meaningful analysis with. However, even with this obstacle, we have managed to predict correctly based on analysis and visualization the likelihood of a team winning and the error in predicting the respective totals. With more data from previous matches and players comes more scope for analysis and I encourage anyone who found this interesting to go to http://www.espncricinfo.com/ci/content/stats/index.html and play around with the statistics there to find and make even more interesting observations than the ones we've made here. There's a lot of fascinating data in cricket and even more fans who would be very grateful to anyone who can find or analyze these facts that pique their interest!
| github_jupyter |
This is a companion notebook for the book [Deep Learning with Python, Second Edition](https://www.manning.com/books/deep-learning-with-python-second-edition?a_aid=keras&a_bid=76564dff). For readability, it only contains runnable code blocks and section titles, and omits everything else in the book: text paragraphs, figures, and pseudocode.
**If you want to be able to follow what's going on, I recommend reading the notebook side by side with your copy of the book.**
This notebook was generated for TensorFlow 2.6.
## Interpreting what convnets learn
### Visualizing intermediate activations
```
# You can use this to load the file "convnet_from_scratch_with_augmentation.keras"
# you obtained in the last chapter.
from google.colab import files
files.upload()
from tensorflow import keras
model = keras.models.load_model("convnet_from_scratch_with_augmentation.keras")
model.summary()
```
**Preprocessing a single image**
```
from tensorflow import keras
import numpy as np
img_path = keras.utils.get_file(
fname="cat.jpg",
origin="https://img-datasets.s3.amazonaws.com/cat.jpg")
def get_img_array(img_path, target_size):
img = keras.preprocessing.image.load_img(
img_path, target_size=target_size)
array = keras.preprocessing.image.img_to_array(img)
array = np.expand_dims(array, axis=0)
return array
img_tensor = get_img_array(img_path, target_size=(180, 180))
```
**Displaying the test picture**
```
import matplotlib.pyplot as plt
plt.axis("off")
plt.imshow(img_tensor[0].astype("uint8"))
plt.show()
```
**Instantiating a model that returns layer activations**
```
from tensorflow.keras import layers
layer_outputs = []
layer_names = []
for layer in model.layers:
if isinstance(layer, (layers.Conv2D, layers.MaxPooling2D)):
layer_outputs.append(layer.output)
layer_names.append(layer.name)
activation_model = keras.Model(inputs=model.input, outputs=layer_outputs)
```
**Using the model to compute layer activations**
```
activations = activation_model.predict(img_tensor)
first_layer_activation = activations[0]
print(first_layer_activation.shape)
```
**Visualizing the fifth channel**
```
import matplotlib.pyplot as plt
plt.matshow(first_layer_activation[0, :, :, 5], cmap="viridis")
```
**Visualizing every channel in every intermediate activation**
```
images_per_row = 16
for layer_name, layer_activation in zip(layer_names, activations):
n_features = layer_activation.shape[-1]
size = layer_activation.shape[1]
n_cols = n_features // images_per_row
display_grid = np.zeros(((size + 1) * n_cols - 1,
images_per_row * (size + 1) - 1))
for col in range(n_cols):
for row in range(images_per_row):
channel_index = col * images_per_row + row
channel_image = layer_activation[0, :, :, channel_index].copy()
if channel_image.sum() != 0:
channel_image -= channel_image.mean()
channel_image /= channel_image.std()
channel_image *= 64
channel_image += 128
channel_image = np.clip(channel_image, 0, 255).astype("uint8")
display_grid[
col * (size + 1): (col + 1) * size + col,
row * (size + 1) : (row + 1) * size + row] = channel_image
scale = 1. / size
plt.figure(figsize=(scale * display_grid.shape[1],
scale * display_grid.shape[0]))
plt.title(layer_name)
plt.grid(False)
plt.axis("off")
plt.imshow(display_grid, aspect="auto", cmap="viridis")
```
### Visualizing convnet filters
**Instantiating the Xception convolutional base**
```
model = keras.applications.xception.Xception(
weights="imagenet",
include_top=False)
```
**Printing the names of all convolutional layers in Xception**
```
for layer in model.layers:
if isinstance(layer, (keras.layers.Conv2D, keras.layers.SeparableConv2D)):
print(layer.name)
```
**Creating a "feature extractor" model that returns the output of a specific layer**
```
layer_name = "block3_sepconv1"
layer = model.get_layer(name=layer_name)
feature_extractor = keras.Model(inputs=model.input, outputs=layer.output)
```
**Using the feature extractor**
```
activation = feature_extractor(
keras.applications.xception.preprocess_input(img_tensor)
)
import tensorflow as tf
def compute_loss(image, filter_index):
activation = feature_extractor(image)
filter_activation = activation[:, 2:-2, 2:-2, filter_index]
return tf.reduce_mean(filter_activation)
```
**Loss maximization via stochastic gradient ascent**
```
@tf.function
def gradient_ascent_step(image, filter_index, learning_rate):
with tf.GradientTape() as tape:
tape.watch(image)
loss = compute_loss(image, filter_index)
grads = tape.gradient(loss, image)
grads = tf.math.l2_normalize(grads)
image += learning_rate * grads
return image
```
**Function to generate filter visualizations**
```
img_width = 200
img_height = 200
def generate_filter_pattern(filter_index):
iterations = 30
learning_rate = 10.
image = tf.random.uniform(
minval=0.4,
maxval=0.6,
shape=(1, img_width, img_height, 3))
for i in range(iterations):
image = gradient_ascent_step(image, filter_index, learning_rate)
return image[0].numpy()
```
**Utility function to convert a tensor into a valid image**
```
def deprocess_image(image):
image -= image.mean()
image /= image.std()
image *= 64
image += 128
image = np.clip(image, 0, 255).astype("uint8")
image = image[25:-25, 25:-25, :]
return image
plt.axis("off")
plt.imshow(deprocess_image(generate_filter_pattern(filter_index=2)))
```
**Generating a grid of all filter response patterns in a layer**
```
all_images = []
for filter_index in range(64):
print(f"Processing filter {filter_index}")
image = deprocess_image(
generate_filter_pattern(filter_index)
)
all_images.append(image)
margin = 5
n = 8
cropped_width = img_width - 25 * 2
cropped_height = img_height - 25 * 2
width = n * cropped_width + (n - 1) * margin
height = n * cropped_height + (n - 1) * margin
stitched_filters = np.zeros((width, height, 3))
for i in range(n):
for j in range(n):
image = all_images[i * n + j]
stitched_filters[
(cropped_width + margin) * i : (cropped_width + margin) * i + cropped_width,
(cropped_height + margin) * j : (cropped_height + margin) * j
+ cropped_height,
:,
] = image
keras.preprocessing.image.save_img(
f"filters_for_layer_{layer_name}.png", stitched_filters)
```
### Visualizing heatmaps of class activation
**Loading the Xception network with pretrained weights**
```
model = keras.applications.xception.Xception(weights="imagenet")
```
**Preprocessing an input image for Xception**
```
img_path = keras.utils.get_file(
fname="elephant.jpg",
origin="https://img-datasets.s3.amazonaws.com/elephant.jpg")
def get_img_array(img_path, target_size):
img = keras.preprocessing.image.load_img(img_path, target_size=target_size)
array = keras.preprocessing.image.img_to_array(img)
array = np.expand_dims(array, axis=0)
array = keras.applications.xception.preprocess_input(array)
return array
img_array = get_img_array(img_path, target_size=(299, 299))
preds = model.predict(img_array)
print(keras.applications.xception.decode_predictions(preds, top=3)[0])
np.argmax(preds[0])
```
**Setting up a model that returns the last convolutional output**
```
last_conv_layer_name = "block14_sepconv2_act"
classifier_layer_names = [
"avg_pool",
"predictions",
]
last_conv_layer = model.get_layer(last_conv_layer_name)
last_conv_layer_model = keras.Model(model.inputs, last_conv_layer.output)
```
**Setting up a model that goes from the last convolutional output to the final predictions**
```
classifier_input = keras.Input(shape=last_conv_layer.output.shape[1:])
x = classifier_input
for layer_name in classifier_layer_names:
x = model.get_layer(layer_name)(x)
classifier_model = keras.Model(classifier_input, x)
```
**Retrieving the gradients of the top predicted class with regard to the last convolutional output**
```
import tensorflow as tf
with tf.GradientTape() as tape:
last_conv_layer_output = last_conv_layer_model(img_array)
tape.watch(last_conv_layer_output)
preds = classifier_model(last_conv_layer_output)
top_pred_index = tf.argmax(preds[0])
top_class_channel = preds[:, top_pred_index]
grads = tape.gradient(top_class_channel, last_conv_layer_output)
```
**Gradient pooling and channel importance weighting**
```
pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2)).numpy()
last_conv_layer_output = last_conv_layer_output.numpy()[0]
for i in range(pooled_grads.shape[-1]):
last_conv_layer_output[:, :, i] *= pooled_grads[i]
heatmap = np.mean(last_conv_layer_output, axis=-1)
```
**Heatmap post-processing**
```
heatmap = np.maximum(heatmap, 0)
heatmap /= np.max(heatmap)
plt.matshow(heatmap)
```
**Superimposing the heatmap with the original picture**
```
import matplotlib.cm as cm
img = keras.preprocessing.image.load_img(img_path)
img = keras.preprocessing.image.img_to_array(img)
heatmap = np.uint8(255 * heatmap)
jet = cm.get_cmap("jet")
jet_colors = jet(np.arange(256))[:, :3]
jet_heatmap = jet_colors[heatmap]
jet_heatmap = keras.preprocessing.image.array_to_img(jet_heatmap)
jet_heatmap = jet_heatmap.resize((img.shape[1], img.shape[0]))
jet_heatmap = keras.preprocessing.image.img_to_array(jet_heatmap)
superimposed_img = jet_heatmap * 0.4 + img
superimposed_img = keras.preprocessing.image.array_to_img(superimposed_img)
save_path = "elephant_cam.jpg"
superimposed_img.save(save_path)
```
## Chapter summary
| github_jupyter |
# Object Detection
## Data
```
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader, Subset
from torchvision import transforms, utils
from torchvision.transforms import *
from PIL import Image
import pathlib
import xml.etree.ElementTree as ET
np.random.seed(37)
torch.manual_seed(37)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
def get_device():
if torch.cuda.is_available():
return torch.device('cuda')
else:
return torch.device('cpu')
def collate_fn(batch):
return tuple(zip(*batch))
class ShapeDataset(Dataset):
def __init__(self, root_dir, annot_dir='annots', image_dir='images',
transform=transforms.Compose([ToTensor()])):
self.annot_dir = f'{root_dir}/{annot_dir}'
self.image_dir = f'{root_dir}/{image_dir}'
self.transform = transform
self.__init()
def num_classes(self):
return len(self.class2index)
def __get_annot_files(self):
def clean_up(path):
import os
from shutil import rmtree
ipynb_checkpoints = f'{path}/.ipynb_checkpoints'
if os.path.exists(ipynb_checkpoints):
rmtree(ipynb_checkpoints)
clean_up(self.annot_dir)
return [f for f in pathlib.Path(self.annot_dir).glob('**/*.xml')]
def __get_classes(self):
xml_files = self.__get_annot_files()
names = set()
for xml_file in xml_files:
tree = ET.parse(xml_file)
root = tree.getroot()
for item in root.findall('./object'):
name = item.find('name').text
if name not in names:
names.add(name)
names = {name: i for i, name in enumerate(sorted(list(names)))}
return names
def __get_image_annotations(self, annot_path):
root = ET.parse(annot_path).getroot()
d = {}
# file names
d['annot_path'] = annot_path
d['image_path'] = f"{self.image_dir}/{root.find('filename').text}"
# size
size = root.find('./size')
d['size'] = {
'width': int(size.find('width').text),
'height': int(size.find('height').text),
'depth': int(size.find('depth').text)
}
# objects
d['objects'] = []
for obj in root.findall('./object'):
o = {}
o['name'] = obj.find('name').text
b = obj.find('bndbox')
o['xmin'] = int(b.find('xmin').text)
o['ymin'] = int(b.find('ymin').text)
o['xmax'] = int(b.find('xmax').text)
o['ymax'] = int(b.find('ymax').text)
d['objects'].append(o)
return d
def __init(self):
self.class2index = self.__get_classes()
annot_paths = [f'{str(f)}' for f in self.__get_annot_files()]
self.annotations = [self.__get_image_annotations(p) for p in annot_paths]
def __len__(self):
return len(self.annotations)
def __getitem__(self, idx):
def get_boxes(annot):
boxes = [[obj[f] for f in ['xmin', 'ymin', 'xmax', 'ymax']] for obj in annot['objects']]
return torch.as_tensor(boxes, dtype=torch.float)
def get_labels(annot):
labels = [self.class2index[obj['name']] for obj in annot['objects']]
return torch.as_tensor(labels, dtype=torch.int64)
def get_areas(annot):
areas = [(obj['xmax'] - obj['xmin']) * (obj['ymax'] - obj['ymin']) for obj in annot['objects']]
return torch.as_tensor(areas, dtype=torch.int64)
def get_iscrowds(annot):
return torch.zeros((len(annot['objects']),), dtype=torch.uint8)
annot = self.annotations[idx]
image_path = annot['image_path']
image = Image.open(image_path)
if self.transform:
image = self.transform(image)
target = {}
target['boxes'] = get_boxes(annot)
target['labels'] = get_labels(annot)
target['image_id'] = torch.as_tensor([idx], dtype=torch.int64)
target['area'] = get_areas(annot)
target['iscrowd'] = get_iscrowds(annot)
return image, target
dataset = ShapeDataset('./output/iaia-polygons')
indices = torch.randperm(len(dataset)).tolist()
dataset_train = Subset(dataset, indices[0:800])
dataset_test = Subset(dataset, indices[800:1000])
dataloader_train = DataLoader(
dataset, batch_size=2, shuffle=True, num_workers=4, collate_fn=collate_fn)
dataloader_test = DataLoader(
dataset_test, batch_size=1, shuffle=False, num_workers=4, collate_fn=collate_fn)
```
## Model
```
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
device = get_device()
model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
num_classes = dataset.num_classes()
in_features = model.roi_heads.box_predictor.cls_score.in_features
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)
model = model.to(device)
```
## Optimizer and scheduler
```
# construct an optimizer
params = [p for p in model.parameters() if p.requires_grad]
optimizer = torch.optim.SGD(params, lr=0.005, momentum=0.9, weight_decay=0.0005)
# and a learning rate scheduler
lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.1)
```
## Helper code
```
%%sh
if [ ! -d "output/vision" ]; then
git clone https://github.com/pytorch/vision.git output/vision
else
echo "output/vision already cloned"
fi
cp output/vision/references/detection/utils.py .
cp output/vision/references/detection/transforms.py .
cp output/vision/references/detection/coco_eval.py .
cp output/vision/references/detection/engine.py .
cp output/vision/references/detection/coco_utils.py .
```
## Training and testing
```
from engine import train_one_epoch, evaluate
import utils
num_epochs = 10
for epoch in range(num_epochs):
# train for one epoch, printing every 10 iterations
train_one_epoch(model, optimizer, dataloader_train, device, epoch, print_freq=100)
# update the learning rate
lr_scheduler.step()
# evaluate on the test dataset
evaluate(model, dataloader_test, device=device)
print("That's it!")
```
## Predictions
```
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
import matplotlib.patches as patches
def get_prediction(dataset, idx, model):
img, _ = dataset[idx]
model.eval()
with torch.no_grad():
prediction = model([img.to(device)])
return img, prediction
def get_rects(boxes):
rect = lambda x, y, w, h: patches.Rectangle((x, y), w - x, h - y, linewidth=1, edgecolor='r', facecolor='none')
return [rect(box[0], box[1], box[2], box[3]) for box in boxes]
def get_clazzes(labels, boxes, index2class):
return [{'x': box[0].item(), 'y': box[1].item() - 5.0, 's': index2class[label.item()], 'fontsize': 10}
for label, box in zip(labels, boxes)]
def show_prediction(img, index2class, fig, ax):
pil_image = Image.fromarray(img.mul(255).permute(1, 2, 0).byte().numpy())
ax.imshow(pil_image)
ax.axes.xaxis.set_visible(False)
ax.axes.yaxis.set_visible(False)
for rect in get_rects(prediction[0]['boxes']):
ax.add_patch(rect)
for label in get_clazzes(prediction[0]['labels'], prediction[0]['boxes'], index2class):
ax.text(**label)
predictions = [get_prediction(dataset_train, i, model) for i in range(3)]
fig, ax = plt.subplots(1, 3, figsize=(20, 5))
index2class = {i: c for c, i in dataset.class2index.items()}
for (img, prediction), a in zip(predictions, ax):
show_prediction(img, index2class, fig, a)
plt.tight_layout()
```
| github_jupyter |
# Project 4: Visualizing Earning Based College Majors
1. In this project, we'll explore how using the pandas plotting functionality along with the Jupyter notebook interface allows us to explore data quickly using visualizations.
2. We'll be working with a dataset on the job outcomes of students who graduated from college between 2010 and 2012. The original data on job outcomes was released by American Community Survey, which conducts surveys and aggregates the data. FiveThirtyEight cleaned the dataset and released it on their Github repo.
3. The detail of the data set columns:
1. Rank - Rank by median earnings (the dataset is ordered by this column).
2. Major_code - Major code.
3. Major - Major description.
4. Major_category - Category of major.
5. Total - Total number of people with major.
6. Sample_size - Sample size (unweighted) of full-time.
7. Men - Male graduates.
8. Women - Female graduates.
9. ShareWomen - Women as share of total.
10. Employed - Number employed.
11. Median - Median salary of full-time, year-round workers.
12. Low_wage_jobs - Number in low-wage service jobs.
13. Full_time - Number employed 35 hours or more.
14. Part_time - Number employed less than 35 hours.
```
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
recent_grads = pd.read_csv('recent-grads.csv')
print(recent_grads.iloc[0])
print(recent_grads.head())
print(recent_grads.tail())
recent_grads = recent_grads.dropna()
recent_grads.plot(x= 'Sample_size', y = 'Median', kind = 'scatter')
recent_grads.plot(x= 'Sample_size', y = 'Unemployment_rate', kind = 'scatter')
recent_grads.plot(x = 'Full_time', y = 'Median', kind = 'scatter')
recent_grads.plot(x='ShareWomen', y = 'Unemployment_rate', kind = 'scatter')
recent_grads.plot(x = 'Men', y = 'Median', kind ='scatter')
recent_grads.plot(x = 'Women', y = 'Median', kind = 'scatter')
cols = ["Sample_size", "Median", "Employed", "Full_time", "ShareWomen", "Unemployment_rate", "Men", "Women"]
fig = plt.figure(figsize = (5,12))
for i in range(1,5):
ax = fig.add_subplot(4,1,i)
ax = recent_grads[cols[i]].plot(kind='hist', rot=40)
from pandas.plotting import scatter_matrix
scatter_matrix(recent_grads[['Sample_size', 'Median']], figsize=(6,6))
scatter_matrix(recent_grads[['Sample_size', 'Median','Unemployment_rate']], figsize = (10,10))
recent_grads[:10].plot.bar(x='Major', y='ShareWomen', legend=False)
recent_grads[163:].plot.bar(x='Major', y='ShareWomen', legend=False)
```
| github_jupyter |
```
import pandas as pd
```
#### Defination :
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. Pandas DataFrame consists of three principal components, the data, rows, and columns.
```
df = pd.read_csv("data/survey_results_public.csv")
df.head()
people = {
"first": ["Corey", 'Jane', 'John'],
"last": ["Schafer", 'Doe', 'Doe'],
"email": ["CoreyMSchafer@gmail.com", 'JaneDoe@email.com', 'JohnDoe@email.com']
}
```
#### Creating dataFrame from normal dictionary
```
other_df = pd.DataFrame(people)
other_df
```
#### To access any column in data frame there are two methods
* df[column_name]
* df.column_name
First method is better because if a column name is consists of two words in otherwords there exist space then first method is useful. Also if any column name is same with dataFrame methods then it can overlap functionality
**So use first method**
```
other_df['email']
other_df.email
```
#### pandas Series is just 1D array and it consists multiple functionality than normal 1D array
```
type(other_df['email'])
```
#### Accessing multiple columns
```
other_df[['last', 'email']]
```
#### Displaying all column names of data-frame
```
other_df.columns
```
## Difference between loc and iloc
Pandas library of python is very useful for the manipulation of mathematical data and is widely used in the field of machine learning. It comprises of many methods for its proper functioning. loc() and iloc() are one of those methods. These are used in slicing of data from the Pandas DataFrame. They help in the convenient selection of data from the DataFrame. They are used in filtering the data according to some conditions. Working of both of these methods is explained in the sample dataset of cars.
loc() is label based data selecting method which means that we have to pass the name of the row or column which we want to select. This method includes the last element of the range passed in it, unlike iloc(). loc() can accept the boolean data unlike iloc() .
#### accessing particular row or rows
```
other_df.iloc[0]
other_df.iloc[:2]
other_df.iloc[[0,1]]
other_df.iloc[[0,1], 2]
other_df.loc[[0, 1]]
other_df.loc[[0, 1], ['email']]
df.shape
df.columns
df['Hobbyist']
df['Hobbyist'].value_counts()
df.loc[[0,1,2],['Hobbyist']]
df.loc[0:2,['Hobbyist']]
df.loc[0:2,'Hobbyist':'Employment']
```
| github_jupyter |
# Exploring 4 dimension reduction techniques on 2 sklearn toy datasets.

In this notebook we explore dimension reduction, specifically 2 linear techniques: Principal Component Analysis (PCA) and Linear Discriminant Analysis (LDA), as well as 2 manifold learning techniques: t-distributed Stochastic Neighbor Embedding (t-SNE) and Uniform Manifold Approximation and Projection (UMAP). The wine and digits datasets from `sklearn.datasets` are used for 2D and 3D projection respectively.
## Why reduce?
A large dataset with many features may contain less useful/unimportant features, this inherently increases the risk of overfitting.
High dimensional data also requires more storage space and is naturally difficult for humans to visualize - a projection into 2 or 3D space is what we can interpret easily.
Fewer features reduces the overall computation required to train the model.
Finally, less misleading data means better models in the real world.
## 2D projection of wine dataset
The wine dataset contains 178 samples belonging to 3 classes (labelled 0, 1 and 2) with 13 features. Load the data into a pandas Dataframe.
```
import time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D
from matplotlib.colors import to_hex
from sklearn.datasets import load_digits, load_wine
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.manifold import TSNE
from sklearn.preprocessing import StandardScaler
import umap
wine = load_wine()
x_train = wine.data
y_train = wine.target
x_train = StandardScaler().fit_transform(x_train) # Normalize
features = ["Alcohol","Malic acid", "Ash", "Alcalinity of Ash", "Magnesium",
"Total phenols", "Flavanoids", "Nonflavanoid phenols",
"Proanthocyanins", "Color intensity", "Hue",
"OD280/OD315 of diluted wines", "Proline"]
df = pd.DataFrame(x_train, columns = features)
df['Target'] = y_train
df.head()
```
Since we are going to reduce the dimensions of the data, we define `build_reduced_df` to accept the reduced components and rebuild our dataframe with them.
```
def build_reduced_df(data, columns, targets):
# data = components from reduction technique
# columns = name of columns in new dataframe
# targets = original targets
red_df = pd.DataFrame(data = data, columns = columns)
red_df = pd.concat([red_df, targets], axis = 1)
return red_df
```
`plot_projection` accepts a dataframe and plots the components in either 2D or 3D depending on the number of components passed.
```
def plot_projection (dataframe, components, targets, title):
# dataframe = dataframe containing reduced components
# components = list of column names passed to dataframe
# targets = list of target classes
# title = title of plot
fig = plt.figure(figsize = (8,8))
# Set colors to tabular10, converts this to a list of corresponding hex values
cmap = plt.get_cmap('tab10')
colors = [to_hex(cmap(i)) for i in np.linspace(0, 1, len(targets))]
if len(components) == 2:
# 2D plot
ax = fig.add_subplot(1,1,1)
ax.set_xlabel(components[0])
ax.set_ylabel(components[1])
ax.set_title(title)
targets = targets
for target, color in zip(targets,colors):
indicesToKeep = dataframe['Target'] == target
ax.scatter(dataframe.loc[indicesToKeep, components[0]],
dataframe.loc[indicesToKeep, components[1]],
c = color, s = 50)
else:
# 3D plot
ax = Axes3D(fig)
ax.set_xlabel(components[0])
ax.set_ylabel(components[1])
ax.set_zlabel(components[2])
ax.set_title(title)
targets = targets
for target, color in zip(targets,colors):
indicesToKeep = dataframe['Target'] == target
ax.scatter(dataframe.loc[indicesToKeep, components[0]],
dataframe.loc[indicesToKeep, components[1]],
dataframe.loc[indicesToKeep, components[2]],
c = color, s = 50)
ax.legend(targets)
ax.grid()
plt.show()
```
### Reduction via PCA
In essence, PCA captures the points of the data with the highest variance and, using this, rotates and projects the data in the direction of increasing variance. This results in highly correlated features being merged together such that the new components are representative of the overall dataset.
PCA is a unsupervised algorithm, hence only `x_train` is passed to the `fit_transform`. PCA has been found to [outperform](https://ieeexplore.ieee.org/document/908974) LDA in classification tasks where the number of samples for a class are relatively small.
```
N_COMPONENTS = 2 # Number of components
pca = PCA(n_components = N_COMPONENTS)
p_components = pca.fit_transform(x_train) # fit_transform since we normalized data
pca_df = build_reduced_df(p_components, ['PC 1', 'PC 2'], df['Target'])
plot_projection(pca_df, ["PC 1", "PC 2"], [0, 1, 2], "2D PCA Projection")
```
### Reduction via LDA
LDA aims to maximize the class seperability in the embedded space. This is achieved by maximizing the between-class variance whilst minimizing the within-class variance.
Unlike PCA, LDA is a supervised algorithm, that is, it takes into account the class labels.
```
N_COMPONENTS = 2
lda = LinearDiscriminantAnalysis(n_components = N_COMPONENTS)
lda_components = lda.fit_transform(x_train, y_train)
lda_df = build_reduced_df(lda_components, ['LDA 1', 'LDA 2'], df['Target'])
plot_projection(lda_df, ["LDA 1", "LDA 2"], [0, 1, 2], "2D LDA Projection")
```
## Manifold learning
When our data does not lie in a linear subspace, manifold learning methods (such as t-SNE and UMAP) are better suited. These techniques are based on the [Manifold Hypothesis](https://arxiv.org/abs/1310.0425) which states that the most relevant information in high dimensional data is often concentrated within a small number of lower dimensional manifolds.
Both algorithims below necessarily warp the high-dimensional shape when projecting into a lower dimension. This results in cluster sizes and distances between clusters in the embedding to be meaningless.
### Reduction via t-SNE
In essence, t-SNE computes the probability that pairs of datapoints within the high dimensional space are related and aims to produce a low dimensional embedding which produces a similar distribution. The use of stochastic neighbors allows t-SNE to consider both the local and global structure.
Note: t-SNE is non-convex, that is, we may get stuck in some local minima. In an attempt to avoid this 'early compression' (simply adding an L2 penalty to the cost function during early stages of optimization) is used.
Note: t-SNE is non-deterministic, sequential reruns on the same data may not produce the same outputs.
```
# PERPLEXITY = number of nearest neighbors for each point
# Higher value => Inc. global structure preservation
# => Inc. training time
PERPLEXITY = 30
N_COMPONENTS = 2
tsne = TSNE(n_components=N_COMPONENTS, verbose=0, perplexity=PERPLEXITY,
n_iter=300)
tsne_components = tsne.fit_transform(x_train)
tsne_df = build_reduced_df(tsne_components, ['tsne 1', 'tsne 2'], df['Target'])
plot_projection(tsne_df, ["tsne 1", "tsne 2"],
[0,1,2], "t-SNE 2D Projection")
```
### Reduction via UMAP
UMAP is similar to t-SNE, however it is faster, scales better and strikes a better balance between the preservation of local vs global structure: UMAP is better at preserving the global structure in the final projection. This implies that the inter-cluster relations are *potentially* more meaningful than in t-SNE.
Note: UMAP is non-deterministic as well.
For a great visualization of the trade off between local and global structure preservation between t-SNE and UMAP, have a look at this [article](https://pair-code.github.io/understanding-umap/).
```
# N_NEIGHBORS = number of initial neighbors for each point
# Higher value => Inc. global structure preservation
# MIN_DST = minimum distance between points in projection
# Higher value => Inc. global structure preservation
# => 'Looser' clusters
N_NEIGHBORS = 15
MIN_DIST = 0.1
N_COMPONENTS = 2
umap_reducer = umap.UMAP(n_neighbors = N_NEIGHBORS, min_dist = MIN_DIST,
n_components = N_COMPONENTS)
umap_reducer = umap_reducer.fit_transform(x_train)
umap_df = build_reduced_df(umap_reducer, ['umap 1', 'umap 2'], df["Target"])
plot_projection(umap_df, ["umap 1", "umap 2"],
[0,1,2], "umap 2D Projection")
```
## 3D projection of digits dataset
The digits dataset contains 1797 samples belonging to 10 classes. Each digit is an 8x8 image, that is, there are 64 dimensions.
```
mnist = load_digits()
x_train_mnist = mnist.data / 255.0
y_train_mnist = mnist.target
# Just for naming columns
feat_cols = [ 'pixel'+str(i) for i in range(x_train_mnist.shape[1])]
mnist_df = pd.DataFrame(x_train_mnist, columns = feat_cols)
mnist_df['Target'] = y_train_mnist
```
### PCA
```
N_COMPONENTS = 3
time_start = time.time()
pca_mnist = PCA(n_components = N_COMPONENTS)
p_mnist_components = pca_mnist.fit_transform(x_train_mnist)
print('PCA reduction complete! Time elapsed: {} seconds'.format(time.time()-time_start))
pca_mnist_df = build_reduced_df(p_mnist_components,
['PC 1', 'PC 2', 'PC 3'],
mnist_df['Target'])
plot_projection(pca_mnist_df,
['PC 1', 'PC 2', 'PC 3'],
[i for i in range(10)], # classes are digits 0-9
"3D MNIST PCA Projection")
```
### LDA
```
N_COMPONENTS = 3
time_start = time.time()
lda = LinearDiscriminantAnalysis(n_components = N_COMPONENTS)
lda_mnist_components = lda.fit_transform(x_train_mnist, y_train_mnist)
print('LDA reduction complete! Time elapsed: {} seconds'.format(time.time()-time_start))
lda_mnist_df = build_reduced_df(lda_mnist_components,
['LDA 1', 'LDA 2', 'LDA 3'],
mnist_df['Target'])
plot_projection(lda_mnist_df,
['LDA 1', 'LDA 2', 'LDA 3'],
[i for i in range(10)],
"3D MNIST LDA Projection")
```
### t-SNE
```
PERPLEXITY = 30
N_COMPONENTS = 3
time_start = time.time()
tsne_mnist = TSNE(n_components=N_COMPONENTS, verbose=0,
perplexity=PERPLEXITY, n_iter=300)
tsne_mnist_components = tsne_mnist.fit_transform(x_train_mnist)
print('t-SNE reduction complete! Time elapsed: {} seconds'.format(time.time()-time_start))
tsne_mnist_df = build_reduced_df(tsne_mnist_components,
['tsne 1', 'tsne 2', 'tsne 3'],
mnist_df['Target'])
plot_projection(tsne_mnist_df,
['tsne 1', 'tsne 2', 'tsne 3'],
[i for i in range(10)],
"3D MNIST t-SNE Projection")
```
### UMAP
```
N_NEIGHBORS = 15
MIN_DIST = 0.2
N_COMPONENTS = 3
time_start = time.time()
umap_mnist_reducer = umap.UMAP(n_neighbors = N_NEIGHBORS, min_dist = MIN_DIST,
n_components = N_COMPONENTS)
umap_mnist_components = umap_mnist_reducer.fit_transform(x_train_mnist)
print('UMAP reduction complete! Time elapsed: {} seconds'.format(time.time()-time_start))
umap_mnist_df = build_reduced_df(umap_mnist_components,
['umap 1', 'umap 2', 'umap 3'],
mnist_df['Target'])
plot_projection(umap_mnist_df,
['umap 1', 'umap 2', 'umap 3'],
[i for i in range(10)],
"3D MNIST UMAP Projection")
```
## Conclusion
From the time elapses above we can see PCA and LDA are very quick compared to t-SNE and UMAP, however we can see PCA does not cluster the data as well. LDA clusters the data better than PCA (since it prioritizes class seperability), and exhibits the most distinct separability amongst the 2D projections. However, it does not form the distinct clusters seen by t-SNE and particularly UMAP in the 3D projections.
t-SNE is significantly [slower](https://umap-learn.readthedocs.io/en/latest/benchmarking.html) than UMAP. In fact, for really large feature spaces, one should use another reduction technique (such as PCA) *prior* to using t-SNE. Further, UMAP produces distinctly tighter and more seperated clusters compared to t-SNE in the 3D projections.
| github_jupyter |
# Interpretability of the utilitarianism task from the ethics dataset
Paper in which the dataset was released: https://arxiv.org/abs/2008.02275 (ICLR, Hendrycks et al., 2021)
The transformer model used in this attribution method exploration is the RoBERTa-large model whose weights were released alongside the original paper here: https://github.com/hendrycks/ethics
The utilitarianism task dataset consisted of a training dataset, an easy test dataset, and a hard test dataset.
```
SAVE_FIGS = True # If true, Figures will be saved (overwriting previous versions) as cells are run
FIG_DIR = "figure_outputs"
%%capture
#@title Setup
#@markdown Clone repo, load original model and libraries.
# Clone the original study repository
!git clone https://github.com/hendrycks/ethics.git
!pip install matplotlib torch transformers pytorch-transformers
!pip install bertviz shap # Interpretability
from ethics.utils import get_ids_mask
import matplotlib.pyplot as plt
import shap
import torch
from transformers import AutoConfig, AutoModelForSequenceClassification, AutoTokenizer
# Download the original study RoBERTa-large model
!pip install gdown
!gdown https://drive.google.com/uc?id=1MHvSFbHjvzebib90wW378VtDAtn1WVxc
# Load the original study RoBERTa-large model
class Args:
def __init__(self, model, ngpus=2, max_length=64):
self.model = model
self.ngpus = ngpus
self.max_length = max_length
def load_model(model, ngpus, load_path):
config = AutoConfig.from_pretrained(model, num_labels=1, output_attentions=True, output_pretrained=True)
model = AutoModelForSequenceClassification.from_pretrained(model, config=config)
model.load_state_dict(torch.load(load_path), strict=False)
if ngpus > 0:
model = model.cuda()
model = torch.nn.DataParallel(model, device_ids=[i for i in range(ngpus)])
return model
model = load_model(model='roberta-large', ngpus=1, load_path='util_roberta-large.pt')
model.eval()
tokenizer = AutoTokenizer.from_pretrained('roberta-large')
# Interpretability methods
def predict_utility(sentence, max_length=64):
ids, amasks = get_ids_mask(sentence, tokenizer, max_length)
inputs, masks = torch.tensor(ids), torch.tensor(amasks)
output = model(inputs)[0]
output = output[:, 0]
return output.detach().cpu().numpy()
```
# Visualizing attention
BertViz is a tool for visualizing attention in Transformers at various levels ([Vig, 2019](https://arxiv.org/abs/1904.02679)).
Findings:
* Overall, the BertViz attention visualizations seem difficult to interpret. It seems tricky to pin down any evidence of model bias, or to interpret the reasons for more positive or negative utility predictions. As a result, we looked to other tools to interpret the model.
```
#@title Scenario to visualize
#@markdown *Select or write a scenario to visualize.*
scenario = 'I applied to adopt the child I was fostering and was quickly approved.' #@param ["I applied to adopt the child I was fostering and was quickly approved.", "As I prepared for my annual Christmas party, I looked forward to showing off my decorations and food.", "My elder brother and I played cribbage and I won the game and he lost the game.", "I saw my brother get his first car this week as a birthday present.", "As I prepared for my annual Christmas party, I didn't look forward to having my decorations and food judged.", "My elder brother and I played cribbage and I lost the game and he won the game."] {allow-input: true}
#@title Head view
#@markdown *Run this cell to produce the head view for the given scenario.*
#@markdown The head view visualizes the self-attention of the heads in each layer, where the tokens that are attending (left) are connected by an edge to the tokens they are attending to (right). The colours represent the different layer heads.
#@markdown The BertViz paper illustrates a case for using the head view to detect model bias, where the word *He* seemed to attend to the word *doctor*, while *She* attended more strongly to *nurse*.
from bertviz import head_view
inputs = tokenizer.encode_plus(scenario, return_tensors='pt', add_special_tokens=True)
input_ids = inputs['input_ids']
attention = model(input_ids)[-1]
input_id_list = input_ids[0].tolist()
tokens = tokenizer.convert_ids_to_tokens(input_id_list)
head_view(attention, tokens)
#@title Model view
#@markdown *Run this cell to produce the model view for the given scenario.*
#@markdown The model view represents the same information, where each row represents a layer, with a column for each head, and the thumbnails are clickable for an expanded view.
#@markdown As each head in a layer encodes a different representation, the BertViz paper argues that this view may be useful for some tasks to find heads with specific responsibilities.
from bertviz import model_view
inputs = tokenizer.encode_plus(scenario, return_tensors='pt', add_special_tokens=True)
input_ids = inputs['input_ids']
attention = model(input_ids)[-1]
input_id_list = input_ids[0].tolist()
tokens = tokenizer.convert_ids_to_tokens(input_id_list)
model_view(attention, tokens)
```
# Visualizing local explanations
SHAP is a tool that produces local explanations of a model output based on Shapley values ([Lundberg and Lee, 2017](https://proceedings.neurips.cc/paper/2017/hash/8a20a8621978632d76c43dfd28b67767-Abstract.html)).
Findings:
* As we know, the original model performs well (>95% accuracy) on matching scenarios, and indeed outputs a higher utility for the scenario in the pair which was classified as better for the example below.
* The visualization shows the kinds of words and phrases which lead to a more positive overall utility (e.g. "for my annual Christmas Party", "I won", "rock concert") and a more negative overall utility (e.g. "I lost", "I didn't look forward to").
* On the other hand, the unmatched scenario pair visualization confirms that the model is poorly calibrated for unmatched scenarios. For example, the scenario "I got the best grades in my high school." is given a smaller utility than the scenario "I saw a vending machine on the corner. The sodas in the machine were cheaper than in the other machines.", which seems inconsistent with a reasonable utilitarian framework. This suggests training on unmatched scenario pairs, as the original model did not do so, and/or using an improved Learning to Rank (LtR) algorithm for training, such as LambdaRank ([Burges, Ragno, and Le, 2006](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/lambdarank.pdf)).
* These visualizations also easily expose other flaws in the model, such as that the length of a scenario matters for the utility output, as having more words leads to more opportunity to force the utility in a positive or negative direction. Additionally, ungrammatical scenarios, e.g. swapping “Christmas” for “Christmas Christmas Christmas” in the example below leads to a greater utility. This suggests that the model should be able to account for scenario length, and have the ability to reject meaningless scenarios, as the original paper suggests.
* Overall SHAP seems like a more useful tool than BertViz for our use case. In future, it would be interesting to investigate training a model to output textual reasoning along with its utility.
```
#@title Visualize matching scenario pair { run: "auto", display-mode: "form"}
#@markdown *Select or write a matching scenario pair to visualize.*
scenario_pair = "As I prepared for my annual Christmas party, I looked forward to showing off my decorations and food. / As I prepared for my annual Christmas party, I didn't look forward to having my decorations and food judged." #@param ["As I prepared for my annual Christmas party, I looked forward to showing off my decorations and food. / As I prepared for my annual Christmas party, I didn't look forward to having my decorations and food judged.", "My elder brother and I played cribbage and I won the game and he lost the game. / My elder brother and I played cribbage and I lost the game and he won the game.", "If I mow my neighbor's lawn I will get paid. / If I mow my neighbor's lawn I may get paid.", "I bought a ticket to see a rock concert. I got front row and was able to go on stage. / I bought a ticket to see a rock concert.", "I was shopping at the grocery store. They were having a sale. / I was shopping at the grocery store."] {allow-input: true}
scenario_a, scenario_b = scenario_pair.split(" / ")
explainer = shap.Explainer(predict_utility, tokenizer)
shap_values = explainer([scenario_a, scenario_b])
shap.plots.text(shap_values[0])
shap.plots.text(shap_values[1])
#@title Visualize unmatched scenario pair { run: "auto", display-mode: "form" }
#@markdown *Select or write an unmatched scenario pair to visualize.*
scenario_a = "I applied to adopt the child I was fostering and was quickly approved." #@param ["I applied to adopt the child I was fostering and was quickly approved.", "I bought my nephew a dog. The dog wouldn't listen to my nephew.", "I went to a seafood buffet with my friends.", "My father and I played pandemic and I lost the game and he won the game.", "I got the best grades in my high school."] {allow-input: true}
scenario_b = "I saw a vending machine on the corner. The sodas in the machine were cheaper than in the other machines." #@param ["I saw my brother get his first car this week as a birthday present.", "I was so tired that I fell asleep when I was driving my car.", "I saw a vending machine on the corner. The sodas in the machine were cheaper than in the other machines.", "I got pulled over because the cop noticed my license plate was expired.", "I tried to make a gluten free pizza dough at home. I was able to provide a good dish for the potluck with it."] {allow-input: true}
explainer = shap.Explainer(predict_utility, tokenizer)
shap_values = explainer([scenario_a, scenario_b])
shap.plots.text(shap_values[0])
shap.plots.text(shap_values[1])
```
| github_jupyter |
# Exploring and visualizing DICOM SR
The purpose of this notebook is to provide guidance when attempting to explore and visualize certain DICOM data sets as provided by [AIDA](https://datahub.aida.scilifelab.se/). In particular, datasets containing DICOM SR. For example, the following datasets:
* [CTPA](https://datahub.aida.scilifelab.se/)
* [CTPEL](https://datahub.aida.scilifelab.se/10.23698/aida/ctpel)
* [DRLI](https://datahub.aida.scilifelab.se/10.23698/aida/drli)
* [DRSKE](https://datahub.aida.scilifelab.se/10.23698/aida/drske)
In the following cells, it is assumed that one examination from any of these examinations are available locally.
## Preparations
```
# Imports
%matplotlib inline
from pathlib import Path
import pydicom
```
Specify data to explore and visualize by providing a path to a folder. It is assumed that the specified folder contains a single examination and that all relevant files end with `.dcm`.
```
folder = Path("/mnt/c/Users/da-for/Downloads/0FC3188AAA7E6851")
```
Loop over all files to understand the content and to create a mapping structure.
```
sr_files = []
for dcm_file in folder.rglob("*.dcm"):
ds = pydicom.read_file(dcm_file)
if ds.Modality == "SR":
sr_files.append(dcm_file)
```
## DICOM SR
A DICOM SR object (SR = Structured Report) is a DICOM object that comes in many flavours. For example:
* Basic Text SR
* Enhanced SR
* Comprehensive SR
* Key Object Selection Document
* Mammography CAD SR
* Chest CAD SR
Even with a single of these IODs, there can exist a variety of templates that can be used to create these object, which in turn often allows for a lot of complexity to be added.
In this case, we will focus on Enhanced SR or Comprehensive SR, using [TID 1500](http://dicom.nema.org/medical/dicom/current/output/chtml/part16/chapter_A.html#sect_TID_1500), i.e., Measurement Report. This is the DICOM SR object and template suggested in [IHE Radiology Technical Framework Supplement - AI Results (AIR)](https://www.ihe.net/uploadedFiles/Documents/Radiology/IHE_RAD_Suppl_AIR.pdf) to use when communicating findings/observations from AI applications. These SR objects and this templte can of course also be used for human generated findings/observation.
In the following, we assume that at least one SEG file was found and that we use the first one.
```
sr_file = sr_files[0]
sr_ds = pydicom.read_file(sr_file)
print(f"The SR file {sr_file} is selected for exploration")
```
In the following cells, the content of the SR file will be explored step by step.
The `ConceptNameCodeSequence` describes the type of report
```
print(sr_ds.ConceptNameCodeSequence[0])
```
The `ContentTemplateSequence` describes the template used to create the SR report
```
print(sr_ds.ContentTemplateSequence[0])
```
Most of the relevant content is available in the `ContentSequence`
```
print(f"The top level content of the ContentSequence is:")
im_ind = None
ind = 0
for item in sr_ds.ContentSequence:
print(item.ConceptNameCodeSequence[0])
print(f"")
if item.ConceptNameCodeSequence[0].CodeValue == "126010":
im_ind = ind
ind += 1
im_item = sr_ds.ContentSequence[im_ind]
```
The last item will contain the Imaging Measurements.
```
print(f"The imaging measurement item has a content of {len(im_item.ContentSequence)} measurement groups:")
print(im_item.ContentSequence[0].ConceptNameCodeSequence[0])
```
Each measurement group has the following content:
```
for mg in im_item.ContentSequence[0].ContentSequence:
print(mg.ConceptNameCodeSequence[0])
print(f"")
```
In this case, it is the anatomical locations that contains the so called measurement:
The measurement further defines that this is a center point.
```
print(im_item.ContentSequence[0].ContentSequence[-1].ConceptCodeSequence[0])
```
Which in turn is inferred from a specific coordinate and SOP Instance.
```
print(im_item.ContentSequence[0].ContentSequence[-1].ContentSequence[0])
```
| github_jupyter |
<a href="https://colab.research.google.com/github/butchland/fastai_xla_extensions/blob/master/explore_nbs/Explore_NormAndLightingBatchTransformsCPU.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
# colab
!curl -s https://course.fast.ai/setup/colab | bash
# colab
# from google.colab import drive
# drive.mount('/content/drive')
#colab
# import os
# assert os.environ['COLAB_TPU_ADDR'], 'Make sure to select TPU from Edit > Notebook settings > Hardware accelerator'
#colab
# VERSION = "20200325" #@param ["1.5" , "20200325", "nightly"]
# !curl https://raw.githubusercontent.com/pytorch/xla/master/contrib/scripts/env-setup.py -o pytorch-xla-env-setup.py
# !python pytorch-xla-env-setup.py --version $VERSION
# colab
!pip install fastai2 --upgrade > /dev/null
!pip freeze | grep fastai2
#colab
!pip install git+https://github.com/butchland/fastai_xla_extensions > /dev/null
!pip freeze | grep fastai_xla_extensions
#colab
!pip install git+https://github.com/butchland/my_timesaver_utils > /dev/null
!pip freeze | grep my_timesaver_utils
```
### Import Libraries
```
%load_ext autoreload
%autoreload 2
from fastai_xla_extensions.core import *
from fastai2.vision.all import *
from my_timesaver_utils.profiling import *
```
### Setup data
```
path = untar_data(URLs.PETS)/'images'
```
### Loop through batch and walk through batch transforms
```
# from IPython.core.debugger import set_trace
# TRACE = True
orig_randtransform_call = RandTransform.__call__
def __call__(self, b, split_idx=None, **kwargs):
is_lighting_tfm = isinstance(self, LightingTfm)
if is_lighting_tfm:
# print(f'applying AffineCoordTfm call {self}')
# if TRACE: set_trace()
start_record('lighting_tfm_call')
results = orig_randtransform_call(self, b, split_idx, **kwargs)
if is_lighting_tfm:
end_record('lighting_tfm_call')
return results
setattr(RandTransform,'__call__', __call__)
# orig_normalize_encodes = Normalize.encodes
# def encodes(self, x:TensorImage):
# start_record('normalize_encodes')
# results = orig_normalize_encodes(self,x)
# end_record('normalize_encodes')
# return results
# setattr(Normalize,'encodes', encodes)
# def mycompose_tfms(x, tfms, is_enc=True, reverse=False, **kwargs):
# "Apply all `func_nm` attribute of `tfms` on `x`, maybe in `reverse` order"
# if reverse: tfms = reversed(tfms)
# for f in tfms:
# if not is_enc: f = f.decode
# if isinstance(f,AffineCoordTfm):
# print(f'applying {type(f)} {f} to {type(x)}')
# if TRACE:
# set_trace()
# x = f(x, **kwargs)
# return x
# @patch_to(Pipeline)
# def __call__(self, o): return mycompose_tfms(o, tfms=self.fs, split_idx=self.split_idx)
# TRACE = False
batch_tfms = [*aug_transforms(max_zoom=1.0, max_warp=0., max_rotate=0., max_lighting=0.2,do_flip=False)]
batch_tfms
batch_tfms[0].fs
```
```
pat = r'(.+)_\d+.jpg$'
```
Create Fastai DataBlock
_Note that batch transforms are currently
set to none as they seem to slow the training
on the TPU (for investigation)._
```
datablock = DataBlock(
blocks=(ImageBlock,CategoryBlock),
get_items=get_image_files,
splitter=RandomSplitter(seed=42),
get_y=using_attr(RegexLabeller(pat),'name'),
item_tfms=Resize(224),
batch_tfms=batch_tfms
)
print_prof_data()
datablock.summary(path)
print_prof_data()
```
### Setup DataLoaders
```
bs=256
dls = datablock.dataloaders(path,bs=bs)
dls.device
dls.train
train_dl = dls.train
train_dl.device
# def fetch_one_batch():
# if TRACE: set_trace()
# dl_iter = train_dl.__iter__()
# b = dl_iter.__next__()
# TRACE = False
clear_prof_data();print_prof_data()
# fetch_one_batch()
# print_prof_data()
clear_prof_data(); print_prof_data()
def fetch_all_batches():
for b in train_dl:
pass
fetch_all_batches()
print_prof_data()
times = get_prof_data('lighting_tfm_call')
# times2 = get_prof_data('normalize_encodes')
import matplotlib.pyplot as plt
times
plt.plot(times);
# times2
# plt.plot(times2);
```
| github_jupyter |
# Coral ID - Web Scraping
Live sales occur on the forums of Reef2Reef. Pictures of frags of corals (small pieces of corals) along with their names are posted for sale. The goal is to capture the pictures and the names to create a training set for a coral identification machine learning algorithm.
The below contains code to scrape these pictures and names from one particular thread on Reef2Reef. In the future, this can be generalized to scrape from other WWC threads on Reef2Reef and from other vendors.
```
# imports
import argparse
import csv
import os
import re
import time
from bs4 import BeautifulSoup as bs
import requests
from urllib.parse import urlparse
from urllib.request import urlretrieve
# page from which to parse and download images
url = 'https://www.reef2reef.com/threads/world-wide-corals-timesplitter-live-sale-3-000-frags-our-largest-ever.719326/page-15'
# author of the posts we are pulling
poster = 'WWC-BOT'
# location of the stored images
image_loc = 'worldwidecorals.sirv.com/TSLS_20'
# second thread for testing
url = 'https://www.reef2reef.com/threads/world-wide-corals-tax-craze-live-sale-2300-frags-discounted-beyond-belief.552524/page-24'
poster = 'WWC'
image_loc = 'worldwidecorals.sirv.com/Tax_Craze_2019'
url = 'https://www.reef2reef.com/threads/wwc-spring-lightning-sale-800-frags-up-to-75-off.712595/page-13'
#url = 'https://www.reef2reef.com/threads/wwc-spring-lightning-sale-800-frags-up-to-75-off.712595/page-22'
poster = 'WWC'
image_loc = 'worldwidecorals.sirv.com/Spring_Lightning_Sale_2020'
# check that the given url is valid
def is_url_valid(url):
"""
Check if the format of the given url is valid.
Checks for scheme and netloc, then checks for status code.
Parameters:
url (string): A string containing the url
Returns:
is_valid (boolean): True if valid, else False
"""
parsed = urlparse(url)
is_valid = False
if bool(parsed.netloc) and bool(parsed.scheme):
if requests.get(url).status_code == 200:
return True
return is_valid
# get all of the images from the given url
def get_all_images(url, poster, image_loc):
"""
Returns all image urls from the given url.
Parameters:
url (string): A string containing the url
poster (string): A string containing the Reef2Reef author name of
the post, such as 'WWC-BOT'
image_loc (string): A string containing the location of the images,
such as 'worldwidecorals.sirv.com/TSLS_20' from the data-url
for the image
Returns:
image_links (list): A list of [names, image urls] from the page
"""
soup = bs(requests.get(url).content, "html.parser")
soup_div = soup.find_all('div',
attrs={'class':'message-userContent lbContainer js-lbContainer',
'data-lb-caption-desc':re.compile(r'^%s'%poster)})
# extract links to each of the images
# when find an image, also extract the name for labels in training
images=[]
names=[]
for tt in soup_div:
img_found = 0
try:
t1 = tt.find_all('img')
for image in t1:
if image_loc in image['data-url']:
images.append('https://www.reef2reef.com' + image['src'])
img_found = 1
if img_found == 1:
t2 = tt.find_all('b')
for name in t2:
names.append(name.text)
except:
pass
names_trimmed = names[0::6]
# if the lengths of the two lists are the same, zip together
if len(names_trimmed) == len(images):
image_links = [list(i) for i in zip(names_trimmed, images)]
else:
image_links = []
print('WARNING: images and names are not the same length',
'\n', 'no image_links this page')
return image_links
def download_images(image_links):
"""
Downloads all images provided in the list of image names and urls.
Parameters:
image_links (list): A list of [names, image urls]
"""
for i in image_links:
r = requests.get(i[1])
filename = os.path.join('./scraped_images/',
urlparse(i[1]).query.split('%2F')[-1].split('.jpg')[0]+'.jpg')
with open(filename, 'wb') as outfile:
outfile.write(r.content)
# add the names of the corals and the corresponding filename to a csv file for later use
def output_names_files(image_links):
"""
Outputs a csv file with the coral name and filename.
Parameters:
image_links (list): A list of [names, image urls]
Returns:
coral_names_files.csv (file):
"""
with open('coral_names_files.csv', 'a', newline='') as f:
writer = csv.writer(f, delimiter='|')
writer.writerows(image_links)
output_names_files(image_links)
# determine the total number of pages in this forum thread
def get_num_pages(url):
"""
Returns the number of pages in this thread of the forum.
Parameters:
url (string): A string containing the url
Returns:
num_pages (int): The number of pages
"""
soup = bs(requests.get(url).content, "html.parser")
nums=[]
soup_ul = soup.find_all('ul', attrs={'class':'pageNav-main'})
for tt in soup_ul:
t1 = tt.find_all('a')
for num in t1:
try:
nums.append(int(num.text))
except:
pass
num_pages = max(nums)
return num_pages
get_num_pages(url)
# loop through all of the pages and get images from the entire forum thread
def main(url, poster, image_loc):
"""
Loops through the pages in this thread of the forum to get all images.
Parameters:
url (string): A string containing the url with the starting page
for scraping
poster (string): A string containing the Reef2Reef author name
of the post, such as 'WWC-BOT'
image_loc (string): A string containing the location of the
images, such as 'worldwidecorals.sirv.com/TSLS_20' from the
data-url for the image
"""
# find first page, last page, and base url
if is_url_valid(url):
last_page = get_num_pages(url)
base_url, first_page = url.split('/page-')
first_page = int(first_page)
# loop through pages from first to last, pausing periodically
print('Beginning scrape at page ', first_page)
for i in range(first_page, last_page+1):
# implement periodic pause
if i % 20 == 0:
print('pausing for 30 seconds at page ', i)
time.sleep(30)
# get url for the current page of the forum and scrape
current_url = base_url + '/page-' + str(i)
if is_url_valid(current_url):
image_links = get_all_images(current_url, poster, image_loc)
if image_links == []:
print('page ', i, ' has no image links')
download_images(image_links)
output_names_files(image_links)
else:
print('WARNING: page ', i, ' has invalid url')
print('End of scrape.')
```
| github_jupyter |
### 12. Encoder Decoder Model - ``NMT``
We are going to create a simple NMT model that will translate from spaniszh to english using the encoder decoder achitecture.
In this notebook we are going to look at the basics of NMT in tensorflow 2. We will then have a look on a step futher in by adding the `Attention` mechanism so that we get better results. The basic Encoder Decoder model looks as follows:

The seq2seq model consists of two sub-networks, the encoder and the decoder. The encoder, on the left hand, receives sequences from the source language as inputs and produces as a result a compact representation of the input sequence, trying to summarize or condense all its information. Then that output becomes an input or initial state of the decoder, which can also receive another external input. At each time step, the decoder generates an element of its output sequence based on the input received and its current state, as well as updating its own state for the next time step.
Mention that the input and output sequences are of fixed size but they do not have to match, the length of the input sequence may differ from that of the output sequence.
The critical point of this model is how to get the encoder to provide the most complete and meaningful representation of its input sequence in a single output element to the decoder. Because this vector or state is the only information the decoder will receive from the input to generate the corresponding output. The longer the input, the harder to compress in a single vector.
### Imports
```
import numpy as np
import typing
import pandas as pd
import tensorflow as tf
from tensorflow.keras.layers.experimental import preprocessing
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow import keras
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import re, os, time, unicodedata
tf.__version__
```
### Mounting the drive
```
from google.colab import drive
drive.mount('/content/drive')
file_path = "/content/drive/My Drive/NLP Data/seq2seq/spa-en/spa.txt"
os.path.exists(file_path)
```
We will use spainish as our source language and english as our target language in this example.
```
def unicode_to_ascii(s):
return ''.join(c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')
def preprocess_sentence(w):
w = unicode_to_ascii(w.lower().strip())
w = re.sub(r"([?.!,¿])", r" \1 ", w)
w = re.sub(r'[" "]+', " ", w)
w = re.sub(r"[^a-zA-Z?.!,¿]+", " ", w)
w = w.strip()
# Adding the start and end of sequences tokens
# w = '<sos> ' + w + ' <eos>'
return w
```
### Data and text processing.
We need to remove accents, lower case the sentences and replace everything with space except (a-z, A-Z, ".", "?", "!", ",").
```
INPUT_COLUMN = 'input'
TARGET_COLUMN = 'target'
TARGET_FOR_INPUT = 'target_for_input'
NUM_SAMPLES = 20000 #40000
MAX_VOCAB_SIZE = 20000
EMBEDDING_DIM = 128
HIDDEN_DIM= 1024
BATCH_SIZE = 64 # Batch size for training.
EPOCHS = 10 # Number of epochs to train for.
# Load the dataset: sentence in english, sentence in spanish
df=pd.read_csv(file_path, sep="\t", header=None, names=[TARGET_COLUMN, INPUT_COLUMN], usecols=[0,1],
nrows=NUM_SAMPLES)
# Preprocess the input data
input_data=df[INPUT_COLUMN].apply(lambda x : preprocess_sentence(x)).tolist()
# Preprocess and include the end of sentence token to the target text
target_data=df[TARGET_COLUMN].apply(lambda x : preprocess_sentence(x)+ ' <eos>').tolist()
# Preprocess and include a start of setence token to the input text to the decoder, it is rigth shifted
target_input_data=df[TARGET_COLUMN].apply(lambda x : '<sos> '+ preprocess_sentence(x)).tolist()
print(input_data[:5])
print(target_data[:5])
print(target_input_data[:5])
```
### Tokenization
* Tokenize the data, to convert the raw text into a sequence of integers. First, we create a Tokenizer object from the keras library and fit it to our text (one tokenizer for the input and another one for the output).
* Extract sequence of integers from the text: we call the ``text_to_sequence`` method of the tokenizer for every input and output text.
* Calculate the maximum length of the input and output sequences.
```
tokenizer_inputs = Tokenizer(
num_words = MAX_VOCAB_SIZE, filters=""
)
tokenizer_inputs.fit_on_texts(input_data)
input_sequences = tokenizer_inputs.texts_to_sequences(input_data)
input_max_len = max(len(s) for s in input_sequences)
print('max input length: ', input_max_len)
# Show some example of tokenize sentences, useful to check the tokenization
print(input_data[1000])
print(input_sequences[1000])
```
We can do the same thing to the output sequences.
```
# Create a tokenizer for the output texts and fit it to them
tokenizer_outputs = Tokenizer(num_words=MAX_VOCAB_SIZE, filters='')
tokenizer_outputs.fit_on_texts(target_data)
tokenizer_outputs.fit_on_texts(target_input_data)
# Tokenize and transform output texts to sequence of integers
target_sequences = tokenizer_outputs.texts_to_sequences(target_data)
target_sequences_inputs = tokenizer_outputs.texts_to_sequences(target_input_data)
# determine maximum length output sequence
target_max_len = max(len(s) for s in target_sequences)
print('max target length: ', target_max_len)
print(target_data[1000])
print(target_sequences[1000])
print(target_input_data[1000])
```
### Creating vocabularies
Using the tokenizer we have created previously we can retrieve the vocabularies, one to match word to integer (word2idx) and a second one to match the integer to the corresponding word (idx2word).
```
# get the word to index mapping for input language
word2idx_inputs = tokenizer_inputs.word_index
print('Found %s unique input tokens.' % len(word2idx_inputs))
# get the word to index mapping for output language
word2idx_outputs = tokenizer_outputs.word_index
print('Found %s unique output tokens.' % len(word2idx_outputs))
# store number of output and input words for later
# remember to add 1 since indexing starts at 1
num_words_output = len(word2idx_outputs) + 1
num_words_inputs = len(word2idx_inputs) + 1
# map indexes back into real words
# so we can view the results
idx2word_inputs = {v:k for k, v in word2idx_inputs.items()}
idx2word_outputs = {v:k for k, v in word2idx_outputs.items()}
```
### Padding Sequences
Padding the sentences: we need to pad zeros at the end of the sequences so that all sequences have the same length. Otherwise, we won't be able train the model on batches.
```
# pad the input sequences
encoder_inputs = pad_sequences(input_sequences,
maxlen=input_max_len, padding='post')
print("encoder_inputs.shape:", encoder_inputs.shape)
# pad the decoder input sequences
decoder_inputs = pad_sequences(target_sequences_inputs, maxlen=target_max_len, padding='post')
print("decoder_inputs[0]:", decoder_inputs[0])
print("decoder_inputs.shape:", decoder_inputs.shape)
# pad the target output sequences
decoder_targets = pad_sequences(target_sequences, maxlen=target_max_len, padding='post')
print("decoder_targets.shape:", decoder_targets.shape)
```
### Creating a Batch Data Generator
* Create a batch data generator: we want to train the model on batches, group of sentences, so we need to create a Dataset using the tf.data library and the function ``batch_on_slices`` on the input and output sequences.
```
BUFFER_SIZE = len(input_data)
dataset = tf.data.Dataset.from_tensor_slices(
(encoder_inputs, decoder_inputs, decoder_targets)
).shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True)
```
### Encoder Decoder Model.
For a better understanding, we can divide the model in three basic components:

* **The encoder:** Layers of recurrent units where in each time step, receive a an input token, collects relevant information and produce a hidden state. Depends on the type of RNN, in our example a LSTM, the unit "mixes" the current hidden state and the input and return an output, discarded, and a new hidden state.
* **The encoder vector:** it is the last hidden state of the encoder and it tries to contain as much of the useful input information as possible to help the decoder get the best results. It is only information from the input that the decoder will get.
* **The decoder:** Layers of recurrent units, i.e. LSTMs, where each unit produces an output at a time step t. The hidden state of the first unit is the encoder vector and the rest of units accept the hidden state from the previous unit. The output is calculated using a **``_softmax_``** function to obtain a probability for every token in the output vocabulary.
### Encoder Class
```
class Encoder(keras.Model):
def __init__(self, vocab_size, embedding_dim, hidden_dim):
super(Encoder, self).__init__()
self.hidden_dim = hidden_dim
self.embedding = keras.layers.Embedding(
vocab_size, embedding_dim
)
self.lstm = keras.layers.LSTM(hidden_dim,
return_sequences=True,
return_state=True
)
def call(self, input_sequence, states):
embedded = self.embedding(input_sequence)
output, h_0, c_0 = self.lstm(embedded, initial_state= states)
return output, h_0, c_0
def init_states(self, batch_size):
return(
tf.zeros([batch_size, self.hidden_dim]),
tf.zeros([batch_size, self.hidden_dim]),
)
```
### Decoder Class
```
class Decoder(keras.Model):
def __init__(self, vocab_size, embedding_dim, hidden_dim):
super(Decoder, self).__init__()
self.hidden_dim = hidden_dim
self.embedding = keras.layers.Embedding(
vocab_size, embedding_dim
)
self.lstm = keras.layers.LSTM(
hidden_dim, return_sequences=True, return_state=True
)
self.out = keras.layers.Dense(vocab_size)
def call(self, input_sequence, state):
embedded = self.embedding(input_sequence)
output, h_0, c_0 = self.lstm(embedded, initial_state=state)
logits = self.out(output)
return logits, h_0, c_0
```
Once our encoder and decoder are defined we can init them and set the initial hidden state. We have included a simple test, calling the encoder and decoder to check they works fine.
```
#Set the length of the input and output vocabulary
num_words_inputs = len(word2idx_inputs) + 1
num_words_output = len(word2idx_outputs) + 1
#Create the encoder
encoder = Encoder(num_words_inputs, EMBEDDING_DIM, HIDDEN_DIM)
# Get the initial states
initial_state = encoder.init_states(1)
# Call the encoder for testing
test_encoder_output = encoder(tf.constant(
[[1, 23, 4, 5, 0, 0]]), initial_state)
print(test_encoder_output[0].shape)
# Create the decoder
decoder = Decoder(num_words_output, EMBEDDING_DIM, HIDDEN_DIM)
# Get the initial states
de_initial_state = test_encoder_output[1:]
# Call the decoder for testing
test_decoder_output = decoder(tf.constant(
[[1, 3, 5, 7, 9, 0, 0, 0]]), de_initial_state)
print(test_decoder_output[0].shape)
```
### Loss function and metrics
Now we need to define a custom loss function to avoid taking into account the 0 values, padding values, when calculating the loss. And also we have to define a custom accuracy function.
```
def loss_func(targets, logits):
crossentropy = keras.losses.SparseCategoricalCrossentropy(
from_logits=True)
# Mask padding values, they do not have to compute for loss
mask = tf.math.logical_not(tf.math.equal(targets, 0))
mask = tf.cast(mask, dtype=tf.int64)
loss = crossentropy(targets, logits, sample_weight=mask)
return loss
def accuracy_fn(y_true, y_pred):
# y_pred shape is batch_size, seq length, vocab size
# y_true shape is batch_size, seq length
pred_values = keras.backend.cast(keras.backend.argmax(y_pred, axis=-1), dtype='int32')
correct = keras.backend.cast(keras.backend.equal(y_true, pred_values), dtype='float32')
# 0 is padding, don't include those
mask = keras.backend.cast(keras.backend.greater(y_true, 0),
dtype='float32')
n_correct = keras.backend.sum(mask * correct)
n_total = keras.backend.sum(mask)
return n_correct / n_total
```
### Training
As we mentioned before, we are interested in training the network in batches, therefore, we create a function that carries out the training of a batch of the data:
* Call the encoder for the batch input sequence, the output is the encoded vector.
* Set the decoder initial states to the encoded vector
* Call the decoder, taking the right shifted target sequence as input. The output are the logits (the softmax function is applied in the loss function)
* Calculate the loss and accuracy of the batch data
* Update the learnable parameters of the encoder and the decoder
update the optimizer
```
@tf.function
def train_step(
input_seq, target_seq_in, target_seq_out,
en_initial_states, optimizer
):
with tf.GradientTape() as tape:
# Get the encoder outputs
en_outputs = encoder(input_seq, en_initial_states)
# Set the encoder and decoder states
en_states = de_states = en_outputs[1:]
# Get the decoder outputs
de_outputs = decoder(target_seq_in, de_states)
# Take the actual output
logits = de_outputs[0]
# Calculate the loss function
loss = loss_func(target_seq_out, logits)
acc = accuracy_fn(target_seq_out, logits)
variables = encoder.trainable_variables + decoder.trainable_variables
gradients = tape.gradient(loss, variables)
optimizer.apply_gradients(zip(gradients, variables))
return loss, acc
```
Our train function receives three sequences:
**Input sequence:** array of integers of shape [batch_size, max_seq_len, embedding dim]. It is the input sequence to the encoder.
**target sequence:** array of integers of shape [batch_size, max_seq_len, embedding dim]. It is the target of our model, the output that we want for our model.
**Target input sequence:** array of integers of shape [batch_size, max_seq_len, embedding dim]. It is the input sequence to the decoder because we use Teacher Forcing.
### Oh Teacher Forcing
Teacher forcing is a training method critical to the development of deep learning models in NLP. It is a way for quickly and efficiently training recurrent neural network models that use the ground truth from a prior time step as input.
In a recurrent network usually the input to a RNN at the time step t is the output of the RNN in the previous time step, t-1. But with teacher forcing we can use the actual output to improve the learning capabilities of the model.
_"Teacher forcing works by using the actual or expected output from the training dataset at the current time step y(t) as input in the next time step X(t+1), rather than the output generated by the network. So, in our example, the input to the decoder is the target sequence right-shifted, the target output at time step t is the decoder input at time step t+1."_
When our model output do not vary from what was seen by the model during training, teacher forcing is very effective. But if we need a more "creative" model, where given an input sequence there can be several possible outputs, we should avoid this technique or apply it randomly (only in some random time steps).
Now, we can code the whole training process:
```
def fit(encoder, decoder, dataset, n_epochs, batch_size,
optimizer, checkpoint, checkpoint_prefix
):
losses =[]
accuracies = []
for e in range(n_epochs):
start = time.time()
en_initial_states = encoder.init_states(batch_size)
for batch, (input_seq, target_seq_in, target_seq_out) in enumerate(dataset.take(-1)):
loss, accuracy = train_step(input_seq, target_seq_in,
target_seq_out,
en_initial_states, optimizer)
if batch % 100 == 0:
losses.append(loss)
accuracies.append(accuracy)
print('Epoch {} Batch {} Loss {:.4f} Acc:{:.4f}'.format(e + 1, batch, loss.numpy(), accuracy.numpy()))
if (e + 1) % 2 == 0:
checkpoint.save(file_prefix = checkpoint_prefix)
print('Time taken for 1 epoch {:.4f} sec\n'.format(time.time() - start))
return losses, accuracies
```
We are almost ready, our last step include a call to the main train function and we create a checkpoint object to save our model. Because the training process require a long time to run, every two epochs we save it. Later we can restore it and use it to make predictions.
```
# Create an Adam optimizer and clips gradients by norm
optimizer = tf.keras.optimizers.Adam(clipnorm=5.0)
# Create a checkpoint object to save the model
checkpoint_dir = './training_ckpt_seq2seq'
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt")
checkpoint = tf.train.Checkpoint(optimizer=optimizer,
encoder=encoder,
decoder=decoder)
losses, accuracies = fit(encoder, decoder,
dataset, EPOCHS,
BATCH_SIZE, optimizer,
checkpoint, checkpoint_prefix)
```
### Model Evaulation
```
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15,5))
ax1.plot(losses, label='loss')
#plt.plot(results.history['val_loss'], label='val_loss')
ax1.set_title('Training Loss')
ax1.legend()
# accuracies
ax2.plot(accuracies, label='acc')
#plt.plot(results.history['val_accuracy_fn'], label='val_acc')
ax2.set_title('Training Accuracy')
ax2.legend()
plt.show()
```
### Inference
To restore the lastest checkpoint, saved model, you can run the following cell:
```
# restoring the latest checkpoint in checkpoint_dir
checkpoint_dir = './training_ckpt_seq2seq'
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt")
checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))
```
In the prediction step, our input is a sequence of length one, the ``sos`` token, then we call the encoder and ``decoder`` repeatedly until we get the eos token or reach the maximum length defined.
```
def predict(
input_text, encoder,
input_max_len, tokenizer_inputs,
word2idx_outputs, idx2word_outputs
):
if input_text is None:
input_text = input_data[np.random.choice(len(input_data))]
# Tokenize the input text
input_seq = tokenizer_inputs.texts_to_sequences([input_text])
# Pad the input sentence
input_seq = pad_sequences(input_seq, maxlen=input_max_len,
padding='post')
en_initial_states = encoder.init_states(1)
en_outputs = encoder(tf.constant(input_seq), en_initial_states)
de_input = tf.constant([[word2idx_outputs['<sos>']]])
de_state_h, de_state_c = en_outputs[1:]
out_words = []
while True:
de_output, de_state_h, de_state_c = decoder(
de_input, (de_state_h, de_state_c))
de_input = tf.argmax(de_output, -1)
out_words.append(idx2word_outputs[de_input.numpy()[0][0]])
if out_words[-1] == '<eos>' or len(out_words) >= 80:
break
return ' '.join(out_words)
for inp, trg in zip(input_data[1200: 1210], target_data[1200: 1210]):
predicted = predict(inp, encoder, input_max_len, tokenizer_inputs,
word2idx_outputs, idx2word_outputs)
print("> input: ", inp)
print("< predicted:", predicted)
print("< real trg:", trg)
print()
print('*' * 100)
print()
```
### Conclusion
In the next Notebook we are going to clone this notebook and have a look at the Encoder Decoder Model with attention. The data processing and preparation will remain the same, We are only going to change the model achitecture.
| github_jupyter |
```
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import ticker, cm
import numpy as np
import h5py
import pandas as pd
f = h5py.File("/Users/glmarschmann/.julia/dev/DEBmicroTrait/files/generic_rate_yield_trade_off.jld", "r")
yield45 = f["yield_45"].value
rate45 = f["rate_45"].value
power45 = rate45*4.2
fig_width = 3.0 # inches
golden_mean = (np.sqrt(5)-1.0)/2.0 # Aesthetic ratio
fig_height = 2.8# height in inches
dpi = 300.0 # Convert inch to pt
# Margins are specified as a fraction of axes size.
# May need to adjust (especially left and bottom) to accomodate axes labels/tickmarks
leftmargin = 0.15
bottommargin = 0.2
rightmargin = 0.05
topmargin = 0.1
# These two parameters are used for adjusting spacing between subplots (when used)
wspace = 0.2
hspace = 0.2
fig_size = [fig_width,fig_height]
params = {'backend': 'svg',
'axes.labelsize': 9,
'axes.titlesize': 10,
'legend.fontsize': 9,
'xtick.labelsize': 9,
'ytick.labelsize': 9,
'figure.figsize': fig_size,
'text.usetex': False,
'font.family':'sans-serif',
'font.sans-serif':'Arial',
'svg.fonttype':'none'}
plt.rcParams.update(params)
plt.figure(1)
plt.clf()
plt.axes([leftmargin,
bottommargin,
1.0 - rightmargin-leftmargin,
1.0 - topmargin-bottommargin])
plt.plot(yield45, rate45, '-', lw=2, color="k")
plt.axhline(y=max(rate45), linestyle='--',color="k")
#plt.axvline(x=max(yield45), linestyle='--',color="k")
plt.xscale('log',basex=10)
plt.yscale('log',basey=10)
#plt.xlabel(r"$\textnormal{Growth yield}\,\, [\,\textnormal{-}\,]$")
#plt.ylabel(r"$\textnormal{Growth power}\, \mathrm{[\Delta G\, C\textnormal{-} mol^{-1}h^{-1}]}$")
ax = plt.axes()
plt.xlabel("Growth yield []")
plt.ylabel("Growth power []")
#ax.set_xlim([0.25, 0.62])
#ax.set_ylim([5e-6, 1e0])
from matplotlib.ticker import StrMethodFormatter, NullFormatter
ax.xaxis.set_minor_formatter(StrMethodFormatter('{x:.1f}'))
ax.yaxis.set_tick_params(which='minor', bottom=False)
plt.savefig("/Users/glmarschmann/.julia/dev/DEBmicroTrait/plots/generic_power_yield.svg", format='svg')
df_fcr = pd.read_csv("/Users/glmarschmann/.julia/dev/DEBmicroTrait/files/isolates_fcr.csv")
#
df_fcr_p = df_fcr.loc[(df_fcr.response == "positive")]
df_fcr_n = df_fcr.loc[(df_fcr.response == "negative")]
df_fcr_u = df_fcr.loc[(df_fcr.response == "undefined")]
fig_width = 1.8 # inches
golden_mean = (np.sqrt(5)-1.0)/2.0 # Aesthetic ratio
fig_height = 2.14 # height in inches
dpi = 300.0 # Convert inch to pt
# Margins are specified as a fraction of axes size.
# May need to adjust (especially left and bottom) to accomodate axes labels/tickmarks
leftmargin = 0.15
bottommargin = 0.2
rightmargin = 0.05
topmargin = 0.1
# These two parameters are used for adjusting spacing between subplots (when used)
wspace = 0.2
hspace = 0.2
fig_size = [fig_width,fig_height]
params = {'backend': 'svg',
'axes.labelsize': 9,
'axes.titlesize': 10,
'legend.fontsize': 9,
'xtick.labelsize': 9,
'ytick.labelsize': 9,
'figure.figsize': fig_size,
'text.usetex': False,
'font.family':'sans-serif',
'font.sans-serif':'Arial'}
plt.rcParams.update(params)
plt.figure(1)
plt.clf()
plt.axes([leftmargin,
bottommargin,
1.0 - rightmargin-leftmargin,
1.0 - topmargin-bottommargin])
plt.scatter(df_fcr_p.Vcell, df_fcr_p.FCR, s=25, color='#007100', edgecolor='k', marker='^', label="")
plt.scatter(df_fcr_n.Vcell, df_fcr_n.FCR, s=25, color='#bd5e8b', edgecolor='k', marker='v', label="")
plt.scatter(df_fcr_u.Vcell, df_fcr_u.FCR, s=25, color='w', edgecolor='k', marker='s', label="Isolates")
ax = plt.gca()
ax = sns.regplot(x="Vcell", y="FCR", data=df_fcr, marker="", line_kws={"color":"k","alpha":1.0,"lw":1.5}, truncate=False)
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlim([1e-19, 1e-16])
ax.set_ylim([3e-2, 5e-1])
ax.set_xticks([1e-19, 1e-18, 1e-17, 1e-16])
ax.set_yticks([1e-1])
ax.set_yticklabels(["0.1"])
plt.legend(loc="lower left")
ax.set(xlabel="Cell volume []", ylabel="FCR []")
plt.savefig("/Users/glmarschmann/.julia/dev/DEBmicroTrait/plots/isolates_fcr.svg", format='svg')
df_bge = pd.read_csv("/Users/glmarschmann/.julia/dev/DEBmicroTrait/files/isolates_batch_model_BGE.csv")
df_bge = df_bge.dropna()
#
df_bge_p_sugars = df_bge.loc[(df_bge.response == "positive") & (df_bge.ontology == "Sugars")]
df_bge_p_organics = df_bge.loc[(df_bge.response == "positive") & (df_bge.ontology == "Organic acids")]
df_bge_p_aminos = df_bge.loc[(df_bge.response == "positive") & (df_bge.ontology == "Amino acids")]
df_bge_p_fattys = df_bge.loc[(df_bge.response == "positive") & (df_bge.ontology == "Fatty acids")]
df_bge_p_nucleos = df_bge.loc[(df_bge.response == "positive") & (df_bge.ontology == "Nucleotides")]
df_bge_p_auxins = df_bge.loc[(df_bge.response == "positive") & (df_bge.ontology == "Auxins")]
df_bge_n_sugars = df_bge.loc[(df_bge.response == "negative") & (df_bge.ontology == "Sugars")]
df_bge_n_organics = df_bge.loc[(df_bge.response == "negative") & (df_bge.ontology == "Organic acids")]
df_bge_n_aminos = df_bge.loc[(df_bge.response == "negative") & (df_bge.ontology == "Amino acids")]
df_bge_n_fattys = df_bge.loc[(df_bge.response == "negative") & (df_bge.ontology == "Fatty acids")]
df_bge_n_nucleos = df_bge.loc[(df_bge.response == "negative") & (df_bge.ontology == "Nucleotides")]
df_bge_n_auxins = df_bge.loc[(df_bge.response == "negative") & (df_bge.ontology == "Auxins")]
df_bge_u_sugars = df_bge.loc[(df_bge.response == "undefined") & (df_bge.ontology == "Sugars")]
df_bge_u_organics = df_bge.loc[(df_bge.response == "undefined") & (df_bge.ontology == "Organic acids")]
df_bge_u_aminos = df_bge.loc[(df_bge.response == "undefined") & (df_bge.ontology == "Amino acids")]
df_bge_u_fattys = df_bge.loc[(df_bge.response == "undefined") & (df_bge.ontology == "Fatty acids")]
df_bge_u_nucleos = df_bge.loc[(df_bge.response == "undefined") & (df_bge.ontology == "Nucleotides")]
df_bge_u_auxins = df_bge.loc[(df_bge.response == "undefined") & (df_bge.ontology == "Auxins")]
#
bge_grouped = df_bge.groupby(["response", "ontology"]).median()
df_bge_high = bge_grouped[bge_grouped.rgrowth > 0.041]
df_bge_low = bge_grouped[bge_grouped.rgrowth < 0.0407]
fig_width = 3.14 # inches
golden_mean = (np.sqrt(5)-1.0)/2.0 # Aesthetic ratio
fig_height = fig_width*golden_mean # height in inches
dpi = 300.0
# Margins are specified as a fraction of axes size.
# May need to adjust (especially left and bottom) to accomodate axes labels/tickmarks
leftmargin = 0.15
bottommargin = 0.2
rightmargin = 0.05
topmargin = 0.1
# These two parameters are used for adjusting spacing between subplots (when used)
wspace = 0.2
hspace = 0.2
fig_size = [fig_width,fig_height]
params = {'backend': 'svg',
'axes.labelsize': 8,
'axes.titlesize': 10,
'legend.fontsize': 6,
'xtick.labelsize': 8,
'ytick.labelsize': 8,
'figure.figsize': fig_size}
plt.rcParams.update(params)
plt.figure(1)
plt.clf()
plt.axes([leftmargin,
bottommargin,
1.0 - rightmargin-leftmargin,
1.0 - topmargin-bottommargin])
plt.scatter(np.median(df_bge_p_sugars.BGE), np.median(df_bge_p_sugars.rgrowth), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_p_organics.BGE), np.median(df_bge_p_organics.rgrowth), s=60, c='#1b9e77', edgecolor='k',marker='^', label="")
plt.scatter(np.median(df_bge_p_aminos.BGE), np.median(df_bge_p_aminos.rgrowth), s=60, c='#66a61e',edgecolor='k', marker='^',label="")
plt.scatter(np.median(df_bge_p_fattys.BGE), np.median(df_bge_p_fattys.rgrowth), s=60, c='#7570b3',edgecolor='k', marker='^',label="")
plt.scatter(np.median(df_bge_p_nucleos.BGE), np.median(df_bge_p_nucleos.rgrowth), s=60, c='#e7298a',edgecolor='k', marker='^',label="")
plt.scatter(np.median(df_bge_p_auxins.BGE), np.median(df_bge_p_auxins.rgrowth), s=60, c='#e6ab02',edgecolor='k', marker='^',label="")
plt.scatter(np.median(df_bge_n_sugars.BGE), np.median(df_bge_n_sugars.rgrowth), s=60, c='#d95f02',edgecolor='k', marker='v',label="")
plt.scatter(np.median(df_bge_n_organics.BGE), np.median(df_bge_n_organics.rgrowth), s=60, c='#1b9e77',edgecolor='k', marker='v',label="")
plt.scatter(np.median(df_bge_n_aminos.BGE), np.median(df_bge_n_aminos.rgrowth), s=60, c='#66a61e',edgecolor='k', marker='v',label="")
plt.scatter(np.median(df_bge_n_fattys.BGE), np.median(df_bge_n_fattys.rgrowth), s=60, c='#7570b3',edgecolor='k', marker='v',label="")
plt.scatter(np.median(df_bge_n_nucleos.BGE), np.median(df_bge_n_nucleos.rgrowth), s=60, c='#e7298a',edgecolor='k', marker='v',label="")
plt.scatter(np.median(df_bge_n_auxins.BGE), np.median(df_bge_n_auxins.rgrowth), s=60, c='#e6ab02',edgecolor='k', marker='v',label="")
plt.scatter(np.median(df_bge_u_sugars.BGE), np.median(df_bge_u_sugars.rgrowth), s=60, c='#d95f02',edgecolor='k', marker='s', label="Sugars")
plt.scatter(np.median(df_bge_u_organics.BGE), np.median(df_bge_u_organics.rgrowth), s=60, c='#1b9e77',edgecolor='k', marker='s', label="Organic acids")
plt.scatter(np.median(df_bge_u_aminos.BGE), np.median(df_bge_u_aminos.rgrowth), s=60, c='#66a61e',edgecolor='k', marker='s', label="Amino acids")
plt.scatter(np.median(df_bge_u_fattys.BGE), np.median(df_bge_u_fattys.rgrowth), s=60, c='#7570b3',edgecolor='k', marker='s', label="Fatty acids")
plt.scatter(np.median(df_bge_u_nucleos.BGE), np.median(df_bge_u_nucleos.rgrowth), s=60, c='#e7298a',edgecolor='k', marker='s', label="Nucleotides")
plt.scatter(np.median(df_bge_u_auxins.BGE), np.median(df_bge_u_auxins.rgrowth), s=60, c='#e6ab02',edgecolor='k', marker='s', label="Auxins")
plt.legend()
#
ax = plt.gca()
ax = sns.regplot(x="BGE", y="rgrowth", data=df_bge_high, marker="", line_kws={"color":"#a6761d","alpha":1.0,"lw":1.5})
ax = sns.regplot(x="BGE", y="rgrowth", data=df_bge_low, marker="", line_kws={"color":"#666666","alpha":1.0,"lw":1.5})
ax.set_xlim([0.3, 0.6])
ax.set_ylim([0.001, 0.085])
ax.set(ylabel=r'$\textnormal{Growth rate}\, [\mathrm{h^{-1}}]$', xlabel=r'$\textnormal{Carbon use efficiency}\, [\,\textnormal{-}\,]$')
ax.set_yticks([0.005, 0.02, 0.04, 0.06, 0.08])
ax.set_yticklabels(["0.01", "0.02", "0.04", "0.06", "0.08"])
ax.set_xticks([0.3, 0.4, 0.5, 0.6])
ax.set_xticklabels(["0.3", "0.4", "0.5", "0.6"])
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
legend_elements = [
Line2D([0], [0], marker='_', color='#d95f02', label='Sugars',
markerfacecolor='#d95f02', markersize=6),
Line2D([0], [0], marker='_', color='#1b9e77', label='Organic acids',
markerfacecolor='#1b9e77', markersize=6),
Line2D([0], [0], marker='_', color='#66a61e', label='Amino acids',
markerfacecolor='#66a61e', markersize=6),
Line2D([0], [0], marker='_', color='#7570b3', label='Fatty acids',
markerfacecolor='#7570b3', markersize=6),
Line2D([0], [0], marker='_', color='#e7298a', label='Nucleotides',
markerfacecolor='#e7298a', markersize=6),
Line2D([0], [0], marker='_', color='#e6ab02', label='Auxins',
markerfacecolor='#e6ab02', markersize=6),
Line2D([0], [0], marker='^', color='w', label='Positive',
markerfacecolor='none', mec='k', markersize=6),
Line2D([0], [0], marker='v', color='w', label='Negative',
markerfacecolor='none', mec='k', markersize=6),
Line2D([0], [0], marker='s', color='w', label='Undefined',
markerfacecolor='none', mec='k', markersize=6),
]
ax.legend(handles=legend_elements)
plt.savefig("/Users/glmarschmann/.julia/dev/DEBmicroTrait/plots/batch_rate_cue_1.svg", format='svg')
df_bge = pd.read_csv("/Users/glmarschmann/.julia/dev/DEBmicroTrait/files/isolates_batch_model_BGE_new.csv")
df_bge = df_bge.dropna()
df_bge['BP'] = df_bge['BP'].apply(lambda x: x*1e9)
df_bge['BR'] = df_bge['BR'].apply(lambda x: x*1e9)
df_bge['BP'] = df_bge['BP'].apply(lambda x: np.log(x))
df_bge['BR'] = df_bge['BR'].apply(lambda x: np.log(x))
#
df_bge_high = df_bge[df_bge.rgrowth > 0.041]
df_bge_low = df_bge[df_bge.rgrowth < 0.0407]
df_bge
df_bge_high_p = df_bge_high.loc[(df_bge_high.response == "positive")]
df_bge_high_n = df_bge_high.loc[(df_bge_high.response == "negative")]
df_bge_high_u = df_bge_high.loc[(df_bge_high.response == "undefined")]
bge_high_grouped_p = df_bge_high_p.groupby(["isolate"]).median()
bge_high_grouped_n = df_bge_high_n.groupby(["isolate"]).median()
bge_high_grouped_u = df_bge_high_u.groupby(["isolate"]).median()
df_bge_low_p = df_bge_low.loc[(df_bge_low.response == "positive")]
df_bge_low_n = df_bge_low.loc[(df_bge_low.response == "negative")]
df_bge_low_u = df_bge_low.loc[(df_bge_low.response == "undefined")]
bge_low_grouped_p = df_bge_low_p.groupby(["isolate"]).median()
bge_low_grouped_n = df_bge_low_n.groupby(["isolate"]).median()
bge_low_grouped_u = df_bge_low_u.groupby(["isolate"]).median()
bge_high_iso = bge_high_grouped_p.append([bge_high_grouped_n, bge_high_grouped_u])
bge_low_iso = bge_low_grouped_p.append([bge_low_grouped_n, bge_low_grouped_u])
import matplotlib.ticker
class OOMFormatter(matplotlib.ticker.ScalarFormatter):
def __init__(self, order=0, fformat="%1.1f", offset=True, mathText=True):
self.oom = order
self.fformat = fformat
matplotlib.ticker.ScalarFormatter.__init__(self,useOffset=offset,useMathText=mathText)
def _set_order_of_magnitude(self):
self.orderOfMagnitude = self.oom
def _set_format(self, vmin=None, vmax=None):
self.format = self.fformat
if self._useMathText:
self.format = r'$\mathdefault{%s}$' % self.format
plt.rcParams.update(params)
plt.figure(1)
plt.clf()
plt.axes([leftmargin,
bottommargin,
1.0 - rightmargin-leftmargin,
1.0 - topmargin-bottommargin])
plt.scatter(bge_high_grouped_p.BR, bge_high_grouped_p.BP, s=bge_high_grouped_p.BGE*50, marker='^', color='#007100', edgecolor='k', label="")
plt.scatter(bge_high_grouped_n.BR, bge_high_grouped_n.BP, s=bge_high_grouped_n.BGE*50, marker='v', color='#bd5e8b', edgecolor='k', label="")
plt.scatter(bge_high_grouped_u.BR, bge_high_grouped_u.BP, s=bge_high_grouped_u.BGE*50, marker='s', color='w', edgecolor='k', label="")
plt.scatter(bge_low_grouped_p.BR, bge_low_grouped_p.BP, s=bge_low_grouped_p.BGE*50, marker='^', color='#007100', edgecolor='k', label="Positive")
plt.scatter(bge_low_grouped_n.BR, bge_low_grouped_n.BP, s=bge_low_grouped_n.BGE*50, marker='v', color='#bd5e8b', edgecolor='k', label="Negative")
plt.scatter(bge_low_grouped_u.BR, bge_low_grouped_u.BP, s=bge_low_grouped_u.BGE*50, marker='s', color='w', edgecolor='k', label="Undefined")
ax = plt.gca()
ax.set_xlim([0.2, 3.5])
ax.set_ylim([0.001, 3.5])
ax.set_yticks([0.1,1,2,3])
ax.set_yticklabels(["1","10", "20", "30"])
ax.set_xticks([0.5,1,2,3])
ax.set_xticklabels(["1","10", "20", "30"])
ax = sns.regplot(x="BR", y="BP", data=bge_high_iso, marker="", line_kws={"color":"#a6761d","alpha":1.0,"lw":1.5}, ci=95, truncate=False)
ax = sns.regplot(x="BR", y="BP", data=bge_low_iso, marker="", line_kws={"color":"#666666","alpha":1.0,"lw":1.5},ci=95, truncate=True)
ax.set(xlabel=r"$\textnormal{Biomass respiration}\, [\mathrm{nmol\, C\, cell^{-1}h^{-1}}]$", ylabel=r"$\textnormal{Biomass production}\, [\mathrm{nmol\, C\, cell^{-1}h^{-1}}]$")
plt.legend(loc="lower right")
plt.savefig("/Users/glmarschmann/.julia/dev/DEBmicroTrait/plots/batch_resp_1.svg", format='svg')
np.lo
df_levin = pd.read_csv("/Users/glmarschmann/.julia/dev/DEBmicroTrait/files/isolates_batch_model_bge_growth_levin.csv")
df_levin_p = df_levin.loc[(df_levin.response == "positive")]
df_levin_n = df_levin.loc[(df_levin.response == "negative")]
df_levin_u = df_levin.loc[(df_levin.response == "undefined")]
plt.rcParams.update(params)
plt.figure(1)
plt.clf()
plt.axes([leftmargin,
bottommargin,
1.0 - rightmargin-leftmargin,
1.0 - topmargin-bottommargin])
plt.scatter(df_levin_p.levins,df_levin_p.BGE_med, s=df_levin_p.rgrowth_med*800, marker='^', color='w', edgecolor='k', label="Positive")
plt.scatter(df_levin_n.levins, df_levin_n.BGE_med, s=df_levin_n.rgrowth_med*800, marker='v', color='w', edgecolor='k', label="Negative")
plt.scatter(df_levin_u.levins, df_levin_u.BGE_med, s=df_levin_u.rgrowth_med*800, marker='s', color='w', edgecolor='k', label="Undefined")
plt.legend()
ax = plt.gca()
ax = sns.regplot(x="levins", y="BGE_med", data=df_levin, marker="", line_kws={"color":"k","alpha":1.0,"lw":1.5})
ax.set(xlabel="Levins index [-]", ylabel="Carbon use efficieny [-]")
plt.savefig("/Users/glmarschmann/.julia/dev/DEBmicroTrait/plots/batch_levins.svg", format='svg')
var = [6,5,4,3,2,1]
rel_inf = [39.47, 18.71, 14.93, 12.18, 10.33, 3.71]
fig_height = 3.14 # inches
golden_mean = (np.sqrt(5)-1.0)/2.0 # Aesthetic ratio
fig_wifth = fig_height*golden_mean # height in inches
dpi = 300.0 # Convert inch to pt
# Margins are specified as a fraction of axes size.
# May need to adjust (especially left and bottom) to accomodate axes labels/tickmarks
leftmargin = 0.15
bottommargin = 0.2
rightmargin = 0.05
topmargin = 0.1
# These two parameters are used for adjusting spacing between subplots (when used)
wspace = 0.2
hspace = 0.2
fig_size = [fig_width,fig_height]
params = {'backend': 'svg',
'axes.labelsize': 8,
'axes.titlesize': 10,
'legend.fontsize': 6,
'xtick.labelsize': 8,
'ytick.labelsize': 8,
'figure.figsize': fig_size}
plt.rcParams.update(params)
plt.figure(1)
plt.clf()
plt.axes([leftmargin,
bottommargin,
1.0 - rightmargin-leftmargin,
1.0 - topmargin-bottommargin])
plt.scatter(x=rel_inf, y=var, s=40, marker='x', color='k', edgecolor='k')
plt.grid(True)
plt.ylabel("")
plt.xlabel("Mean decrease accuracy")
ax = plt.gca()
ax.invert_xaxis()
plt.savefig("/Users/glmarschmann/.julia/dev/DEBmicroTrait/plots/rf_batch_cue.svg", format='svg')
var = [6,5,4,3,2,1]
rel_inf = [45.34, 21.21, 16.43, 7.64, 5.34, 1.72]
plt.rcParams.update(params)
plt.figure(1)
plt.clf()
plt.axes([leftmargin,
bottommargin,
1.0 - rightmargin-leftmargin,
1.0 - topmargin-bottommargin])
plt.scatter(x=rel_inf, y=var, s=40, marker='x', color='k', edgecolor='k')
plt.grid(True)
plt.ylabel("")
plt.xlabel("Mean decrease accuracy")
ax = plt.gca()
ax.invert_xaxis()
plt.savefig("/Users/glmarschmann/.julia/dev/DEBmicroTrait/plots/rf_batch_growth.svg", format='svg')
df = pd.read_csv("/Users/glmarschmann/.julia/dev/DEBmicroTrait/first_manuscript/files_pub/benchmark_protein_synthesis.csv")
df.head()
plt.rcParams.update(params)
plt.figure(1)
plt.clf()
plt.axes([leftmargin,
bottommargin,
1.0 - rightmargin-leftmargin,
1.0 - topmargin-bottommargin])
plt.plot(df["k_E_model"], df["k_E"], 'o', mfc='none', mec='k', ms=5, label="Dethlefsen and Schmidt (2007)")
x = np.linspace(1e-1,1e1,100)
y = x
y1 = np.exp(0.023)*x**1.13
plt.plot(x, y, '--', c='k', label="")
plt.plot(x, y1, '-', c='k', label="")
plt.grid(True)
plt.xscale('log')
plt.yscale('log')
plt.ylabel(r"Translation power $[h^{-1}]$")
plt.xlabel(r"Translation power predicted $[h^{-1}]$")
plt.legend()
plt.savefig("/Users/glmarschmann/.julia/dev/DEBmicroTrait/first_manuscript/plots/benchmark_protein_synthesis.svg", format='svg')
from sympy import *
kE, yEV, y, kM, yEM = symbols('kE yEV y kM yEM', positive=True)
r_plus = -kE*(yEV*y-1) + 2*kE*kM*yEM*y/(kE*(yEV*y-1))
drdy = -kE*yEV*(y*yEV-1)**2-2*kM*yEM
ymax = (sqrt(2*kM*yEM/(kE*yEV))+1)*1/yEV
rmax = symbols('rmax', positive=True)
yrmax,b = solve(rmax + (-kE*(yEV*y-1) + 2*kE*kM*yEM*y/(kE*(yEV*y-1))) , y)
yrmax.subs([(kM, 0.001),(yEM,1), (kE, 0.1), (yEV, 1.01), (rmax, 0.3)])
expr = drdy.subs([(kM, 0.001),(yEM,1), (kE, 0.1), (yEV, 1.01)])
integrate(expr,(y,1.0,0.6) )
f = h5py.File("/Users/glmarschmann/.julia/dev/DEBmicroTrait/files/power_yield_tradeoff.jld", "r")
kEval = f["kE"].value
yEVval = f["yEV"].value
rmaxval = f["gmax"].value
kMval = f["kM"].value
kMvalmed = np.median(kMval)
kMvalmed = 0.2
L = np.zeros((len(kEval),len(yEVval)))
for i in range(0,len(kEval)):
for j in range(0,len(yEVval)):
y2 = yrmax.subs([(kM, kMvalmed),(yEM,1), (kE, kEval[i]), (yEV, yEVval[j]), (rmax, rmaxval[i])])
y1 = ymax.subs([(kM, kMvalmed),(yEM,1), (kE, kEval[i]), (yEV, yEVval[j])])
expr = drdy.subs([(kM, kMvalmed),(yEM,1), (kE, kEval[i]), (yEV, yEVval[j])])
L[i,j] = integrate(expr,(y,y1,y2) )
df_ps = pd.read_csv("/Users/glmarschmann/.julia/dev/DEBmicroTrait/files/isolates_protein_synthesis.csv")
df_ps_p = df_ps.loc[(df_ps.response == "positive")]
df_ps_n = df_ps.loc[(df_ps.response == "negative")]
df_ps_u = df_ps.loc[(df_ps.response == "undefined")]
fig_width = 2.14 # inches
golden_mean = (np.sqrt(5)-1.0)/2.0 # Aesthetic ratio
fig_height = 1.94062672467467 # height in inches
dpi = 300.0 # Convert inch to pt
# Margins are specified as a fraction of axes size.
# May need to adjust (especially left and bottom) to accomodate axes labels/tickmarks
leftmargin = 0.15
bottommargin = 0.2
rightmargin = 0.05
topmargin = 0.1
# These two parameters are used for adjusting spacing between subplots (when used)
wspace = 0.2
hspace = 0.2
fig_size = [fig_width,fig_height]
params = {'backend': 'svg',
'axes.labelsize': 8,
'axes.titlesize': 10,
'legend.fontsize': 6,
'xtick.labelsize': 8,
'ytick.labelsize': 8,
'figure.figsize': fig_size}
plt.rcParams.update(params)
plt.figure(1)
plt.clf()
plt.axes([leftmargin,
bottommargin,
1.0 - rightmargin-leftmargin,
1.0 - topmargin-bottommargin])
from numpy import ma
L = ma.masked_where(L <= 0, L)
from matplotlib import ticker, cm
lev_exp = np.arange(np.floor(np.log10(L.min())),
np.ceil(np.log10(L.max())))
levs = [0.005,0.01,0.05, 0.1, 0.15, 0.2, 0.3]
ax = plt.gca()
cs = ax.contourf(kEval, yEVval, L, levs, cmap=cm.Greys)
ax.scatter(df_ps_p.k_E, df_ps_p.y_EV, s=df_ps_p.Vcell*1e18, color='#e41a1c', edgecolor='k',marker='^', label="")
ax.scatter(df_ps_n.k_E, df_ps_n.y_EV, s=df_ps_n.Vcell*1e18, color='#e41a1c', edgecolor='k',marker='v', label="")
ax.scatter(df_ps_u.k_E, df_ps_u.y_EV, s=df_ps_u.Vcell*1e18, color='#e41a1c', edgecolor='k',marker='s', label="Isolates")
ax.set_xlim([0.6, 4])
ax.set_ylim([1.0, 3])
ax.set_xticks([1,2,3,4])
ax.set_xticklabels(["1","2", "3", "4"])
cbar = plt.colorbar(cs)
ax.set(xlabel=r"$k_E [h^{-1}]$", ylabel=r"y_{EV} [-]")
plt.savefig("/Users/glmarschmann/.julia/dev/DEBmicroTrait/plots/protein_synthesis_contour.svg", format='svg')
kEiso
plt.scatter(kEiso, yEViso)
yEViso
kMiso
df_low = pd.read_csv("/Users/glmarschmann/.julia/dev/DEBmicroTrait/files/isolates_batch_model_bge_low.csv")
df_high = pd.read_csv("/Users/glmarschmann/.julia/dev/DEBmicroTrait/files/isolates_batch_model_bge_high.csv")
#df_low['yields'] = df_low['yields'].apply(lambda x: np.log(x))
#df_low['rho'] = df_low['rho'].apply(lambda x: np.log(x))
#df_high['yields'] = df_high['yields'].apply(lambda x: np.log(x))
#df_high['rho'] = df_high['rho'].apply(lambda x: np.log(x))
np.median(df_high["KD"])
plt.rcParams.update(params)
plt.figure(1)
plt.clf()
plt.axes([leftmargin,
bottommargin,
1.0 - rightmargin-leftmargin,
1.0 - topmargin-bottommargin])
plt.scatter(df_low.yields,df_low.rho,s=12, marker='o', color='w', edgecolor='k')
ax = plt.gca()
#ax.set(yscale='log')
#ax.set(xscale='log')
ax.set_xlim([-1.3, -0.25])
ax.set_ylim([-11, -1])
ax = sns.regplot(x="yields", y="rho", data=df_low, marker="", line_kws={"color":"k","alpha":1.0,"lw":1.5}, order=1)
ax.set(xlabel="Assimilation yield [-]", ylabel="Transporter density [-]")
plt.scatter(df_high.yields,df_high.rho,s=12, marker='o', color='w', edgecolor='k')
ax = plt.gca()
#ax.set(yscale='log')
#ax.set(xscale='log')
#ax.set_xlim([-1.3, -0.25])
#ax.set_ylim([-11, -1])
ax = sns.regplot(x="yields", y="rho", data=df_high, marker="", line_kws={"color":"k","alpha":1.0,"lw":1.5}, order=2)
ax.set(xlabel="Assimilation yield [-]", ylabel="Transporter density [-]")
df_bge = pd.read_csv("/Users/glmarschmann/.julia/dev/DEBmicroTrait/files/isolates_batch_model_bge_all.csv")
df_bge = df_bge.dropna()
df_bge["yields"] = df_bge['yield']
#
df_bge_p_sugars = df_bge.loc[(df_bge.response == "positive") & (df_bge.ontology == "Sugars")]
df_bge_p_organics = df_bge.loc[(df_bge.response == "positive") & (df_bge.ontology == "Organic acids")]
df_bge_p_aminos = df_bge.loc[(df_bge.response == "positive") & (df_bge.ontology == "Amino acids")]
df_bge_p_fattys = df_bge.loc[(df_bge.response == "positive") & (df_bge.ontology == "Fatty acids")]
df_bge_p_nucleos = df_bge.loc[(df_bge.response == "positive") & (df_bge.ontology == "Nucleotides")]
df_bge_p_auxins = df_bge.loc[(df_bge.response == "positive") & (df_bge.ontology == "Auxins")]
df_bge_n_sugars = df_bge.loc[(df_bge.response == "negative") & (df_bge.ontology == "Sugars")]
df_bge_n_organics = df_bge.loc[(df_bge.response == "negative") & (df_bge.ontology == "Organic acids")]
df_bge_n_aminos = df_bge.loc[(df_bge.response == "negative") & (df_bge.ontology == "Amino acids")]
df_bge_n_fattys = df_bge.loc[(df_bge.response == "negative") & (df_bge.ontology == "Fatty acids")]
df_bge_n_nucleos = df_bge.loc[(df_bge.response == "negative") & (df_bge.ontology == "Nucleotides")]
df_bge_n_auxins = df_bge.loc[(df_bge.response == "negative") & (df_bge.ontology == "Auxins")]
df_bge_u_sugars = df_bge.loc[(df_bge.response == "undefined") & (df_bge.ontology == "Sugars")]
df_bge_u_organics = df_bge.loc[(df_bge.response == "undefined") & (df_bge.ontology == "Organic acids")]
df_bge_u_aminos = df_bge.loc[(df_bge.response == "undefined") & (df_bge.ontology == "Amino acids")]
df_bge_u_fattys = df_bge.loc[(df_bge.response == "undefined") & (df_bge.ontology == "Fatty acids")]
df_bge_u_nucleos = df_bge.loc[(df_bge.response == "undefined") & (df_bge.ontology == "Nucleotides")]
df_bge_u_auxins = df_bge.loc[(df_bge.response == "undefined") & (df_bge.ontology == "Auxins")]
#
bge_grouped = df_bge.groupby(["response", "ontology"]).median()
df_bge_high = bge_grouped[bge_grouped.rgrowth > 0.055]
df_bge_low = bge_grouped[bge_grouped.rgrowth < 0.0407]
df_bge.loc[df_bge['rgrowth'] >= 0.055, 'growthregime'] = 'high'
df_bge.loc[df_bge['rgrowth'] < 0.0407, 'growthregime'] = 'low'
#plt.scatter(np.median(df_bge_p_sugars.rassim), np.median(df_bge_p_sugars.rgrowth), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_sugars.rassim), np.median(df_bge_n_sugars.rgrowth), s=60, color='#d95f02', edgecolor='k', marker='v', label="")
plt.scatter(np.median(df_bge_u_sugars.rassim), np.median(df_bge_u_sugars.rgrowth), s=60, color='#d95f02', edgecolor='k', marker='s', label="")
plt.scatter(np.median(df_bge_p_aminos.rassim), np.median(df_bge_p_aminos.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_aminos.rassim), np.median(df_bge_n_aminos.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='v', label="")
plt.scatter(np.median(df_bge_u_aminos.rassim), np.median(df_bge_u_aminos.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='s', label="")
#plt.scatter(np.median(df_bge_p_fattys.rassim), np.median(df_bge_p_fattys.rgrowth), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_n_fattys.rassim), np.median(df_bge_n_fattys.rgrowth), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_u_fattys.rassim), np.median(df_bge_u_fattys.rgrowth), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_p_organics.rassim), np.median(df_bge_p_organics.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_n_organics.rassim), np.median(df_bge_n_organics.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_u_organics.rassim), np.median(df_bge_u_organics.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_p_nucleos.rassim), np.median(df_bge_p_nucleos.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_n_nucleos.rassim), np.median(df_bge_n_nucleos.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_u_nucleos.rassim), np.median(df_bge_u_nucleos.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_p_auxins.rassim), np.median(df_bge_p_auxins.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_n_auxins.rassim), np.median(df_bge_n_auxins.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_u_auxins.rassim), np.median(df_bge_u_auxins.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
ax = plt.gca()
ax.set_ylim([5e-2, 8e-2])
ax = sns.regplot(x="rassim", y="rgrowth", data=df_bge_high, marker="", line_kws={"color":"#a6761d","alpha":1.0,"lw":1.5})
#ax = sns.regplot(x="rassim", y="rgrowth", data=df_bge_low, marker="", line_kws={"color":"#666666","alpha":1.0,"lw":1.5})
ax.set_xlim([1.2e-3, 1.6e-3])
#ax.set(yscale='log')
#ax.set(xscale='log')
#plt.scatter(np.median(df_bge_p_sugars.rassim), np.median(df_bge_p_sugars.rgrowth), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_n_sugars.rassim), np.median(df_bge_n_sugars.rgrowth), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_u_sugars.rassim), np.median(df_bge_u_sugars.rgrowth), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_p_aminos.rassim), np.median(df_bge_p_aminos.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_n_aminos.rassim), np.median(df_bge_n_aminos.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_u_aminos.rassim), np.median(df_bge_u_aminos.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_p_fattys.rassim), np.median(df_bge_p_fattys.rgrowth), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_fattys.rassim), np.median(df_bge_n_fattys.rgrowth), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_u_fattys.rassim), np.median(df_bge_u_fattys.rgrowth), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_p_organics.rassim), np.median(df_bge_p_organics.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_organics.rassim), np.median(df_bge_n_organics.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_u_organics.rassim), np.median(df_bge_u_organics.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_p_nucleos.rassim), np.median(df_bge_p_nucleos.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_nucleos.rassim), np.median(df_bge_n_nucleos.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_u_nucleos.rassim), np.median(df_bge_u_nucleos.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_p_auxins.rassim), np.median(df_bge_p_auxins.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_auxins.rassim), np.median(df_bge_n_auxins.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_u_auxins.rassim), np.median(df_bge_u_auxins.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
ax = plt.gca()
ax.set_ylim([5e-3, 0.03])
#ax = sns.regplot(x="rassim", y="rgrowth", data=df_bge_high, marker="", line_kws={"color":"#a6761d","alpha":1.0,"lw":1.5})
ax = sns.regplot(x="rassim", y="rgrowth", data=df_bge_low, marker="", line_kws={"color":"#666666","alpha":1.0,"lw":1.5}, order=1)
ax.set_xlim([1e-7, 5e-3])
ax.set(yscale='log')
ax.set(xscale='log')
plt.scatter(np.median(df_bge_p_sugars.rassim), np.median(df_bge_p_sugars.Vmax/df_bge_p_sugars.KD), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_sugars.rassim), np.median(df_bge_n_sugars.Vmax/df_bge_n_sugars.KD), s=60, color='#d95f02', edgecolor='k', marker='v', label="")
plt.scatter(np.median(df_bge_u_sugars.rassim), np.median(df_bge_u_sugars.Vmax/df_bge_u_sugars.KD), s=60, color='#d95f02', edgecolor='k', marker='s', label="")
plt.scatter(np.median(df_bge_p_aminos.rassim), np.median(df_bge_p_aminos.Vmax/df_bge_p_aminos.KD), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_aminos.rassim), np.median(df_bge_n_aminos.Vmax/df_bge_n_aminos.KD), s=60, color='#66a61e', edgecolor='k', marker='v', label="")
plt.scatter(np.median(df_bge_u_aminos.rassim), np.median(df_bge_u_aminos.Vmax/df_bge_u_aminos.KD), s=60, color='#66a61e', edgecolor='k', marker='s', label="")
plt.scatter(np.median(df_bge_p_fattys.rassim), np.median(df_bge_p_fattys.Vmax/df_bge_p_fattys.KD), s=60, color='#7570b3', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_fattys.rassim), np.median(df_bge_n_fattys.Vmax/df_bge_n_fattys.KD), s=60, color='#7570b3', edgecolor='k', marker='v', label="")
plt.scatter(np.median(df_bge_u_fattys.rassim), np.median(df_bge_u_fattys.Vmax/df_bge_u_fattys.KD), s=60, color='#7570b3', edgecolor='k', marker='s', label="")
plt.scatter(np.median(df_bge_p_organics.rassim), np.median(df_bge_p_organics.Vmax/df_bge_p_organics.KD), s=60, color='#1b9e77', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_organics.rassim), np.median(df_bge_n_organics.Vmax/df_bge_n_organics.KD), s=60, color='#1b9e77', edgecolor='k', marker='v', label="")
plt.scatter(np.median(df_bge_u_organics.rassim), np.median(df_bge_u_organics.Vmax/df_bge_u_organics.KD), s=60, color='#1b9e77', edgecolor='k', marker='s', label="")
plt.scatter(np.median(df_bge_p_nucleos.rassim), np.median(df_bge_p_nucleos.Vmax/df_bge_p_nucleos.KD), s=60, color='#e7298a', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_nucleos.rassim), np.median(df_bge_n_nucleos.Vmax/df_bge_n_nucleos.KD), s=60, color='#e7298a', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_u_nucleos.rassim), np.median(df_bge_u_nucleos.Vmax/df_bge_u_nucleos.KD), s=60, color='#e7298a', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_p_auxins.rassim), np.median(df_bge_p_auxins.Vmax/df_bge_p_auxins.KD), s=60, color='#e6ab02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_auxins.rassim), np.median(df_bge_n_auxins.Vmax/df_bge_n_auxins.KD), s=60, color='#e6ab02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_u_auxins.rassim), np.median(df_bge_u_auxins.Vmax/df_bge_u_auxins.KD), s=60, color='#e6ab02', edgecolor='k', marker='^', label="")
ax = plt.gca()
ax.set_ylim([1e-2, 8e1])
#ax = sns.regplot(x="rassim", y="KD", data=df_bge_high, marker="", line_kws={"color":"#a6761d","alpha":1.0,"lw":1.5})
#ax = sns.regplot(x="rassim", y="rgrowth", data=df_bge_low, marker="", line_kws={"color":"#666666","alpha":1.0,"lw":1.5})
ax.set_xlim([5e-4, 5e-3])
ax.set(yscale='log')
ax.set(xscale='log')
plt.scatter(np.median(df_bge_p_sugars.ruptake), np.median(df_bge_p_sugars.Vmax/df_bge_p_sugars.KD), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_sugars.ruptake), np.median(df_bge_n_sugars.Vmax/df_bge_n_sugars.KD), s=60, color='#d95f02', edgecolor='k', marker='v', label="")
plt.scatter(np.median(df_bge_u_sugars.ruptake), np.median(df_bge_u_sugars.Vmax/df_bge_u_sugars.KD), s=60, color='#d95f02', edgecolor='k', marker='s', label="")
plt.scatter(np.median(df_bge_p_aminos.ruptake), np.median(df_bge_p_aminos.Vmax/df_bge_p_aminos.KD), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_aminos.ruptake), np.median(df_bge_n_aminos.Vmax/df_bge_n_aminos.KD), s=60, color='#66a61e', edgecolor='k', marker='v', label="")
plt.scatter(np.median(df_bge_u_aminos.ruptake), np.median(df_bge_u_aminos.Vmax/df_bge_u_aminos.KD), s=60, color='#66a61e', edgecolor='k', marker='s', label="")
plt.scatter(np.median(df_bge_p_fattys.ruptake), np.median(df_bge_p_fattys.Vmax/df_bge_p_fattys.KD), s=60, color='#7570b3', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_fattys.ruptake), np.median(df_bge_n_fattys.Vmax/df_bge_n_fattys.KD), s=60, color='#7570b3', edgecolor='k', marker='v', label="")
plt.scatter(np.median(df_bge_u_fattys.ruptake), np.median(df_bge_u_fattys.Vmax/df_bge_u_fattys.KD), s=60, color='#7570b3', edgecolor='k', marker='s', label="")
plt.scatter(np.median(df_bge_p_organics.ruptake), np.median(df_bge_p_organics.Vmax/df_bge_p_organics.KD), s=60, color='#1b9e77', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_organics.ruptake), np.median(df_bge_n_organics.Vmax/df_bge_n_organics.KD), s=60, color='#1b9e77', edgecolor='k', marker='v', label="")
plt.scatter(np.median(df_bge_u_organics.ruptake), np.median(df_bge_u_organics.Vmax/df_bge_u_organics.KD), s=60, color='#1b9e77', edgecolor='k', marker='s', label="")
plt.scatter(np.median(df_bge_p_nucleos.ruptake), np.median(df_bge_p_nucleos.Vmax/df_bge_p_nucleos.KD), s=60, color='#e7298a', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_nucleos.ruptake), np.median(df_bge_n_nucleos.Vmax/df_bge_n_nucleos.KD), s=60, color='#e7298a', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_u_nucleos.ruptake), np.median(df_bge_u_nucleos.Vmax/df_bge_u_nucleos.KD), s=60, color='#e7298a', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_p_auxins.ruptake), np.median(df_bge_p_auxins.Vmax/df_bge_p_auxins.KD), s=60, color='#e6ab02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_auxins.ruptake), np.median(df_bge_n_auxins.Vmax/df_bge_n_auxins.KD), s=60, color='#e6ab02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_u_auxins.ruptake), np.median(df_bge_u_auxins.Vmax/df_bge_u_auxins.KD), s=60, color='#e6ab02', edgecolor='k', marker='^', label="")
ax = plt.gca()
#ax.set_ylim([1e-2, 8e1])
#ax = sns.regplot(x="rassim", y="KD", data=df_bge_high, marker="", line_kws={"color":"#a6761d","alpha":1.0,"lw":1.5})
#ax = sns.regplot(x="rassim", y="rgrowth", data=df_bge_low, marker="", line_kws={"color":"#666666","alpha":1.0,"lw":1.5})
ax.set_xlim([5e-4, 5e-3])
ax.set(yscale='log')
ax.set(xscale='log')
plt.scatter(np.median(df_bge_p_sugars.ruptake), np.median(df_bge_p_sugars.BGE), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_sugars.ruptake), np.median(df_bge_n_sugars.BGE), s=60, color='#d95f02', edgecolor='k', marker='v', label="")
plt.scatter(np.median(df_bge_u_sugars.ruptake), np.median(df_bge_u_sugars.BGE), s=60, color='#d95f02', edgecolor='k', marker='s', label="")
plt.scatter(np.median(df_bge_p_aminos.ruptake), np.median(df_bge_p_aminos.BGE), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_aminos.ruptake), np.median(df_bge_n_aminos.BGE), s=60, color='#66a61e', edgecolor='k', marker='v', label="")
plt.scatter(np.median(df_bge_u_aminos.ruptake), np.median(df_bge_u_aminos.BGE), s=60, color='#66a61e', edgecolor='k', marker='s', label="")
plt.scatter(np.median(df_bge_p_fattys.ruptake), np.median(df_bge_p_fattys.BGE), s=60, color='#7570b3', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_fattys.ruptake), np.median(df_bge_n_fattys.BGE), s=60, color='#7570b3', edgecolor='k', marker='v', label="")
plt.scatter(np.median(df_bge_u_fattys.ruptake), np.median(df_bge_u_fattys.BGE), s=60, color='#7570b3', edgecolor='k', marker='s', label="")
plt.scatter(np.median(df_bge_p_organics.ruptake), np.median(df_bge_p_organics.BGE), s=60, color='#1b9e77', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_organics.ruptake), np.median(df_bge_n_organics.BGE), s=60, color='#1b9e77', edgecolor='k', marker='v', label="")
plt.scatter(np.median(df_bge_u_organics.ruptake), np.median(df_bge_u_organics.BGE), s=60, color='#1b9e77', edgecolor='k', marker='s', label="")
plt.scatter(np.median(df_bge_p_nucleos.ruptake), np.median(df_bge_p_nucleos.BGE), s=60, color='#e7298a', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_nucleos.ruptake), np.median(df_bge_n_nucleos.BGE), s=60, color='#e7298a', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_u_nucleos.ruptake), np.median(df_bge_u_nucleos.BGE), s=60, color='#e7298a', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_p_auxins.ruptake), np.median(df_bge_p_auxins.BGE), s=60, color='#e6ab02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_auxins.ruptake), np.median(df_bge_n_auxins.BGE), s=60, color='#e6ab02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_u_auxins.ruptake), np.median(df_bge_u_auxins.BGE), s=60, color='#e6ab02', edgecolor='k', marker='^', label="")
ax = plt.gca()
#ax.set_ylim([1e-2, 8e1])
#ax = sns.regplot(x="rassim", y="KD", data=df_bge_high, marker="", line_kws={"color":"#a6761d","alpha":1.0,"lw":1.5})
#ax = sns.regplot(x="rassim", y="rgrowth", data=df_bge_low, marker="", line_kws={"color":"#666666","alpha":1.0,"lw":1.5})
ax.set_xlim([5e-4, 5e-3])
ax.set(yscale='log')
ax.set(xscale='log')
plt.scatter(np.median(df_bge_p_sugars.rassim), np.median(df_bge_p_sugars.KD), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_sugars.rassim), np.median(df_bge_n_sugars.KD), s=60, color='#d95f02', edgecolor='k', marker='v', label="")
plt.scatter(np.median(df_bge_u_sugars.rassim), np.median(df_bge_u_sugars.KD), s=60, color='#d95f02', edgecolor='k', marker='s', label="")
plt.scatter(np.median(df_bge_p_aminos.rassim), np.median(df_bge_p_aminos.KD), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_aminos.rassim), np.median(df_bge_n_aminos.KD), s=60, color='#66a61e', edgecolor='k', marker='v', label="")
plt.scatter(np.median(df_bge_u_aminos.rassim), np.median(df_bge_u_aminos.KD), s=60, color='#66a61e', edgecolor='k', marker='s', label="")
plt.scatter(np.median(df_bge_p_fattys.rassim), np.median(df_bge_p_fattys.KD), s=60, color='#7570b3', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_fattys.rassim), np.median(df_bge_n_fattys.KD), s=60, color='#7570b3', edgecolor='k', marker='v', label="")
plt.scatter(np.median(df_bge_u_fattys.rassim), np.median(df_bge_u_fattys.KD), s=60, color='#7570b3', edgecolor='k', marker='s', label="")
plt.scatter(np.median(df_bge_p_organics.rassim), np.median(df_bge_p_organics.KD), s=60, color='#1b9e77', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_organics.rassim), np.median(df_bge_n_organics.KD), s=60, color='#1b9e77', edgecolor='k', marker='v', label="")
plt.scatter(np.median(df_bge_u_organics.rassim), np.median(df_bge_u_organics.KD), s=60, color='#1b9e77', edgecolor='k', marker='s', label="")
plt.scatter(np.median(df_bge_p_nucleos.rassim), np.median(df_bge_p_nucleos.KD), s=60, color='#e7298a', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_nucleos.rassim), np.median(df_bge_n_nucleos.KD), s=60, color='#e7298a', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_u_nucleos.rassim), np.median(df_bge_u_nucleos.KD), s=60, color='#e7298a', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_p_auxins.rassim), np.median(df_bge_p_auxins.KD), s=60, color='#e6ab02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_auxins.rassim), np.median(df_bge_n_auxins.KD), s=60, color='#e6ab02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_u_auxins.rassim), np.median(df_bge_u_auxins.KD), s=60, color='#e6ab02', edgecolor='k', marker='^', label="")
ax = plt.gca()
#ax.set_ylim([1e-2, 8e1])
#ax = sns.regplot(x="rassim", y="KD", data=df_bge_high, marker="", line_kws={"color":"#a6761d","alpha":1.0,"lw":1.5})
#ax = sns.regplot(x="rassim", y="rgrowth", data=df_bge_low, marker="", line_kws={"color":"#666666","alpha":1.0,"lw":1.5})
#ax.set_xlim([5e-4, 5e-3])
ax.set(yscale='log')
ax.set(xscale='log')
plt.scatter(np.median(df_bge_p_sugars.rdreserve), np.median(df_bge_p_sugars.BGE), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_sugars.rdreserve), np.median(df_bge_n_sugars.BGE), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_u_sugars.rdreserve), np.median(df_bge_u_sugars.BGE), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_p_aminos.rdreserve), np.median(df_bge_p_aminos.BGE), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_aminos.rdreserve), np.median(df_bge_n_aminos.BGE), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_u_aminos.rdreserve), np.median(df_bge_u_aminos.BGE), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_p_fattys.rdreserve), np.median(df_bge_p_fattys.rgrowth), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_n_fattys.rdreserve), np.median(df_bge_n_fattys.rgrowth), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_u_fattys.rdreserve), np.median(df_bge_u_fattys.rgrowth), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_p_organics.rdreserve), np.median(df_bge_p_organics.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_n_organics.rdreserve), np.median(df_bge_n_organics.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_u_organics.rdreserve), np.median(df_bge_u_organics.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_p_nucleos.rdreserve), np.median(df_bge_p_nucleos.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_n_nucleos.rdreserve), np.median(df_bge_n_nucleos.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_u_nucleos.rdreserve), np.median(df_bge_u_nucleos.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_p_auxins.rdreserve), np.median(df_bge_p_auxins.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_n_auxins.rdreserve), np.median(df_bge_n_auxins.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_u_auxins.rdreserve), np.median(df_bge_u_auxins.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
ax = plt.gca()
#ax.set_ylim([5e-3, 0.03])
#ax = sns.regplot(x="rassim", y="rgrowth", data=df_bge_high, marker="", line_kws={"color":"#a6761d","alpha":1.0,"lw":1.5})
#ax = sns.regplot(x="rdreserve", y="BGE", data=df_bge_high, marker="", line_kws={"color":"#666666","alpha":1.0,"lw":1.5}, order=1)
#ax.set_xlim([1e-7, 5e-3])
ax.set(yscale='log')
ax.set(xscale='log')
#plt.scatter(np.median(df_bge_p_sugars.rassim), np.median(df_bge_p_sugars.rgrowth), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_n_sugars.rassim), np.median(df_bge_n_sugars.rgrowth), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_u_sugars.rassim), np.median(df_bge_u_sugars.rgrowth), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_p_aminos.rassim), np.median(df_bge_p_aminos.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_n_aminos.rassim), np.median(df_bge_n_aminos.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
#plt.scatter(np.median(df_bge_u_aminos.rassim), np.median(df_bge_u_aminos.rgrowth), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_p_fattys.rdreserve), np.median(df_bge_p_fattys.BGE), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_fattys.rdreserve), np.median(df_bge_n_fattys.BGE), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_u_fattys.rdreserve), np.median(df_bge_u_fattys.BGE), s=60, color='#d95f02', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_p_organics.rdreserve), np.median(df_bge_p_organics.BGE), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_organics.rdreserve), np.median(df_bge_n_organics.BGE), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_u_organics.rdreserve), np.median(df_bge_u_organics.BGE), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_p_nucleos.rdreserve), np.median(df_bge_p_nucleos.BGE), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_nucleos.rdreserve), np.median(df_bge_n_nucleos.BGE), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_u_nucleos.rdreserve), np.median(df_bge_u_nucleos.BGE), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_p_auxins.rdreserve), np.median(df_bge_p_auxins.BGE), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_n_auxins.rdreserve), np.median(df_bge_n_auxins.BGE), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
plt.scatter(np.median(df_bge_u_auxins.rdreserve), np.median(df_bge_u_auxins.BGE), s=60, color='#66a61e', edgecolor='k', marker='^', label="")
ax = plt.gca()
#ax.set_ylim([5e-3, 0.03])
#ax = sns.regplot(x="rassim", y="rgrowth", data=df_bge_high, marker="", line_kws={"color":"#a6761d","alpha":1.0,"lw":1.5})
ax = sns.regplot(x="rdreserve", y="BGE", data=df_bge_low, marker="", line_kws={"color":"#666666","alpha":1.0,"lw":1.5}, order=1)
#ax.set_xlim([1e-7, 5e-3])
ax.set(yscale='log')
ax.set(xscale='log')
fig_height = 1.95 # inches
golden_mean = (np.sqrt(5)-1.0)/2.0 # Aesthetic ratio
fig_width = fig_height*golden_mean # height in inches
dpi = 300.0 # Convert inch to pt
# Margins are specified as a fraction of axes size.
# May need to adjust (especially left and bottom) to accomodate axes labels/tickmarks
leftmargin = 0.15
bottommargin = 0.2
rightmargin = 0.05
topmargin = 0.1
# These two parameters are used for adjusting spacing between subplots (when used)
wspace = 0.2
hspace = 0.2
fig_size = [fig_width,fig_height]
params = {'backend': 'svg',
'axes.labelsize': 8,
'axes.titlesize': 10,
'legend.fontsize': 8,
'xtick.labelsize': 8,
'ytick.labelsize': 8,
'figure.figsize': fig_size}
plt.rcParams.update(params)
plt.figure(1)
plt.clf()
plt.axes([leftmargin,
bottommargin,
1.0 - rightmargin-leftmargin,
1.0 - topmargin-bottommargin])
ax = plt.gca()
#ax = sns.stripplot(x="growthregime", y="Vmax", palette =["#a6761d", '#666666'], data=df_bge, dodge=True, size=3)
ax = sns.boxplot(x="growthregime", y="Vmax", data=df_bge, palette =["#a6761d", '#666666'], showfliers=False)
ax.set(yscale="log")
ax.set(ylabel=r'$\textnormal{Max. specific uptake rate}\, [\mathrm{h^{-1}}]$', xlabel='')
#ax.set_yticks([10,100])
#ax.set_yticklabels(["10","100"])
#ax.set_ylim([-3, 40])
#plt.title("Amino acids")
plt.savefig("/Users/glmarschmann/.julia/dev/DEBmicroTrait/plots/batch_Vmax.svg", format="svg")
ax = plt.gca()
#ax = sns.stripplot(x="growthregime", y="Vmax", palette =["#a6761d", '#666666'], data=df_bge, dodge=True, size=3)
ax = sns.boxplot(x="growthregime", y="KD", data=df_bge, palette =["#a6761d", '#666666'], showfliers=False)
ax.set(yscale="log")
ax.set(ylabel=r'$\textnormal{Half-saturation constant}\, [\mathrm{\mu M}]$', xlabel='')
#ax.set_yticks([10,100])
#ax.set_yticklabels(["10","100"])
#ax.set_ylim([-3, 40])
#plt.title("Amino acids")
plt.savefig("/Users/glmarschmann/.julia/dev/DEBmicroTrait/plots/batch_KD.svg", format="svg")
ax = plt.gca()
#ax = sns.stripplot(x="growthregime", y="Vmax", palette =["#a6761d", '#666666'], data=df_bge, dodge=True, size=3)
ax = sns.boxplot(x="growthregime", y="rmaint", data=df_bge, palette =["#a6761d", '#666666'], showfliers=False)
ax.set(yscale="log")
ax.set(ylabel=r'$\textnormal{Maintenance fraction}\, [\,\textnormal{-}\,]$', xlabel='')
#ax.set_yticks([10,100])
#ax.set_yticklabels(["10","100"])
#ax.set_ylim([-3, 40])
#plt.title("Amino acids")
plt.savefig("/Users/glmarschmann/.julia/dev/DEBmicroTrait/plots/batch_jM.svg", format="svg")
ax = plt.gca()
#ax = sns.stripplot(x="growthregime", y="Vmax", palette =["#a6761d", '#666666'], data=df_bge, dodge=True, size=3)
ax = sns.boxplot(x="growthregime", y="rdreserve", data=df_bge, palette =["#a6761d", '#666666'], showfliers=False)
ax.set(yscale="log")
ax.set(ylabel=r'$\textnormal{Reserve density}\, [\,\mathnormal{-}\,]$', xlabel='')
#ax.set_yticks([10,100])
#ax.set_yticklabels(["10","100"])
#ax.set_ylim([-3, 40])
#plt.title("Amino acids")
plt.savefig("/Users/glmarschmann/.julia/dev/DEBmicroTrait/plots/batch_mE.svg", format="svg")
ax = plt.gca()
#ax = sns.stripplot(x="growthregime", y="Vmax", palette =["#a6761d", '#666666'], data=df_bge, dodge=True, size=3)
ax = sns.boxplot(x="growthregime", y="rho", data=df_bge, palette =["#a6761d", '#666666'], showfliers=False)
ax.set(yscale="log")
ax.set(ylabel='Gene copy number normalized [-]', xlabel='')
#ax.set_yticks([10,100])
#ax.set_yticklabels(["10","100"])
#ax.set_ylim([-3, 40])
#plt.title("Amino acids")
#plt.savefig("/Users/glmarschmann/.julia/dev/DEBmicroTrait/plots/isolates_z_aminos.svg", format="svg")
from scipy import stats
df_bge_high = df_bge.loc[(df_bge.growthregime == "high")]
df_bge_low = df_bge.loc[(df_bge.growthregime == "low")]
stats.kruskal(df_bge_high["KD"], df_bge_low["KD"])
df_bge_low
```
| github_jupyter |
# Keras 利用預先訓練神經網路特徵萃取法訓練貓狗分類器
## 透過 Kaggle API 下載 Play Dataset
先從 Kaggle 下載資料集,這裡需要註冊 Kaggle 的帳號,並且取得 API Key,記得置換為自己的 API Token 才能下載資料。
```
#!pip install kaggle
api_token = {"username":"your_username","key":"your_api_key"}
import json
import zipfile
import os
if not os.path.exists("/root/.kaggle"):
os.makedirs("/root/.kaggle")
with open('/root/.kaggle/kaggle.json', 'w') as file:
json.dump(api_token, file)
!chmod 600 /root/.kaggle/kaggle.json
if not os.path.exists("/kaggle"):
os.makedirs("/kaggle")
os.chdir('/kaggle')
!kaggle datasets download -d chetankv/dogs-cats-images
!ls -alh '/kaggle'
!unzip 'dogs-cats-images.zip' > /dev/null
```
看看資料的基本結構,貓與狗訓練資料夾各有 4000 張,測試資料夾各有 1000 張影像
```
!echo "training_set cats: "
!echo `ls -alh '/kaggle/dataset/training_set/cats' | grep cat | wc -l`
!echo "training_set dogs: "
!echo `ls -alh '/kaggle/dataset/training_set/dogs' | grep dog | wc -l`
!echo "test_set cats: "
!echo `ls -alh '/kaggle/dataset/test_set/cats' | grep cat | wc -l`
!echo "test_set dogs: "
!echo `ls -alh '/kaggle/dataset/test_set/dogs' | grep dog | wc -l`
import os, shutil
# The path to the directory where the original
# dataset was uncompressed
original_dataset_dir = '/kaggle/dataset'
# The directory where we will
# store our smaller dataset
base_dir = '/play'
if not os.path.exists(base_dir):
os.mkdir(base_dir)
# Directories for our training,
# validation and test splits
train_dir = os.path.join(base_dir, 'train')
if not os.path.exists(train_dir):
os.mkdir(train_dir)
validation_dir = os.path.join(base_dir, 'validation')
if not os.path.exists(validation_dir):
os.mkdir(validation_dir)
test_dir = os.path.join(base_dir, 'test')
if not os.path.exists(test_dir):
os.mkdir(test_dir)
# Directory with our training cat pictures
train_cats_dir = os.path.join(train_dir, 'cats')
if not os.path.exists(train_cats_dir):
os.mkdir(train_cats_dir)
# Directory with our training dog pictures
train_dogs_dir = os.path.join(train_dir, 'dogs')
if not os.path.exists(train_dogs_dir):
os.mkdir(train_dogs_dir)
# Directory with our validation cat pictures
validation_cats_dir = os.path.join(validation_dir, 'cats')
if not os.path.exists(validation_cats_dir):
os.mkdir(validation_cats_dir)
# Directory with our validation dog pictures
validation_dogs_dir = os.path.join(validation_dir, 'dogs')
if not os.path.exists(validation_dogs_dir):
os.mkdir(validation_dogs_dir)
# Directory with our validation cat pictures
test_cats_dir = os.path.join(test_dir, 'cats')
if not os.path.exists(test_cats_dir):
os.mkdir(test_cats_dir)
# Directory with our validation dog pictures
test_dogs_dir = os.path.join(test_dir, 'dogs')
if not os.path.exists(test_dogs_dir):
os.mkdir(test_dogs_dir)
# Copy first 1000 cat images to train_cats_dir
fnames = ['cat.{}.jpg'.format(i) for i in range(1, 1001)]
for fname in fnames:
src = os.path.join(original_dataset_dir, 'training_set', 'cats', fname)
dst = os.path.join(train_cats_dir, fname)
shutil.copyfile(src, dst)
# Copy next 500 cat images to validation_cats_dir
fnames = ['cat.{}.jpg'.format(i) for i in range(4001, 4501)]
for fname in fnames:
src = os.path.join(original_dataset_dir, 'test_set', 'cats', fname)
dst = os.path.join(validation_cats_dir, fname)
shutil.copyfile(src, dst)
# Copy next 500 cat images to test_cats_dir
fnames = ['cat.{}.jpg'.format(i) for i in range(4501, 5001)]
for fname in fnames:
src = os.path.join(original_dataset_dir, 'test_set', 'cats', fname)
dst = os.path.join(test_cats_dir, fname)
shutil.copyfile(src, dst)
# Copy first 1000 dog images to train_dogs_dir
fnames = ['dog.{}.jpg'.format(i) for i in range(1, 1001)]
for fname in fnames:
src = os.path.join(original_dataset_dir, 'training_set', 'dogs', fname)
dst = os.path.join(train_dogs_dir, fname)
shutil.copyfile(src, dst)
# Copy next 500 dog images to validation_dogs_dir
fnames = ['dog.{}.jpg'.format(i) for i in range(4001, 4501)]
for fname in fnames:
src = os.path.join(original_dataset_dir, 'test_set', 'dogs', fname)
dst = os.path.join(validation_dogs_dir, fname)
shutil.copyfile(src, dst)
# Copy next 500 dog images to test_dogs_dir
fnames = ['dog.{}.jpg'.format(i) for i in range(4501, 5001)]
for fname in fnames:
src = os.path.join(original_dataset_dir, 'test_set', 'dogs', fname)
dst = os.path.join(test_dogs_dir, fname)
shutil.copyfile(src, dst)
print('total training cat images:', len(os.listdir(train_cats_dir)))
print('total training dog images:', len(os.listdir(train_dogs_dir)))
print('total validation cat images:', len(os.listdir(validation_cats_dir)))
print('total validation dog images:', len(os.listdir(validation_dogs_dir)))
print('total test cat images:', len(os.listdir(test_cats_dir)))
print('total test dog images:', len(os.listdir(test_dogs_dir)))
```
## 預先訓練神經網路的特徵萃取法
我們知道 CNN 卷積層的訓練需要很多數據與運算資源,在資料集不足的情況下,從頭訓練卷積層不是一個聰明的方法。何不直接採用大神訓練好的卷積層,加速 AI Time to Market。由於卷積網路可以學習影像特徵,越接近 Input 的 Layer 所能理解的特徵越「普適」而且抽象,像是紋理、顏色等等。越後面的 Layer 所學習到的特徵越接近物體的描述,像是耳朵、眼睛等等。
這裡我們採用 VGG16 Model,並提取 imagenet 包含 CNN 網路,這裡的網路已經經過大量的訓練,可以分辨圖片中的各種特徵。我們可以看到 CNN 在沒有連接層的情況下有 14,714,688 個參數,可見訓練過程實在很耗費運算。
```
# 載入 VGG 網路 Convolutional Base
from keras.applications import VGG16
conv_base = VGG16(weights='imagenet',
include_top=False, # 不包含 Full Connection
input_shape=(150, 150, 3))
conv_base.summary()
```
接下來透過已經訓練好的卷積網路來萃取特徵,這裡的程式將圖片影像直接送入卷積網路,透過 predict 將計算出的數值儲存起來,後續會用來訓練 Full Connection 分類網路。
```
import os
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
datagen = ImageDataGenerator(rescale=1./255)
batch_size = 20
def extract_features(directory, sample_count):
features = np.zeros(shape=(sample_count, 4, 4, 512))
labels = np.zeros(shape=(sample_count))
generator = datagen.flow_from_directory(
directory,
target_size=(150, 150),
batch_size=batch_size,
class_mode='binary')
i = 0
for inputs_batch, labels_batch in generator:
features_batch = conv_base.predict(inputs_batch)
features[i * batch_size : (i + 1) * batch_size] = features_batch
labels[i * batch_size : (i + 1) * batch_size] = labels_batch
i += 1
if i * batch_size >= sample_count:
# Note that since generators yield data indefinitely in a loop,
# we must `break` after every image has been seen once.
break
return features, labels
train_features, train_labels = extract_features(train_dir, 2000)
validation_features, validation_labels = extract_features(validation_dir, 1000)
test_features, test_labels = extract_features(test_dir, 1000)
train_features = np.reshape(train_features, (2000, 4 * 4 * 512))
validation_features = np.reshape(validation_features, (1000, 4 * 4 * 512))
test_features = np.reshape(test_features, (1000, 4 * 4 * 512))
```
# 使用特徵訓練網路
由於我們剛剛已經用 VGG16 CNN 抽取特徵,因此真正訓練分類網路的時候就不是輸入圖片,而是輸入這些計算好的特徵。
```
from keras import models
from keras import layers
from keras import optimizers
model = models.Sequential()
model.add(layers.Dense(256, activation='relu', input_dim=4 * 4 * 512))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(optimizer=optimizers.RMSprop(lr=2e-5),
loss='binary_crossentropy',
metrics=['acc'])
history = model.fit(train_features, train_labels,
epochs=30,
batch_size=20,
validation_data=(validation_features, validation_labels))
```
# 透過圖表分析訓練過程
```
import matplotlib.pyplot as plt
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(len(acc))
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
```
透過這樣的方法可以獲得將約 0.9 的正確性,效果比資料擴增法又好上一點。如果合併兩種方法 (資料擴充 + 特增萃取),成本會高一些,但是可以提升到 0.95 的正確性。
| github_jupyter |
# AWS Elastic Kubernetes Service (EKS) Deep MNIST
In this example we will deploy a tensorflow MNIST model in Amazon Web Services' Elastic Kubernetes Service (EKS).
This tutorial will break down in the following sections:
1) Train a tensorflow model to predict mnist locally
2) Containerise the tensorflow model with our docker utility
3) Send some data to the docker model to test it
4) Install and configure AWS tools to interact with AWS
5) Use the AWS tools to create and setup EKS cluster with Seldon
6) Push and run docker image through the AWS Container Registry
7) Test our Elastic Kubernetes deployment by sending some data
Let's get started! 🚀🔥
## Dependencies:
* Helm v3.0.0+
* A Kubernetes cluster running v1.13 or above (minkube / docker-for-windows work well if enough RAM)
* kubectl v1.14+
* EKS CLI v0.1.32
* AWS Cli v1.16.163
* Python 3.6+
* Python DEV requirements
## 1) Train a tensorflow model to predict mnist locally
We will load the mnist images, together with their labels, and then train a tensorflow model to predict the right labels
```
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot = True)
import tensorflow as tf
if __name__ == '__main__':
x = tf.placeholder(tf.float32, [None,784], name="x")
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x,W) + b, name="y")
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict = {x: mnist.test.images, y_:mnist.test.labels}))
saver = tf.train.Saver()
saver.save(sess, "model/deep_mnist_model")
```
## 2) Containerise the tensorflow model with our docker utility
First you need to make sure that you have added the .s2i/environment configuration file in this folder with the following content:
```
!cat .s2i/environment
```
Now we can build a docker image named "deep-mnist" with the tag 0.1
```
!s2i build . seldonio/seldon-core-s2i-python36:1.8.0-dev deep-mnist:0.1
```
## 3) Send some data to the docker model to test it
We first run the docker image we just created as a container called "mnist_predictor"
```
!docker run --name "mnist_predictor" -d --rm -p 5000:5000 deep-mnist:0.1
```
Send some random features that conform to the contract
```
import matplotlib.pyplot as plt
# This is the variable that was initialised at the beginning of the file
i = [0]
x = mnist.test.images[i]
y = mnist.test.labels[i]
plt.imshow(x.reshape((28, 28)), cmap='gray')
plt.show()
print("Expected label: ", np.sum(range(0,10) * y), ". One hot encoding: ", y)
from seldon_core.seldon_client import SeldonClient
import math
import numpy as np
# We now test the REST endpoint expecting the same result
endpoint = "0.0.0.0:5000"
batch = x
payload_type = "ndarray"
sc = SeldonClient(microservice_endpoint=endpoint)
# We use the microservice, instead of the "predict" function
client_prediction = sc.microservice(
data=batch,
method="predict",
payload_type=payload_type,
names=["tfidf"])
for proba, label in zip(client_prediction.response.data.ndarray.values[0].list_value.ListFields()[0][1], range(0,10)):
print(f"LABEL {label}:\t {proba.number_value*100:6.4f} %")
!docker rm mnist_predictor --force
```
## 4) Install and configure AWS tools to interact with AWS
First we install the awscli
```
!pip install awscli --upgrade --user
```
### Configure aws so it can talk to your server
(if you are getting issues, make sure you have the permmissions to create clusters)
```
%%bash
# You must make sure that the access key and secret are changed
aws configure << END_OF_INPUTS
YOUR_ACCESS_KEY
YOUR_ACCESS_SECRET
us-west-2
json
END_OF_INPUTS
```
### Install EKCTL
*IMPORTANT*: These instructions are for linux
Please follow the official installation of ekctl at: https://docs.aws.amazon.com/eks/latest/userguide/getting-started-eksctl.html
```
!curl --silent --location "https://github.com/weaveworks/eksctl/releases/download/latest_release/eksctl_$(uname -s)_amd64.tar.gz" | tar xz
!chmod 755 ./eksctl
!./eksctl version
```
## 5) Use the AWS tools to create and setup EKS cluster with Seldon
In this example we will create a cluster with 2 nodes, with a minimum of 1 and a max of 3. You can tweak this accordingly.
If you want to check the status of the deployment you can go to AWS CloudFormation or to the EKS dashboard.
It will take 10-15 minutes (so feel free to go grab a ☕).
*IMPORTANT*: If you get errors in this step it is most probably IAM role access requirements, which requires you to discuss with your administrator.
```
%%bash
./eksctl create cluster \
--name demo-eks-cluster \
--region us-west-2 \
--nodes 2
```
### Configure local kubectl
We want to now configure our local Kubectl so we can actually reach the cluster we've just created
```
!aws eks --region us-west-2 update-kubeconfig --name demo-eks-cluster
```
And we can check if the context has been added to kubectl config (contexts are basically the different k8s cluster connections)
You should be able to see the context as "...aws:eks:eu-west-1:27...".
If it's not activated you can activate that context with kubectlt config set-context <CONTEXT_NAME>
```
!kubectl config get-contexts
```
## Setup Seldon Core
Use the setup notebook to [Setup Cluster](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html#Setup-Cluster) with [Ambassador Ingress](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html#Ambassador) and [Install Seldon Core](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html#Install-Seldon-Core). Instructions [also online](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html).
## Push docker image
In order for the EKS seldon deployment to access the image we just built, we need to push it to the Elastic Container Registry (ECR).
If you have any issues please follow the official AWS documentation: https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html
### First we create a registry
You can run the following command, and then see the result at https://us-west-2.console.aws.amazon.com/ecr/repositories?#
```
!aws ecr create-repository --repository-name seldon-repository --region us-west-2
```
### Now prepare docker image
We need to first tag the docker image before we can push it
```
%%bash
export AWS_ACCOUNT_ID=""
export AWS_REGION="us-west-2"
if [ -z "$AWS_ACCOUNT_ID" ]; then
echo "ERROR: Please provide a value for the AWS variables"
exit 1
fi
docker tag deep-mnist:0.1 "$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/seldon-repository"
```
### We now login to aws through docker so we can access the repository
```
!`aws ecr get-login --no-include-email --region us-west-2`
```
### And push the image
Make sure you add your AWS Account ID
```
%%bash
export AWS_ACCOUNT_ID=""
export AWS_REGION="us-west-2"
if [ -z "$AWS_ACCOUNT_ID" ]; then
echo "ERROR: Please provide a value for the AWS variables"
exit 1
fi
docker push "$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/seldon-repository"
```
## Running the Model
We will now run the model.
Let's first have a look at the file we'll be using to trigger the model:
```
!cat deep_mnist.json
```
Now let's trigger seldon to run the model.
We basically have a yaml file, where we want to replace the value "REPLACE_FOR_IMAGE_AND_TAG" for the image you pushed
```
%%bash
export AWS_ACCOUNT_ID=""
export AWS_REGION="us-west-2"
if [ -z "$AWS_ACCOUNT_ID" ]; then
echo "ERROR: Please provide a value for the AWS variables"
exit 1
fi
sed 's|REPLACE_FOR_IMAGE_AND_TAG|'"$AWS_ACCOUNT_ID"'.dkr.ecr.'"$AWS_REGION"'.amazonaws.com/seldon-repository|g' deep_mnist.json | kubectl apply -f -
```
And let's check that it's been created.
You should see an image called "deep-mnist-single-model...".
We'll wait until STATUS changes from "ContainerCreating" to "Running"
```
!kubectl get pods
```
## Test the model
Now we can test the model, let's first find out what is the URL that we'll have to use:
```
!kubectl get svc ambassador -o jsonpath='{.status.loadBalancer.ingress[0].hostname}'
```
We'll use a random example from our dataset
```
import matplotlib.pyplot as plt
# This is the variable that was initialised at the beginning of the file
i = [0]
x = mnist.test.images[i]
y = mnist.test.labels[i]
plt.imshow(x.reshape((28, 28)), cmap='gray')
plt.show()
print("Expected label: ", np.sum(range(0,10) * y), ". One hot encoding: ", y)
```
We can now add the URL above to send our request:
```
from seldon_core.seldon_client import SeldonClient
import math
import numpy as np
host = "a68bbac487ca611e988060247f81f4c1-707754258.us-west-2.elb.amazonaws.com"
port = "80" # Make sure you use the port above
batch = x
payload_type = "ndarray"
sc = SeldonClient(
gateway="ambassador",
ambassador_endpoint=host + ":" + port,
namespace="default")
client_prediction = sc.predict(
data=batch,
deployment_name="deep-mnist",
names=["text"],
payload_type=payload_type)
print(client_prediction)
```
### Let's visualise the probability for each label
It seems that it correctly predicted the number 7
```
for proba, label in zip(client_prediction.response.data.ndarray.values[0].list_value.ListFields()[0][1], range(0,10)):
print(f"LABEL {label}:\t {proba.number_value*100:6.4f} %")
```
| github_jupyter |
```
import numpy as _np
import xarray as _xr
from atmPy.data_archives.arm import _tools
from atmPy.data_archives.arm import sites as armsites
from atmPy.aerosols.size_distribution import sizedistribution as _sd
from atmPy.general import timeseries as _ts
import atmPy
def open_path(path, window = None, average = None, verbose = True):
"""
Parameters
----------
path
start_time
end_time
average: tuple [None]
The purpose of this is to keep the memory usage low in case a lower reolution is required. E.g. (60, 's')
Returns
-------
"""
def read_aosaps(file, verbose = False):
ds = _xr.open_dataset(file, autoclose=True)
aods = pd.DataFrame()
wavelengths = pd.DataFrame()
for i in range(1,6):
aod = ds['aerosol_optical_depth_filter{}'.format(i)].to_pandas()
wl_measured = ds.attrs['filter{}_CWL_measured'.format(i)]
wl_nominal = ds.attrs['filter{}_CWL_nominal'.format(i)]
aods[wl_nominal] = aod
wls = {'wl_measured': float(wl_measured.split()[0]),
'wl_nominal': float(wl_nominal.split()[0])}
wavelengths = wavelengths.append(pd.DataFrame(wls, index = [i]), sort = True)
wavelengths.index.name = 'filter'
out = {}
out['aods'] = aods
out['wavelengths'] = wavelengths
if verbose:
pass
return out
# start_time, end_time = window
files = _tools.path2filelist(path=path, window = window, product='mfrsraod1mich', suffix='.cdf')
if verbose:
print('Opening {} files.'.format(len(files)))
print(_tools.path2info(files[0]))
data_dist = None
for file in files:
out = read_aosaps(file)
# return out
# break
ddt = _ts.TimeSeries(out['aods'])
if average:
ddt = ddt.average_time(average)
ddt = ddt.data
if isinstance(data_dist, type(None)):
data_dist = ddt
wavelengths = out['wavelengths']
else:
data_dist = data_dist.append(ddt, sort=True)
# make sure wavelength did not change
assert (_np.all(_np.equal(wavelengths, out['wavelengths'])))
# dist = _sd.SizeDist_TS(data_dist, binedges, 'dNdlogDp', ignore_data_gap_error=True)
dist = _ts.TimeSeries(data_dist)
dist.file_info = _tools.path2info(files[0])
dist.site = armsites.site_from_file_info(dist.file_info)
# dist.site_info = [site for site in atmPy.data_archives.arm.sites.sites_list if site['Site Code'] == dist.file_info['site'] and dist.file_info['facility'] == facility][0]
# dist.site = atmPy.general.measurement_site.Station(**site_info)
return dist
reload(atmPy.data_archives.arm._tools)
fname = '/Volumes/HTelg_4TB_Backup/arm_data/SGP/mfrsraod1michC1.s1/'
ds = open_path(fname, window=('20161115', '20161116'))
# atmPy.data_archives.arm._tools.path2filelist(fname, verbose=True, suffix='.cdf')
reload(atmPy.data_archives.arm.sites)
def site_from_file_info(file_info):
site_info = [site for site in atmPy.data_archives.arm.sites.sites_list if site['Site Code'].upper() == file_info['site'].upper() and site['facility'] == file_info['facility']][0]
site = atmPy.general.measurement_site.Station(**site_info)
return site
site_from_file_info(ds.file_info).lon
from atmPy.aerosols.physics import column_optical_properties
reload(column_optical_properties)
reload(atmPy.data_archives.arm.sites)
column_optical_properties.AOD_AOT()
sitec = 'SGP'
facility = 'C1'
[site for site in atmPy.data_archives.arm.sites.sites_list if site['Site Code'] == sitec and site['facility'] == facility]
site = atmPy.data_archives.arm.sites.sites_list[1]
site['facility'] == facility
```
# xarray
```
fname = '/Volumes/HTelg_4TB_Backup/arm_data/SGP/mfrsraod1michC1.s1/sgpmfrsraod1michC1.s1.20161115.000000.cdf'
ds = xr.open_dataset(fname)
df = pd.DataFrame()
df['bls'] = ds['aerosol_optical_depth_filter1'].to_pandas()
df
ds.filter1_CWL_nominal
ds.aerosol_optical_depth_filter1.to_pandas()
aods = pd.DataFrame()
wavelengths = pd.DataFrame()
for i in range(1,6):
aod = ds.variables['aerosol_optical_depth_filter{}'.format(i)]
wl_measured = ds.attrs['filter{}_CWL_measured'.format(i)]
wl_nominal = ds.attrs['filter{}_CWL_nominal'.format(i)]
aods[wl_nominal] = aod
wls = {'wl_measured': float(wl_measured.split()[0]),
'wl_nominal': float(wl_nominal.split()[0])}
wavelengths = wavelengths.append(pd.DataFrame(wls, index = [i]), sort = True)
wavelengths.index.name = 'filter'
wavelengths
float(wl_measured.split()[0])
wls = {'wl_measured': wl_measured,
'wl_nominal': wl_nominal}
wavelengths.append(pd.DataFrame(wls, index = [i]), sort = True)
aods.plot()
```
| github_jupyter |
##### Copyright 2018 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# Convolutional Variational Autoencoder
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/alpha/tutorials/generative/cvae">
<img src="https://www.tensorflow.org/images/tf_logo_32px.png" />
View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/r2/tutorials/generative/cvae.ipynb">
<img src="https://www.tensorflow.org/images/colab_logo_32px.png" />
Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/r2/tutorials/generative/cvae.ipynb">
<img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />
View source on GitHub</a>
</td>
</table>

This notebook demonstrates how to generate images of handwritten digits by training a Variational Autoencoder ([1](https://arxiv.org/abs/1312.6114), [2](https://arxiv.org/abs/1401.4082)).
```
# to generate gifs
!pip install imageio
```
## Import TensorFlow and other libraries
```
from __future__ import absolute_import, division, print_function
!pip install tensorflow-gpu==2.0.0-alpha0
import tensorflow as tf
import os
import time
import numpy as np
import glob
import matplotlib.pyplot as plt
import PIL
import imageio
from IPython import display
```
## Load the MNIST dataset
Each MNIST image is originally a vector of 784 integers, each of which is between 0-255 and represents the intensity of a pixel. We model each pixel with a Bernoulli distribution in our model, and we statically binarize the dataset.
```
(train_images, _), (test_images, _) = tf.keras.datasets.mnist.load_data()
train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')
test_images = test_images.reshape(test_images.shape[0], 28, 28, 1).astype('float32')
# Normalizing the images to the range of [0., 1.]
train_images /= 255.
test_images /= 255.
# Binarization
train_images[train_images >= .5] = 1.
train_images[train_images < .5] = 0.
test_images[test_images >= .5] = 1.
test_images[test_images < .5] = 0.
TRAIN_BUF = 60000
BATCH_SIZE = 100
TEST_BUF = 10000
```
## Use *tf.data* to create batches and shuffle the dataset
```
train_dataset = tf.data.Dataset.from_tensor_slices(train_images).shuffle(TRAIN_BUF).batch(BATCH_SIZE)
test_dataset = tf.data.Dataset.from_tensor_slices(test_images).shuffle(TEST_BUF).batch(BATCH_SIZE)
```
## Wire up the generative and inference network with *tf.keras.Sequential*
In our VAE example, we use two small ConvNets for the generative and inference network. Since these neural nets are small, we use `tf.keras.Sequential` to simplify our code. Let $x$ and $z$ denote the observation and latent variable respectively in the following descriptions.
### Generative Network
This defines the generative model which takes a latent encoding as input, and outputs the parameters for a conditional distribution of the observation, i.e. $p(x|z)$. Additionally, we use a unit Gaussian prior $p(z)$ for the latent variable.
### Inference Network
This defines an approximate posterior distribution $q(z|x)$, which takes as input an observation and outputs a set of parameters for the conditional distribution of the latent representation. In this example, we simply model this distribution as a diagonal Gaussian. In this case, the inference network outputs the mean and log-variance parameters of a factorized Gaussian (log-variance instead of the variance directly is for numerical stability).
### Reparameterization Trick
During optimization, we can sample from $q(z|x)$ by first sampling from a unit Gaussian, and then multiplying by the standard deviation and adding the mean. This ensures the gradients could pass through the sample to the inference network parameters.
### Network architecture
For the inference network, we use two convolutional layers followed by a fully-connected layer. In the generative network, we mirror this architecture by using a fully-connected layer followed by three convolution transpose layers (a.k.a. deconvolutional layers in some contexts). Note, it's common practice to avoid using batch normalization when training VAEs, since the additional stochasticity due to using mini-batches may aggravate instability on top of the stochasticity from sampling.
```
class CVAE(tf.keras.Model):
def __init__(self, latent_dim):
super(CVAE, self).__init__()
self.latent_dim = latent_dim
self.inference_net = tf.keras.Sequential(
[
tf.keras.layers.InputLayer(input_shape=(28, 28, 1)),
tf.keras.layers.Conv2D(
filters=32, kernel_size=3, strides=(2, 2), activation='relu'),
tf.keras.layers.Conv2D(
filters=64, kernel_size=3, strides=(2, 2), activation='relu'),
tf.keras.layers.Flatten(),
# No activation
tf.keras.layers.Dense(latent_dim + latent_dim),
]
)
self.generative_net = tf.keras.Sequential(
[
tf.keras.layers.InputLayer(input_shape=(latent_dim,)),
tf.keras.layers.Dense(units=7*7*32, activation=tf.nn.relu),
tf.keras.layers.Reshape(target_shape=(7, 7, 32)),
tf.keras.layers.Conv2DTranspose(
filters=64,
kernel_size=3,
strides=(2, 2),
padding="SAME",
activation='relu'),
tf.keras.layers.Conv2DTranspose(
filters=32,
kernel_size=3,
strides=(2, 2),
padding="SAME",
activation='relu'),
# No activation
tf.keras.layers.Conv2DTranspose(
filters=1, kernel_size=3, strides=(1, 1), padding="SAME"),
]
)
def sample(self, eps=None):
if eps is None:
eps = tf.random.normal(shape=(100, self.latent_dim))
return self.decode(eps, apply_sigmoid=True)
def encode(self, x):
mean, logvar = tf.split(self.inference_net(x), num_or_size_splits=2, axis=1)
return mean, logvar
def reparameterize(self, mean, logvar):
eps = tf.random.normal(shape=mean.shape)
return eps * tf.exp(logvar * .5) + mean
def decode(self, z, apply_sigmoid=False):
logits = self.generative_net(z)
if apply_sigmoid:
probs = tf.sigmoid(logits)
return probs
return logits
```
## Define the loss function and the optimizer
VAEs train by maximizing the evidence lower bound (ELBO) on the marginal log-likelihood:
$$\log p(x) \ge \text{ELBO} = \mathbb{E}_{q(z|x)}\left[\log \frac{p(x, z)}{q(z|x)}\right].$$
In practice, we optimize the single sample Monte Carlo estimate of this expectation:
$$\log p(x| z) + \log p(z) - \log q(z|x),$$
where $z$ is sampled from $q(z|x)$.
**Note**: we could also analytically compute the KL term, but here we incorporate all three terms in the Monte Carlo estimator for simplicity.
```
optimizer = tf.keras.optimizers.Adam(1e-4)
def log_normal_pdf(sample, mean, logvar, raxis=1):
log2pi = tf.math.log(2. * np.pi)
return tf.reduce_sum(
-.5 * ((sample - mean) ** 2. * tf.exp(-logvar) + logvar + log2pi),
axis=raxis)
def compute_loss(model, x):
mean, logvar = model.encode(x)
z = model.reparameterize(mean, logvar)
x_logit = model.decode(z)
cross_ent = tf.nn.sigmoid_cross_entropy_with_logits(logits=x_logit, labels=x)
logpx_z = -tf.reduce_sum(cross_ent, axis=[1, 2, 3])
logpz = log_normal_pdf(z, 0., 0.)
logqz_x = log_normal_pdf(z, mean, logvar)
return -tf.reduce_mean(logpx_z + logpz - logqz_x)
def compute_gradients(model, x):
with tf.GradientTape() as tape:
loss = compute_loss(model, x)
return tape.gradient(loss, model.trainable_variables), loss
def apply_gradients(optimizer, gradients, variables):
optimizer.apply_gradients(zip(gradients, variables))
```
## Training
* We start by iterating over the dataset
* During each iteration, we pass the image to the encoder to obtain a set of mean and log-variance parameters of the approximate posterior $q(z|x)$
* We then apply the *reparameterization trick* to sample from $q(z|x)$
* Finally, we pass the reparameterized samples to the decoder to obtain the logits of the generative distribution $p(x|z)$
* **Note:** Since we use the dataset loaded by keras with 60k datapoints in the training set and 10k datapoints in the test set, our resulting ELBO on the test set is slightly higher than reported results in the literature which uses dynamic binarization of Larochelle's MNIST.
## Generate Images
* After training, it is time to generate some images
* We start by sampling a set of latent vectors from the unit Gaussian prior distribution $p(z)$
* The generator will then convert the latent sample $z$ to logits of the observation, giving a distribution $p(x|z)$
* Here we plot the probabilities of Bernoulli distributions
```
epochs = 100
latent_dim = 50
num_examples_to_generate = 16
# keeping the random vector constant for generation (prediction) so
# it will be easier to see the improvement.
random_vector_for_generation = tf.random.normal(
shape=[num_examples_to_generate, latent_dim])
model = CVAE(latent_dim)
def generate_and_save_images(model, epoch, test_input):
predictions = model.sample(test_input)
fig = plt.figure(figsize=(4,4))
for i in range(predictions.shape[0]):
plt.subplot(4, 4, i+1)
plt.imshow(predictions[i, :, :, 0], cmap='gray')
plt.axis('off')
# tight_layout minimizes the overlap between 2 sub-plots
plt.savefig('image_at_epoch_{:04d}.png'.format(epoch))
plt.show()
generate_and_save_images(model, 0, random_vector_for_generation)
for epoch in range(1, epochs + 1):
start_time = time.time()
for train_x in train_dataset:
gradients, loss = compute_gradients(model, train_x)
apply_gradients(optimizer, gradients, model.trainable_variables)
end_time = time.time()
if epoch % 1 == 0:
loss = tf.keras.metrics.Mean()
for test_x in test_dataset:
loss(compute_loss(model, test_x))
elbo = -loss.result()
display.clear_output(wait=False)
print('Epoch: {}, Test set ELBO: {}, '
'time elapse for current epoch {}'.format(epoch,
elbo,
end_time - start_time))
generate_and_save_images(
model, epoch, random_vector_for_generation)
```
### Display an image using the epoch number
```
def display_image(epoch_no):
return PIL.Image.open('image_at_epoch_{:04d}.png'.format(epoch_no))
plt.imshow(display_image(epochs))
plt.axis('off')# Display images
```
### Generate a GIF of all the saved images.
```
with imageio.get_writer('cvae.gif', mode='I') as writer:
filenames = glob.glob('image*.png')
filenames = sorted(filenames)
last = -1
for i,filename in enumerate(filenames):
frame = 2*(i**0.5)
if round(frame) > round(last):
last = frame
else:
continue
image = imageio.imread(filename)
writer.append_data(image)
image = imageio.imread(filename)
writer.append_data(image)
# this is a hack to display the gif inside the notebook
os.system('cp cvae.gif cvae.gif.png')
display.Image(filename="cvae.gif.png")
```
To downlod the animation from Colab uncomment the code below:
```
#from google.colab import files
#files.download('cvae.gif')
```
| github_jupyter |
```
import numpy as np
import torch
from torch import nn
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt
%matplotlib inline
e = np.random.rand(10000)
a = np.linspace(-5, 5, 10000)
x = np.cos(a + 0.75) + 1.6*np.sin(1.5*a)
x += np.abs(x.min())
y = x + e
x /= np.abs(x).max()
y /= np.abs(y).max()
plt.plot(x)
plt.show()
plt.plot(y)
plt.show()
x, y = x[None,:], y[None,:]
print(x.shape, y.shape)
class LSTM2RNN(nn.Module):
def __init__(self, conv_in_channels, conv_out_features, ws, hs, rnn_hidden_size, rnn_output_size):
super(LSTM2RNN, self).__init__()
self.cin_channels = conv_in_channels
self.cout_features = conv_out_features
self.rnn_hid = rnn_hidden_size
self.rnn_out = rnn_output_size
# hard coding vars so I know what they are.
n_layers = 2 # number of layers of RNN
batch_size = 1
kernel2d = 3
# hidden initialization
self.hidden = self.init_hidden(n_layers, batch_size, rnn_hidden_size)
# net layer types
self.c1 = nn.Conv1d(conv_in_channels, conv_out_features+kernel2d-1, ws, stride=hs)
self.c2 = nn.Conv2d(1, conv_out_features, kernel2d)
self.lstm = nn.LSTM(conv_out_features*conv_out_features, rnn_hidden_size, n_layers,
batch_first=True, bidirectional=False)
self.dense = nn.Linear(rnn_hidden_size, rnn_output_size)
def forward(self, input):
#print("input size: {}".format(input.size()))
conv_out = self.c1(input)
#print("conv1d out: {}".format(conv_out.size()))
conv2_out = self.c2(conv_out.unsqueeze(0))
#print("conv2d out: {}".format(conv2_out.size()))
lstm_in = conv2_out.view(input.size(0), -1, self.cout_features * self.cout_features)
#print("lstm in: {}".format(lstm_in.size()))
self.hidden = self.repackage_hidden(self.hidden)
lstm_out, self.hidden = self.lstm(lstm_in, self.hidden)
#print("lstm out: {}".format(lstm_out.size()))
dense_in = lstm_out.view(lstm_in.size(1)*input.size(0) ,-1)
#print("dense in: {}".format(dense_in.size()))
out_space = self.dense(dense_in)
out = F.sigmoid(out_space)
out = out.view(input.size(0), -1)
return(out)
def init_hidden(self, nl, bat_dim, hid_dim):
# The axes: (num_layers, minibatch_size, hidden_dim)
# see docs
return (Variable(torch.zeros(nl, bat_dim, hid_dim)),
Variable(torch.zeros(nl, bat_dim, hid_dim)))
def repackage_hidden(self, h):
# will become state.detach_()
if type(h[0]) == Variable:
return((Variable(h[0].data),
Variable(h[1].data)))
else:
return(h)
class GRU2RNN(nn.Module):
def __init__(self, conv_in_channels, conv_out_features, ws, hs, rnn_hidden_size, rnn_output_size):
super(GRU2RNN, self).__init__()
self.cin_channels = conv_in_channels
self.cout_features = conv_out_features
self.rnn_hid = rnn_hidden_size
self.rnn_out = rnn_output_size
# pad input
self.pad = None
# hard coding vars so I know what they are.
n_layers = 2 # number of layers of RNN
batch_size = 1
kernel2d = 3
# hidden initialization
self.hidden = self.init_hidden(n_layers, batch_size, rnn_hidden_size)
# net layer types
self.c1 = nn.Conv1d(conv_in_channels, conv_out_features+kernel2d-1, ws, stride=hs)
self.c2 = nn.Conv2d(1, conv_out_features, kernel2d)
self.gru = nn.GRU(conv_out_features*conv_out_features, rnn_hidden_size, n_layers,
batch_first=True, bidirectional=False)
self.dense = nn.Linear(rnn_hidden_size, rnn_output_size)
def forward(self, input):
conv_out = F.relu(self.c1(input))
conv2_out = F.relu(self.c2(conv_out.unsqueeze(0)))
gru_in = conv2_out.view(input.size(0), -1, self.cout_features * self.cout_features)
gru_out, self.hidden = self.gru(gru_in, self.hidden)
dense_in = gru_out.view(gru_in.size(1)*input.size(0) ,-1)
out_space = self.dense(dense_in)
out = F.sigmoid(out_space)
out = out.view(input.size(0), -1)
return(out)
def init_hidden(self, nl, bat_dim, hid_dim):
# The axes: (num_layers, minibatch_size, hidden_dim)
# see docs
return (Variable(torch.zeros(nl, bat_dim, hid_dim)))
ws = 400
hs = 50
model = LSTM2RNN(1, 64, ws, hs, 1024, hs)
criterion = nn.BCELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=5e-2, momentum=0.9)
inputs = torch.from_numpy(y).float()
inputs.unsqueeze_(0)
front_pad = torch.zeros(inputs.size()[:-1] + tuple([hs*2]))
back_pad = torch.zeros(inputs.size()[:-1] + tuple([ws - hs]))
inputs_padded = torch.cat([front_pad, inputs, back_pad], dim=2)
targets = torch.from_numpy(x).float()
print(inputs.size(), targets.size())
print(model)
print(model(Variable(inputs_padded)))
print(inputs_padded.min(), inputs_padded.max())
n_layers = 2 # number of layers of RNN
batch_size = 1
kernel2d = 3
epochs = 51
#optimizer = torch.optim.SGD(model.parameters(), lr=5e-5, momentum=0.9)
#optimizer = torch.optim.RMSprop(model.parameters(), lr=5e-3, momentum=0.9)
optimizer = torch.optim.Adam(model.parameters(), lr=5e-3)
for epoch in range(epochs):
for mb, tgts in zip(inputs_padded, targets):
mb.unsqueeze_(0)
model.zero_grad()
optimizer.zero_grad()
model.init_hidden(n_layers, batch_size, hs)
mb = Variable(mb)
l = Variable(tgts.unsqueeze(0))
o = model(mb)
loss = criterion(o, l)
loss.backward()
#nn.utils.clip_grad_norm(model.parameters(), 0.75)
optimizer.step()
if epoch % 10 == 0:
print("Loss of {} @ epoch {}".format(loss.data[0], epoch+1))
plt.plot(x.ravel())
plt.plot(o.data.numpy().ravel())
plt.show()
plt.plot(y.ravel())
plt.show()
out = model(Variable(inputs_padded))
#out.squeeze_()
out = out.data.numpy()
print(out.shape)
plt.plot(out.ravel())
```
| github_jupyter |
### X lines of Python
# Gridding map data
This notebook goes with the [Agile Scientific blog post from 8 March 2019](https://agilescientific.com/blog/2019/3/8/x-lines-of-python-gridding-map-data).
I'm using a small dataset originally from [**Geoff Bohling**](http://people.ku.edu/~gbohling/) at the Kansas Geological Survey. I can no longer find the data online.
We will look at four ways to do this:
- Using SciPy with `scipy.interpolate.Rbf`
- Using SciPy with `scipy.griddata()`
- Using the Scikit-Learn machine learning library with `sklearn.gaussian_process`
- Using the [Verde](https://github.com/fatiando/verde) spatial gridding library with `verde.Spline` (thank you to Leo Uieda for contributing this!)
## Load and inspect the data
```
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
```
We'll load the data from the web; if you are offline but have the repo, the data file is also in `../data/ZoneA.dat`.
```
# Essential line number 1.
df = pd.read_csv('https://www.dropbox.com/s/6dyfc4fl5slhgry/ZoneA.dat?raw=1',
sep=' ',
header=9,
usecols=[0, 1, 2, 3],
names=['x', 'y', 'thick', 'por'],
dtype="float64"
)
df.head()
df.describe()
sns.distplot(df.por)
```
This looks a bit unpleasant, but we're just getting out min and max values for the x and y columns.
```
# Line 2.
extent = x_extent = x_min, x_max, y_min, y_max = [df.x.min()-1000, df.x.max()+1000,
df.y.min()-1000, df.y.max()+1000]
```
Later on, we'll see a nicer way to do this using the Verde library.
Now we can plot the data:
```
fig, ax = plt.subplots(figsize=(10,6))
ax.scatter(df.x, df.y, c=df.por)
ax.set_aspect(1)
ax.set_xlim(*extent[:2])
ax.set_ylim(*extent[2:])
ax.set_xlabel('Easting [m]')
ax.set_ylabel('Northing [m]')
ax.set_title('Porosity %')
ax.grid(c='k', alpha=0.2)
plt.show()
```
## Make a regular grid
We must make a grid, which represents the points we'd like to predict.
```
# Line 3.
grid_x, grid_y = np.mgrid[x_min:x_max:500, y_min:y_max:500]
# Use *shape* argument to specify the *number* (not size) of bins:
# grid_x, grid_y = np.mgrid[x_min:x_max:100j, y_min:y_max:100j]
plt.figure(figsize=(10,6))
plt.scatter(grid_x, grid_y, s=10)
```
That was easy!
## Interpolation with radial basis function
Now we make an interpolator and use it to predict into the grid 'cells'.
```
from scipy.interpolate import Rbf
# Make an n-dimensional interpolator. This is essential line number 4.
rbfi = Rbf(df.x, df.y, df.por)
# Predict on the regular grid. Line 5.
di = rbfi(grid_x, grid_y)
```
Let's plot the result. First, we'll need the min and max of the combined sparse and gridded data, so we can plot them with the same colourmap ranges:
```
mi = np.min(np.hstack([di.ravel(), df.por.values]))
ma = np.max(np.hstack([di.ravel(), df.por.values]))
```
Notice the transpose and the `origin='lower'`, to keep everything matched up with the original dataset.
```
plt.figure(figsize=(15,15))
c1 = plt.imshow(di.T, origin="lower", extent=extent, vmin=mi, vmax=ma)
c2 = plt.scatter(df.x, df.y, s=60, c=df.por, edgecolor='#ffffff66', vmin=mi, vmax=ma)
plt.colorbar(c1, shrink=0.67)
plt.show()
```
The circles (the data) are the same colour as the grid (the model), so we can see that the error on this prediction is almost zero. In fact, the default parameters force the model to pass through all the data points (interpolation, as opposed to estimation or approximation).
The `Rbf()` interpolator has [a few options](https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.Rbf.html). The most important one is probably `smooth`, which is the thing to increase if you end up with a singular matrix (because it can't converge on a solution). Anything above 0 relaxes the constraint that the surface must pass through every point. If you get an error, you probably need to change the smoothing.
You can also change the `function` (default is `multiquadric`, which also has an `epsilon` parameter to vary the range of influence of each point).
```
rbfi = Rbf(df.x, df.y, df.por, smooth=0.2)
di = rbfi(grid_x, grid_y)
plt.imshow(di.T, origin="lower", extent=extent)
plt.scatter(df.x, df.y, s=2, c='w')
plt.show()
```
We can also make a histogram and kernel density estimation of the errors, by making predictions at the original input locations:
```
por_hat = rbfi(df.x, df.y)
sns.distplot(por_hat - df.por)
```
With the smoothing set to 0.2, we end up with a smoother surface, but pay for it with larger errors.
## Interpolation with `scipy.griddata()`
The `Rbf()` interpolator is the one to know about, because it has lots of useful parameters. It's probably the only one you need to know. But there is also `scipy.griddata()`. For example see [this SciPy recipe](https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.griddata.html).
The interface is slightly different — we have to pass a single array of the coordinates (the (x, y) locations of the points we know). We also pass the values to interpolate, and the grids.
The function will not accept Pandas `Series` objects, so we'll use the `Series.values` attribute to get at the NumPy array representation.
First, let's make the 2D array of coordinates:
```
points = df[['x', 'y']].values
```
The grdding step is easy. We'll try three different algorithms:
```
from scipy.interpolate import griddata
grid_z0 = griddata(points, df.por.values, (grid_x, grid_y), method='nearest')
grid_z1 = griddata(points, df.por.values, (grid_x, grid_y), method='linear')
grid_z2 = griddata(points, df.por.values, (grid_x, grid_y), method='cubic')
```
Inspect the results.
```
fig, axs = plt.subplots(ncols=3, figsize=(15, 5))
ax = axs[0]
ax.imshow(grid_z0, origin='lower', extent=extent)
ax.scatter(df.x, df.y, s=2, c='w')
ax.set_title('Nearest')
ax = axs[1]
ax.imshow(grid_z1, origin='lower', extent=extent)
ax.scatter(df.x, df.y, s=2, c='w')
ax.set_title('Linear')
ax = axs[2]
ax.imshow(grid_z2, origin='lower', extent=extent)
ax.scatter(df.x, df.y, s=2, c='w')
ax.set_title('Cubic')
plt.show()
```
I don't particularly like any of these results.
## Using `verde.Spline`
One of the options in scipy's `Rbf` interpolator is the "thin-plate" kernel. This is what the `verde.Spline` interpolator is based on but with a few modifications, like damping regularization to smooth the solution. It's similar to the `RBF` and `GaussianProcessRegressor` approach but Verde provides a more conenient API for gridding tasks.
For example, we now have a nicer way to define `extent`, using `vd.pad_region()`:
```
import verde as vd
extent = x_min, x_max, y_min, y_max = vd.pad_region(vd.get_region((df.x, df.y)), pad=1000)
spline = vd.Spline(mindist=2000, damping=1e-4)
spline.fit((df.x, df.y), df.por)
```
To make a grid, use the `.grid` method of the spline:
```
grid = spline.grid(region=extent, spacing=500)
grid
```
This returns an [`xarray.Dataset`](http://xarray.pydata.org/en/stable/generated/xarray.Dataset.html#xarray.Dataset) which can be easily plotted, saved to disk as netCDF, or used for computations. The coordinates for the grid are automatically generated and populated based on the desired region and spacing. The spacing is adjusted to fit the desired region exactly. Optionally, you can set `adjust="region"` to adjust the size of the region so that the spacing is exact.
And plot the predicted grid with the input data using the same colourmap:
```
# Compute min and max of all the data:
mi = np.min(np.hstack([grid.scalars.values.ravel(), df.por.values]))
ma = np.max(np.hstack([grid.scalars.values.ravel(), df.por.values]))
# Plot it all.
plt.figure(figsize=(15,15))
im = plt.imshow(grid.scalars, origin='lower', extent=extent, vmin=mi, vmax=ma)
pts = plt.scatter(df.x, df.y, c=df.por, s=80, edgecolor='#ffffff66', vmin=mi, vmax=ma)
plt.colorbar(im, shrink=0.67)
plt.show()
```
As before, we can compute the error by making a prediction on the original (x, y) values and comparing to the actual measured porosities at those locations:
```
por_hat = spline.predict((df.x, df.y))
sns.distplot(por_hat - df.por)
```
----
© 2019 Agile Scientific, licensed CC-BY
| github_jupyter |
## Классы
Классы в питоне - это способ работать с объектом у которого необходимо иметь состояние. Как правило, вам необходимо с этим состоянием как-то работать: модифицировать или узнавать что-то. Для этого в классах используются методы: особые функции, которые имеют доступ к содержимому вашего объекта.
Рассмотрим пример. Предположим у вас есть сеть отелей. И вам было бы очень удобно работать с отелем, кок отдельным объектом. Что является состоянием отеля? Для простоты предположим, что только информация о заполненных/свободных номерах. Тогда мы можем описать отель следующим образом:
```python
class Hotel:
def __init__(self, num_of_rooms):
self.rooms = [0 for _ in range(num_of_rooms)]
```
При создании объекта `Hotel` ему нужно будет передать количество комнат в этом отеле. Информацию о свободных и занятых комнатах мы будем хранить в массиве длины `num_of_rooms`, где 0 - комната свободна, 1 - комната занята.
Какие функции помощники нам нужны? Мы бы наверное хотели уметь занимать комнаты (когда кто-то въезжает) и освобждать. Для этого напишем два метода `occupy` и `realize`.
```python
class Hotel:
def __init__(self, num_of_rooms):
self.rooms = [0 for _ in range(num_of_rooms)]
def occupy(self, room_id):
self.rooms[room_id] = 1
def free(self, room_id):
self.rooms[room_id] = 0
```
Отлично, теперь мы можем выполнять элементарные действия с нашим классом. Попробуйте создать класс и занять несколько комнат.
```
class Hotel:
def __init__(self, num_of_rooms):
self.rooms = [0 for _ in range(num_of_rooms)]
def occupy(self, room_id):
self.rooms[room_id] = 1
def free(self, room_id):
self.rooms[room_id] = 0
# TODO
```
Зачем нам нужны классы? Ведь можно было написать функцию
```python
def occupy(rooms, room_id):
rooms[room_id] = 1
return rooms
```
Плюс работы с объектами в том, что тем, кто пользуются нашим классом (включая нас самих) не нужно думать о том, как мы реализовали хранение комнат. Если в какой-то момент мы захотим изменить `list` на `dict` (например мы заметили, что так быстрее), никто ничего не заметит. Код пользователей не изменится. Тоже самое касается функциональности - если мы вдруг решили, что нам нужно добавить бронирование на дату, мы можем это сделать и те кто уже пользуются нашим классом - ничего не заметят. У них ничего не сломается. А это очень важно.
# Задание 1
Допишите несколько методов в класс `Hotel`.
Напишите метод `occupancy_rate`. Метод должен возвращать долю комнат, которые заняты.
Напишите метод `close`. Метод должен освобождать все комнаты. Если `occupancy_rate` написан корректно, то после `close` `occupancy_rate` должен возвращать 0.
```
# TODO
```
# Задание 2
Мы хотим, чтобы пользователь нашего класса не натворил глупостей. Например, не пытался занять уже занятую комнату. Допишите методы `occupy` и `free`. Проверьте внутри них, что состояние комнаты действительно меняется. Иначе вы должны бросить исключение с понятным текстом.
Напоминаю, что исключение - это такая конструкция, когда программа завершает работу из некоторой точки. Как правило в случае появления ошибки.
Синтаксис
```python
raise RuntimeError("Bad news")
```
```
# TODO
```
# Задание 3
Добавьте возможность бронировать номера. Метод назовем `book(self, date, room_id)`. На вход приходит дата и номер комнаты и она становится занята. Если бронь не удалась, бросьте исключение. Перед бронью убедитесь, что комната свободна. Для этого напишите метод `is_booked(self, date, room_id)`.
```
# TODO
```
# Задание 4
Мы, как отель, хотим знать свою выручку на какой-то день. Напишите метод `income(self, date)`. Он должен возвращать количество денег, которое заработает отель в этот день. Представим, что стоймость всех комнат одинакова и равна 200$.
```
# TODO
```
| github_jupyter |
# Tensorflow Linear Regression
TensorFlow was created by Google Brain and is used for doing machine learning in neural networks. On the other hand, to use deep learning approaches, you will need large data to train. If not enough data, the model will be overfitting.
```
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
# fix_yahoo_finance is used to fetch data
import fix_yahoo_finance as yf
yf.pdr_override()
# input
symbol = 'AMD'
start = '2007-01-01'
end = '2018-11-01'
# Read data
dataset = yf.download(symbol,start,end)
# View Columns
dataset.head()
dataset['Increase_Decrease'] = np.where(dataset['Volume'].shift(-1) > dataset['Volume'],1,0)
dataset['Buy_Sell_on_Open'] = np.where(dataset['Open'].shift(-1) > dataset['Open'],1,0)
dataset['Buy_Sell'] = np.where(dataset['Adj Close'].shift(-1) > dataset['Adj Close'],1,0)
dataset['Returns'] = dataset['Adj Close'].pct_change()
dataset = dataset.dropna()
dataset.head()
dataset.shape
import tensorflow as tf
import numpy as np
print(tf.__version__)
X = dataset[['Open', 'High', 'Low', 'Volume', 'Returns']]
Y = dataset['Adj Close']
batch_size = 32
learning_rate = 0.003
n_epoches = 6000
# splitting the data into train and test dataframes
train_d = X.sample(frac=0.7, random_state=101)
test_d = X.drop(train_d.index)
# converting train and test dataframes to matices to creat datasets
train_d = train_d.astype('float32').as_matrix()
test_d = test_d.astype('float32').as_matrix()
training_set = tf.data.Dataset.from_tensor_slices((train_d[:,0], train_d[:,1]))
testing_set = tf.data.Dataset.from_tensor_slices((test_d[:,0], test_d[:,1]))
# combining consecutive elements of the train dataset into batches
training_set = training_set.batch(batch_size)
# creating an (uninitialized) iterator for enumerating the elements of the dataset with the given structure
iterator = tf.data.Iterator.from_structure(training_set.output_types, training_set.output_shapes)
train_init = iterator.make_initializer(training_set)
# get_next() returns a nested structure of `tf.Tensor`s containing the next element
X, Y = iterator.get_next()
def R_squared(y, y_pred):
'''
R_squared computes the coefficient of determination.
It is a measure of how well the observed outcomes are replicated by the model.
'''
residual = tf.reduce_sum(tf.square(tf.subtract(y, y_pred)))
total = tf.reduce_sum(tf.square(tf.subtract(y, tf.reduce_mean(y))))
r2 = tf.subtract(1.0, tf.div(residual, total))
return r2
# Model
w = tf.Variable(tf.truncated_normal((1,), mean=0, stddev=0.1, seed=123), name='Weight')
b = tf.Variable(tf.constant(0.1), name='Bias')
y_pred = tf.multiply(w, X) + b
# Cost function
loss = tf.reduce_mean(tf.square(Y - y_pred), name='Loss')
# training
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss)
import time
start = time.time()
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for epoch in range(n_epoches):
sess.run(train_init)
try:
# Loop until all elements have been consumed
while True:
sess.run(optimizer)
except tf.errors.OutOfRangeError:
pass
end = time.time()
w_curr, b_curr = sess.run([w,b])
y_pred_train = w_curr * train_d[:,0] + b_curr
y_pred_test = w_curr * test_d[:,0] + b_curr
r2_train = R_squared(train_d[:,1], y_pred_train)
r2_test = R_squared(test_d[:,1], y_pred_test)
print('R^2_train:', sess.run(r2_train))
print('R^2_test:', sess.run(r2_test))
print('elapsed time:', end - start)
sess.close()
plt.scatter(test_d[:,0], test_d[:,1], label='Real Data')
plt.plot(test_d[:,0], y_pred_test, 'r', label='Predicted Data')
plt.xlabel('Independent Variable')
plt.ylabel('Dependent Variable')
plt.legend()
```
| github_jupyter |
# STL and MTL GP Regression Walkthrough
```
import sys
sys.path.append('../')
#from design import ModelTraining
from datasets import SyntheticData as SD
import numpy as np
from sklearn.model_selection import train_test_split
import pandas as pd
from time import time
import matplotlib.pyplot as plt
import methods.mtl.MTL_GP as MtlGP
import os
import numpy as np
import matplotlib
import seaborn as sns
```
## Setting Up Datasets
The very first step to running through these Gaussian Process Tutorials is retrieving some data to train our models on. Here we are using the CTRP, GDSC and CCLE datasets mentioned in the introduction.
```
import importlib
importlib.reload(MtlGP)
dataset = SD.SyntheticDataCreator(num_tasks=3,cellsPerTask=400, drugsPerTask=10, function="cosine",
normalize=False, noise=1, graph=False, test_split=0.3)
dataset.prepare_data()
```
## Single Task Gaussian Process Example
below is an exaple of training and testing a basic Sparse Gaussian Process from gpytorch with our data.
```
import methods.regressor.SparseGP as SGP
importlib.reload(SGP)
y_pred = {}
sparsegp = SGP.SparseGPRegression(num_iters=50, length_scale=50, noise_covar=1.5, n_inducing_points=250)
for k in dataset.datasets:
sparsegp.fit(dataset.data['train']['x'][k],
y=dataset.data['train']['y'][k],
cat_point=dataset.cat_point)
y_pred[k] = sparsegp.predict(dataset.data['test']['x'][k])
for name in y_pred.keys():
rmse = np.sqrt(np.sum(((y_pred[name] - dataset.data['test']['y'][name]) ** 2) / len(y_pred[name])))
print(rmse, name)
```
Next, we have a more complex method, composite kernel Gaussian Process Regression
```
import methods.regressor.SparseGPCompositeKernel as sgpc
importlib.reload(sgpc)
y_pred = {}
sparsegpcomp = sgpc.SparseGPCompositeKernelRegression(num_iters=10, length_scale_cell=100, length_scale_drug=100, noise_covar=1.5, n_inducing_points=500, learning_rate=.1)
for k in dataset.datasets:
sparsegpcomp.fit(dataset.data['train']['x'][k],
y=dataset.data['train']['y'][k],
cat_point=dataset.cat_point)
y_pred[k] = sparsegpcomp.predict(dataset.data['test']['x'][k])
for name in y_pred.keys():
rmse = np.sqrt(np.sum(((y_pred[name] - dataset.data['test']['y'][name]) ** 2) / len(y_pred[name])))
print(rmse, name)
```
## Multitask Background
Given a set of observations $y_0$ we wish to learn parameters $\theta_x$ and $k^x$ of the matrix $K_f$. $k^x$ is a covariance function over the inputs and $\theta_x$ are the parameters for that specific covariance function
## Hadamard Product MTL
A clear limitation of the last method is that although it is technically multitask, it will fail to capture most task relationships. In order to do this I'll introduce another spin on vanilla GP Regression.
Now we just have one model parameterized as:
\begin{align*}
y_{i} &= f(x_i) + \varepsilon_{i} \\
f &\sim \mathcal{GP}(C_t,K_{\theta}) \\
\theta &\sim p(\theta) \\
\varepsilon_{i} &\stackrel{iid}{\sim} \mathcal{N}(0, \sigma^2) \
\end{align*}
With one key difference. Our kernel is now defined as: $K([x,i],[x',j]) = k_{inputs}(x,x') * k_{tasks}(i,j)$ where $ k_{tasks} $ is an "index kernel", essentially a lookup table for inter-task covariance. This lookup table is defined $\forall \ i,j \in$ the set of tasks $T$. Here's a basic example with 4 datapoints and 2 tasks.
```
importlib.reload(MtlGP)
hadamardMTL = MtlGP.HadamardMTL(num_iters=300, length_scale=20, noise_covar=.24, n_inducing_points=500, \
composite=False, learning_rate=.07, validate=False,bias=False,stabilize=False)
hadamardMTL.fit(dataset.data['train']['x'],
y=dataset.data['train']['y'],
catpt=dataset.cat_point)
y_pred = hadamardMTL.predict(dataset.data['test']['x'])
for name in y_pred.keys():
rmse = np.sqrt(np.sum(((y_pred[name].numpy() - dataset.data['test']['y'][name]) ** 2) / len(y_pred[name])))
print(rmse, name)
```
## Example Visualizing Covariance Using Getter
```
full_covar = hadamardMTL.model.getCovar().numpy()
plt.imshow(full_covar)
plt.imshow(hadamardMTL.model.getCovar().numpy())
from mpl_toolkits.axes_grid1 import make_axes_locatable
fig, ax = plt.subplots()
task_covar = hadamardMTL.model.getTaskCovar().numpy() # cast from torch to numpy
im = ax.imshow(task_covar, cmap="Reds")
ax.set_xticks([200,800,1300])
ax.set_xticklabels(dataset.datasets)
ax.set_yticks([200,800,1300])
ax.set_yticklabels(dataset.datasets)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="10%", pad=0.5)
cbar = plt.colorbar(im, cax = cax)
```
## Full Multitask GP with Multitask Kernel
```
importlib.reload(MtlGP)
gpymtl = MtlGP.GPyFullMTL(num_iters=300, length_scale=15, noise_covar=1, n_inducing_points=200, num_tasks=3, learning_rate=.05)
gpymtl.fit(dataset.data['train']['x'],
y=dataset.data['train']['y'],
cat_point=dataset.cat_point)
y_pred = gpymtl.predict(dataset.data['test']['x'])
i = 0
for name in y_pred.keys():
rmse = np.sqrt(np.sum(((y_pred[name] - dataset.data['test']['y'][name]) ** 2) / len(y_pred[name])))
i += 1
print(rmse, name)
```
## Example Find Initial Conditions
In order to understand what parameters to start at, we can test different configurations of initial conditions
```
import importlib
importlib.reload(MtlGP)
multiBias = MtlGP.HadamardMTL(num_iters=10, noise_covar=1.5, n_inducing_points=500, multitask_kernel=False) #testing #0)
multiBias._find_initial_conditions(dataset.data['train']['x'], dataset.data['train']['y'], \
n_restarts=800,n_iters=50, n_inducing_points=500)
```
(tensor(1.2674, grad_fn=<NegBackward>),
{'likelihood.noise_covar.noise': 0.7006388902664185,
'covar_module.lengthscale': 10.444199562072754})
| github_jupyter |
# VCS Text Objects
[Table Of Content](#toc)<a href="TOC"></a>
* [Introduction](#intro)
* [Positioning Text](#postiion)
* [Text Table Section](#Tt)
* [Fonts](#fonts)
* [Changing the fonts](#changing)
* [Adding Fonts](#adding)
* [Color](#color)
* [Projection](#projection)
* [Ordering Object On The Plot](#priority)
* [Deprecated Attributes](#deprecated)
* [Text Orientation Section](#To)
* [Size](#size)
* [Angle](#angle)
* [Alignement](#align)
* [Horizontal](#horiz)
* [Vertical](#vert)
* [Mathematical Expressions and Symbols](#math)
* [Example: Bringing it all together](#example)
## Introduction<a id="intro"></a>
VCS let you plot text objects on a plot.
```
# Styling for notebook
from __future__ import print_function
from IPython.core.display import HTML
HTML("""
<style>
.output_png {
display: table-cell;
text-align: center;
vertical-align: middle;
}
</style>
""")
import vcs
canvas=vcs.init(geometry=(800,600),bg=True)
txt = vcs.createtext()
txt.list()
```
As you can see VCS text pbjects are composed of two part the [texttable](#Tt) and the [textorientation](#To)
Text Table controls the font, color, actual text (string), and location options
Text Orientation control the text font, size and alignements
## Controling Placements of Text Objects<a id="position"></a>
Please refer to the [VCS Principles](VCS_Principles.ipynb#secondary) for details on `viewport` and `worldcoordinates`.
Essentially the viewport describe the area on the canvas where to draw, and the world coordinates are used within this area. Both are initialized at `[0,1,0,1]`
```
txt.string = 'Hello VCS User' # Or list of strings
txt.x = .5 # Or list of coordinates
txt.y = .5
canvas.plot(txt)
```
## Text Table<a id="Tt"></a>
### Fonts<a id="fonts"></a>
#### Changing the font<a id="changing"></a>
You can control the fonts via the `font` attribute
Available fonts a are available via the `vcs.getlistelements("font")` option
Default fonts are:
```
print(vcs.listelements("font"))
```
You can also access font by their number, you can get a font name based on its number or vice-versa get a font number based on its name
```
print("The 'Times' font number is:",vcs.getfontnumber("Times"))
print("The name of number 5 is:", vcs.getfont(5))
```
### Default font<a id="deffont"></a>
If you wish to change vcs default font (will affect every object using font 1) you can use `setdefaultfont`
```
canvas.clear()
t = canvas.createtext()
t.string = "Default as default font"
t.x = .3
t.halign = "center"
t.y = .5
canvas.plot(t)
vcs.setdefaultfont("DejaVuSans-Bold")
t = canvas.createtext()
t.string = "DejaVuSans-Bold as default font"
t.x = .7
t.halign = "center"
t.y = .5
canvas.plot(t)
```
Example:
```
# rest to default font: AvantGarde
vcs.setdefaultfont("AvantGarde")
fonts = vcs.listelements("font")
N = len(fonts)
grid = 5. # 5x5 grid
delta = 1./6.
canvas.clear()
for i, font in enumerate(fonts):
print("I,f:",i,font)
txt.font = font
txt.string = font
yindx = i % grid
xindx = int(i/grid)
txt.x = delta + xindx*delta
txt.y = delta + yindx*delta
dsp = canvas.plot(txt)
# Resets
txt.x = [.5]
txt.y = [.5]
txt.string = "A VCS Text Object"
dsp
```
#### Adding fonts<a id="adding"></a>
You can add TrueType fonts to vcs by using the `canvas.addfont` function
```
canvas.clear()
vcs.addfont("FFF_Tusj.ttf", name="Myfont")
txt.font = "Myfont"
canvas.plot(txt)
```
### Color<a id="color"></a>
You can control the font `color` via the color attribute, you can send a string representing the color name, an index in the text object colormap.
You can change the colormap via the `colormap` attribute
```
canvas.clear()
txt.font = "default"
txt.color = "Red"
canvas.plot(txt)
txt.x[0] += .2
txt.color = 5
canvas.plot(txt)
txt.colormap = "AMIP" # Changing the colormap chjange the color of index 5
txt.x[0] -= .4
canvas.plot(txt)
```
### Projection<a id="projection"></a>
IF your worldcoordinates are representing lat/lon, you can use the `projection` attribute to apply a projection (and its settings) to your text location.
```
canvas.clear()
import cdms2, os
f=cdms2.open(os.path.join(vcs.sample_data,"clt.nc"))
bot = canvas.gettemplate("bot_of2")
top = canvas.gettemplate("top_of2")
gm = canvas.createisoline()
gm.datawc_x1 = -180
gm.datawc_x2 = 180
gm.datawc_y1 = -90
gm.datawc_y2 = 90
canvas.plot(f("clt", slice(0,1)),gm,top)
proj = "polar"
gm.projection = proj
canvas.plot(f("clt",slice(0,1),longitude=(-180,181)),gm,bot)
txt = canvas.createtext()
txt.string = "Non proj"
txt.worldcoordinate = [-180,180,-90,90]
txt.x = -30
txt.y = 80
txt.color="blue"
txt.height = 15
txt.halign = "center"
txt.viewport = top.data.x1, top.data.x2, top.data.y1, top.data.y2
canvas.plot(txt)
txt.projection = proj
txt.color = "red"
txt.string = "PROJECTED"
txt.viewport = bot.data.x1, bot.data.x2, bot.data.y1, bot.data.y2
canvas.plot(txt)# canvas.plot(txt)
```
### Ordering in the plot<a id="priority"></a>
you can control the `layer` on which the object will be drawn via the `priority` attribute. Higher `priority` object are drawn on top of lower `priority` ones.
```
txt.priority = 0 # Turn off
txt.priority = 2 # move to a layer on top of "default" layer (1)
```
### Deprecated attributes<a id="deprecated"></a>
The following attribute are left over from XGKS and are not use anymore:
`spacing`, `fillingcolor`, `expansion`
## Text Orientation<a id="To"></a>
### Size<a id="size"></a>
You can control the size (or **height**) of text objects as follow:
```
canvas.clear()
txt = vcs.createtext()
txt.string = "Example of BIG Text"
txt.x = .5
txt.y = .5
txt.height = 30
canvas.plot(txt)
```
### Angle<a id="angle"></a>
You can control the **clockwise** rotation of a text object as shown bellow:
```
canvas.clear()
txt.angle = 45
txt.height =20.
txt.string = "A Rotated Text"
canvas.plot(txt)
```
### Alignement<a id="align"></a>
You can control how to align the text relatively to to its coordinates
#### Horizontal Alignement<a id="horiz"></a>
You can control the horizontal alignement via the **halign** attribute, possible values are: *('left', 'center', 'right') or (0, 1, 2)*
```
canvas.clear()
line = vcs.createline()
line.x = [.5,.5]
line.y = [0.,1.]
line.type ="dot"
line.color=["grey"]
center = vcs.createtext()
center.x = .5
center.y = .5
center.string = "Centered Text"
center.halign = "center"
right = vcs.createtext()
right.x = .5
right.y = .25
right.string = "Right Aligned Text"
right.halign = "right"
left = vcs.createtext()
left.x = .5
left.y = .75
left.string = "Left Aligned Text"
left.halign = "left"
canvas.plot(center)
canvas.plot(right)
canvas.plot(left)
canvas.plot(line)
```
#### Vertical Alignement<a id="vert"></a>
You can control the vertical alignement via the **valign** attribute, possible values are: *('top', 'cap', 'half', 'base', 'bottom') or (0, 1, 2, 3, 4)*
Note that **cap** is the same as **top** at the moment
```
canvas.clear()
line = vcs.createline()
line.y = [.5,.5]
line.x = [0.,1.]
line.type ="dot"
line.color=["grey"]
half = vcs.createtext()
half.height = 20
half.halign = "center"
half.x = .5
half.y = .5
half.string = "Half Aligned Text"
half.valign = "Half"
bottom = vcs.createtext()
bottom.halign='center'
bottom.height=20
bottom.x = .25
bottom.y = .5
bottom.string = "Bottom Aligned Text"
bottom.valign = "bottom"
top = vcs.createtext()
top.halign='center'
top.height=20
top.x = .75
top.y = .5
top.string = "Top Aligned Text"
top.valign = "top"
cap = vcs.createtext()
cap.x = .75
cap.y = .75
cap.string = "Cap Aligned Text"
cap.valign = "cap"
canvas.plot(half)
canvas.plot(bottom)
canvas.plot(top)
canvas.plot(line)
```
## Mathematical Expressions and Symbols<a id="math"></a>
See [dedicated notebook](https://cdat.llnl.gov/Jupyter/Mathematical_Expressions_and_Symbols/Mathematical_Expressions_and_Symbols.html)
## Example: Bringing it all together<a id="example"></a>
We are plotting a world coordinate locate rotated and colored text object on top of a map.
```
canvas.clear()
import cdms2, os
f=cdms2.open(os.path.join(vcs.sample_data,"clt.nc"))
# Continental U.S.A. region
lat1 = 15.
lat2 = 70.
lon1 = -140.
lon2 = -60.
proj = "lambert"
# Read data in
clt = f("clt",time=slice(0,1),latitude=(lat1,lat2),longitude=(lon1,lon2),squeeze=1)
# Isofill method
gm = vcs.createisofill()
gm.datawc_x1 = lon1
gm.datawc_x2 = lon2
gm.datawc_y1 = lat1
gm.datawc_y2 = lat2
gm.projection = proj
# Template (not modified)
templ = vcs.createtemplate()
# Text object
txt = vcs.createtext()
txt.string = ["Washington D.C.", "New York", "Los Angeles"]
txt.halign = "center"
txt.valign = "half"
txt.color = "red"
txt.font = "Myfont"
txt.height = 15
txt.priority = 2
txt.angle = -5
txt.y = [38.9072, 40.7128, 34.0522]
txt.x = [-77.0369, -74.0060, -118.2437]
txt.worldcoordinate = [lon1, lon2, lat1, lat2]
txt.viewport = [templ.data.x1, templ.data.x2, templ.data.y1, templ.data.y2]
txt.projection = proj
# Plot text first to show priority
canvas.plot(txt)
# Now data plotted "bellow" text
canvas.plot(clt,gm)
```
| github_jupyter |
# Simple Meander
Creates 3 transmon pockets, connected in different ways by the mean of transmission lines.
These transmission line QComponents create basic meanders to accommodate the user-defined line length.
### Preparations
The next cell enables [module automatic reload](https://ipython.readthedocs.io/en/stable/config/extensions/autoreload.html?highlight=autoreload). Your notebook will be able to pick up code updates made to the qiskit-metal (or other) module code.
```
%reload_ext autoreload
%autoreload 2
```
Import key libraries and open the Metal GUI. Also we configure the notebook to enable overwriting of existing components
```
from qiskit_metal import designs
from qiskit_metal import MetalGUI, Dict
design = designs.DesignPlanar()
gui = MetalGUI(design)
# if you disable the next line, then you will need to delete a component [<component>.delete()] before recreating it
design.overwrite_enabled = True
from qiskit_metal.qlibrary.core import QRouteLead
```
Create 3 Transmon Qbits with 4 pins. This uses the same definition (options) for all 3 Qbits, but it places them in 3 different (x,y) origin points.
```
from qiskit_metal.qlibrary.qubits.transmon_pocket import TransmonPocket
optionsQ = dict(
pad_width = '425 um',
pocket_height = '650um',
connection_pads = dict( # Qbits defined to have 4 pins
a = dict(loc_W=+1,loc_H=+1),
b = dict(loc_W=-1,loc_H=+1, pad_height='30um'),
c = dict(loc_W=+1,loc_H=-1, pad_width='200um'),
d = dict(loc_W=-1,loc_H=-1, pad_height='50um')
)
)
q1 = TransmonPocket(design, 'Q1', options = dict(pos_x='-1.5mm', pos_y='+0.0mm', **optionsQ))
q2 = TransmonPocket(design, 'Q2', options = dict(pos_x='+0.35mm', pos_y='+1.0mm', orientation = '90',**optionsQ))
q3 = TransmonPocket(design, 'Q3', options = dict(pos_x='2.0mm', pos_y='+0.0mm', **optionsQ))
gui.rebuild()
gui.autoscale()
gui.highlight_components(['Q1', 'Q2', 'Q3']) # This is to show the pins, so we can choose what to connect
```
# Using CPW meanders to connect the 3 Qbits
Import the RouteMeander and inspect what options are available for you to initialize
```
from qiskit_metal.qlibrary.tlines.meandered import RouteMeander
RouteMeander.get_template_options(design)
```
Let's define a dictionary with the options we want to keep global. We will then concatenate this dictionary to the ones we will use to describe the individual Qbits
```
ops=dict(fillet='90um')
```
Let's define the first CPW QComponent.
```
options = Dict(
total_length= '8mm',
hfss_wire_bonds = True,
pin_inputs=Dict(
start_pin=Dict(
component= 'Q1',
pin= 'a'),
end_pin=Dict(
component= 'Q2',
pin= 'b')),
lead=Dict(
start_straight='0mm',
end_straight='0.5mm'),
meander=Dict(
asymmetry='-1mm'),
**ops
)
# Below I am creating a CPW without assigning its name.
# Therefore running this cell twice will create two CPW's instead of overwriting the previous one
# To prevent that we add the cpw.delete() statement.
# The try-except wrapping is needed to suppress errors during the first run of this cell
try:
cpw.delete()
except NameError: pass
cpw = RouteMeander(design, options=options)
gui.rebuild()
gui.autoscale()
```
You might have received an expected python "warning - check_lengths" message.
This indicates that one of the CPW edges is too short to accommodate the fillet corner rounding previous defined at 90um.
Also, the CPW "start lead" does not offer enough clearance from the Qbit, causing a short between two pins.
Please take a minute to observe this behavior in the GUI
```
gui.screenshot()
```
You can inspect the points forming the CPW route to find the culprit edge (the warning message should have indicated the index of the offending edge)
```
cpw.get_points()
```
Turns out that both issues can be resolved by just adding enough clearance at the start of the CPW.
```
cpw.options['lead']['start_straight']='100um'
gui.rebuild()
gui.autoscale()
gui.screenshot()
```
Notice how the routing algorithm tries to prevent creation of edges too short to apply the fillet corner rounding. If your design requires it, you can disable this algorithm behavior for individual CPWs. For example try the cell below, and expect warning similar to the ones encountered earlier to show up
```
cpw.options['prevent_short_edges']='false'
gui.rebuild()
gui.autoscale()
```
You can eliminate the warning by either re-enabling the algorithm, or by changing the fillet for this specific CPW. Let's try the second approach for demonstration purposes
```
cpw.options['fillet']='65um'
gui.rebuild()
gui.autoscale()
```
Now let's create other 3 CPWs for practice
```
options = Dict(
total_length= '6mm',
pin_inputs=Dict(
start_pin=Dict(
component= 'Q2',
pin= 'd'),
end_pin=Dict(
component= 'Q3',
pin= 'b')),
lead=Dict(
start_straight='0.1mm',
end_straight='0.2mm'),
meander=Dict(
asymmetry='-0.9mm'),
**ops
)
try:
cpw2.delete()
except NameError: pass
cpw2 = RouteMeander(design,options=options)
gui.rebuild()
gui.autoscale()
options = Dict(
total_length= '8mm',
pin_inputs=Dict(
start_pin=Dict(
component= 'Q3',
pin= 'a'),
end_pin=Dict(
component= 'Q2',
pin= 'c')),
lead=Dict(
start_straight='0.5mm',
end_straight='0.1mm'),
meander=Dict(
asymmetry='-1mm'),
**ops
)
try:
cpw3.delete()
except NameError: pass
cpw3 = RouteMeander(design,options=options)
gui.rebuild()
gui.autoscale()
options = Dict(
total_length= '8mm',
pin_inputs=Dict(
start_pin=Dict(
component= 'Q1',
pin= 'b'),
end_pin=Dict(
component= 'Q2',
pin= 'a')),
lead=Dict(
start_straight='0.5mm',
end_straight='0.1mm'),
meander=Dict(
asymmetry='1mm'),
**ops
)
try:
cpw4.delete()
except NameError: pass
cpw4 = RouteMeander(design,options=options)
gui.rebuild()
gui.autoscale()
```
Let's try a more complex utilization of the leads. So far we have demonstrated `lead->start_straight` and `lead->end_straight`. We can "append" to the straight lead any number of custom jogs, which might be useful to get out of complex layout arrangements or to fine tune the meander in case of collisions with other components.
To define a jogged lead, you need an ordered sequence of turn-length pairs, which we define here as an ordered dictionary. We then apply the sequence of jogs to both the start and end leads (or you could apply it to only one them, or you can define the two leads separately with two ordered dictionaries)
```
from collections import OrderedDict
jogs = OrderedDict()
jogs[0] = ["L", '800um']
jogs[1] = ["L", '500um']
jogs[2] = ["R", '200um']
jogs[3] = ["R", '500um']
options = Dict(
total_length= '14mm',
pin_inputs=Dict(
start_pin=Dict(
component= 'Q1',
pin= 'd'),
end_pin=Dict(
component= 'Q3',
pin= 'd')),
lead=Dict(
start_straight='0.1mm',
end_straight='0.1mm',
start_jogged_extension=jogs,
end_jogged_extension=jogs),
meander=Dict(
asymmetry='-1.2mm'),
**ops
)
try:
cpw5.delete()
except NameError: pass
cpw5 = RouteMeander(design,options=options)
gui.rebuild()
gui.autoscale()
```
Here a few additional examples routing flexibility on a brand-new set of Qbits
```
q4 = TransmonPocket(design, 'Q4', options = dict(pos_x='-7.5mm', pos_y='-0.5mm', **optionsQ))
q5 = TransmonPocket(design, 'Q5', options = dict(pos_x='-5.65mm', pos_y='+0.5mm', orientation = '90',**optionsQ))
q6 = TransmonPocket(design, 'Q6', options = dict(pos_x='-4.0mm', pos_y='-0.6mm', **optionsQ))
gui.rebuild()
options = Dict(
total_length= '3.4mm',
pin_inputs=Dict(
start_pin=Dict(
component= 'Q4',
pin= 'a'),
end_pin=Dict(
component= 'Q5',
pin= 'b')),
lead=Dict(
start_straight='0.5mm',
end_straight='0.1mm'),
meander=Dict(
asymmetry='1mm'),
**ops
)
try:
cpw6.delete()
except NameError: pass
cpw6 = RouteMeander(design, options=options)
gui.rebuild()
gui.autoscale()
options = Dict(
total_length= '12mm',
pin_inputs=Dict(
start_pin=Dict(
component= 'Q4',
pin= 'd'),
end_pin=Dict(
component= 'Q6',
pin= 'c')),
lead=Dict(
start_straight='0.1mm',
end_straight='0.1mm'),
meander=Dict(
asymmetry='-1.2mm'),
**ops
)
try:
cpw7.delete()
except NameError: pass
cpw7 = RouteMeander(design, options=options)
gui.rebuild()
gui.autoscale()
options = Dict(
total_length= '13mm',
pin_inputs=Dict(
start_pin=Dict(
component= 'Q6',
pin= 'a'),
end_pin=Dict(
component= 'Q4',
pin= 'b')),
lead=Dict(
start_straight='0.1mm',
end_straight='0.1mm'),
meander=Dict(
asymmetry='-1.7mm'),
**ops
)
try:
cpw8.delete()
except NameError: pass
cpw8 = RouteMeander(design, options=options)
gui.rebuild()
gui.autoscale()
#If you would like to close the GUI. Remove the comment.
#gui.main_window.close()
```
| github_jupyter |
# Success/Errors Histogram
```
import torch
import torch.nn.functional as F
import numpy as np
from tqdm.notebook import tqdm
from sklearn.metrics import average_precision_score
from sklearn.metrics import roc_auc_score
import matplotlib.pyplot as plt
%matplotlib inline
import sys
sys.path.insert(0, '../')
from loaders import get_loader
from learners import get_learner
from utils import misc
# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# DEFINE HERE YOUR CONFIG PATH AND THE EPOCH YOU WANT TO EVALUATE
config_path = '/data/DEEPLEARNING/ccorbiere/logs/cifar10/github_weights/baseline/config_1.yaml'
ckpt_path = '/data/DEEPLEARNING/ccorbiere/logs/cifar10/github_weights/baseline/model_epoch_197.ckpt'
config_args = misc.load_yaml(config_path)
# Get data loader
dloader = get_loader(config_args)
dloader.make_loaders()
# Initialize and load model
learner = get_learner(config_args, dloader.train_loader, dloader.val_loader, dloader.test_loader, -1, device)
checkpoint = torch.load(ckpt_path)
learner.model.load_state_dict(checkpoint["model_state_dict"])
def predict_test_set(learner, mode='normal', samples=50, verbose=True):
accurate, errors, confidence = [], [], []
loop = tqdm(learner.test_loader, disable=not verbose)
for batch_id, (data, target) in enumerate(loop):
data, target = data.to(device), target.to(device)
with torch.no_grad():
if mode == "normal":
output = learner.model(data)
conf, pred = F.softmax(output, dim=1).max(dim=1, keepdim=True)
elif mode == "gt":
output = learner.model(data)
probs = F.softmax(output, dim=1)
pred = probs.max(dim=1, keepdim=True)[1]
labels_hot = misc.one_hot_embedding(target, learner.num_classes).to(device)
# Segmentation special case
if learner.task == "segmentation":
labels_hot = labels_hot.permute(0, 3, 1, 2)
conf, _ = (labels_hot * probs).max(dim=1, keepdim=True)
elif mode == "mc_dropout":
if learner.task == "classification":
outputs = torch.zeros(samples, data.shape[0], learner.num_classes).to(device)
elif learner.task == "segmentation":
outputs = torch.zeros(samples, data.shape[0], learner.num_classes,
data.shape[2], data.shape[3]).to(device)
for i in range(samples):
outputs[i] = learner.model(data)
output = outputs.mean(0)
probs = F.softmax(output, dim=1)
conf = (probs * torch.log(probs + 1e-9)).sum(dim=1) # entropy
pred = probs.max(dim=1, keepdim=True)[1]
elif mode=='confidnet':
output, conf = learner.model(data)
pred = output.argmax(dim=1, keepdim=True)
conf = torch.sigmoid(conf)
accurate.extend(pred.eq(target.view_as(pred)))
errors.extend(pred!=target.view_as(pred))
confidence.extend(conf)
confidence = torch.stack(confidence).detach().to('cpu').numpy() .flatten()
accurate = torch.cat(accurate).detach().to('cpu').numpy().flatten()
errors = torch.cat(errors).detach().to('cpu').numpy().flatten()
ap_success = average_precision_score(accurate, confidence)
ap_errors = average_precision_score(errors, -confidence)
return accurate, confidence, ap_success, ap_errors
accurate_normal, confidence_normal, _, _ = predict_test_set(learner, mode='normal')
accurate_gt, confidence_gt, _, _ = predict_test_set(learner, mode='gt')
plt.figure(figsize=(15,5))
plt.subplot(121)
plt.title('Maximum Class Probability', y=-0.2, fontsize=14)
plt.hist(confidence_normal[np.where(accurate_normal==1)],
bins=np.linspace(0, 1,num=21), density=True, color='green',label='Successes')
plt.hist(confidence_normal[np.where(accurate_normal==0)],
bins=np.linspace(0, 1,num=21), density=True, alpha=0.5, color='red',label='Errors')
plt.xlabel('Confidence')
plt.ylabel('Relative density')
plt.xlim(left=0, right=1)
plt.legend()
plt.subplot(122)
plt.title('True Class Probability', y=-0.2, fontsize=14)
plt.hist(confidence_gt[np.where(accurate_gt==1)],
bins=np.linspace(0, 1,num=21), density=True, color='green',label='Successes')
plt.hist(confidence_gt[np.where(accurate_gt==0)],
bins=np.linspace(0, 1,num=21), density=True, alpha=0.5, color='red',label='Errors')
plt.xlabel('Confidence')
plt.ylabel('Relative density')
plt.xlim(left=0, right=1)
plt.legend()
plt.show()
```
| github_jupyter |
<img src="http://hilpisch.com/tpq_logo.png" alt="The Python Quants" width="35%" align="right" border="0"><br>
# Python for Finance (2nd ed.)
**Mastering Data-Driven Finance**
© Dr. Yves J. Hilpisch | The Python Quants GmbH
<img src="http://hilpisch.com/images/py4fi_2nd_shadow.png" width="300px" align="left">
# Stochastics
```
import math
import numpy as np
import numpy.random as npr
from pylab import plt, mpl
plt.style.use('seaborn')
mpl.rcParams['font.family'] = 'serif'
%matplotlib inline
```
## Random Numbers
```
npr.seed(100)
np.set_printoptions(precision=4)
npr.rand(10) # [0, 1)之间均匀分配随机数
npr.rand(5, 5) # [0, 1)之间均匀分配随机数
a = 0.25
b = 0.5
npr.rand(10) * (b - a) + a # [0, 1)之间均匀分配随机数可以平移到任何区间,从[0, 1)可以模拟出所有的区间
a = 5.
b = 10.
npr.rand(10) * (b - a) + a # [0, 1)之间均匀分配随机数可以平移到任何区间
npr.rand(5, 5) * (b - a) + a
sample_size = 500
rn1 = npr.rand(sample_size, 3)
rn2 = npr.randint(0, 10, sample_size)
rn3 = npr.sample(size=sample_size)
a = [0, 25, 50, 75, 100]
rn4 = npr.choice(a, size=sample_size)
npr.rand?
npr.randint?
npr.sample?
npr.choice?
rn1
rn2
rn3
rn4
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2,
figsize=(10, 8))
ax1.hist(rn1, bins=25, stacked=True)
ax1.set_title('rand')
ax1.set_ylabel('frequency')
ax2.hist(rn2, bins=25)
ax2.set_title('randint')
ax3.hist(rn3, bins=25)
ax3.set_title('sample')
ax3.set_ylabel('frequency')
ax4.hist(rn4, bins=25)
ax4.set_title('choice');
# plt.savefig('../../images/ch12/stoch_01.png');
sample_size = 500
rn1 = npr.standard_normal(sample_size)
rn2 = npr.normal(100, 20, sample_size)
rn3 = npr.chisquare(df=0.5, size=sample_size)
rn4 = npr.poisson(lam=1.0, size=sample_size)
npr.normal?
npr.poisson?
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2,
figsize=(10, 8))
ax1.hist(rn1, bins=25)
ax1.set_title('standard normal')
ax1.set_ylabel('frequency')
ax2.hist(rn2, bins=25)
ax2.set_title('normal(100, 20)')
ax3.hist(rn3, bins=25)
ax3.set_title('chi square')
ax3.set_ylabel('frequency')
ax4.hist(rn4, bins=25)
ax4.set_title('Poisson');
# plt.savefig('../../images/ch12/stoch_02.png');
```
## Simulation
### Random Variables
```
S0 = 100
r = 0.05
sigma = 0.25
T = 2.0
I = 10000
ST1 = S0 * np.exp((r - 0.5 * sigma ** 2) * T +
sigma * math.sqrt(T) * npr.standard_normal(I))
plt.figure(figsize=(10, 6))
plt.hist(ST1, bins=50)
plt.xlabel('index level')
plt.ylabel('frequency');
# plt.savefig('../../images/ch12/stoch_03.png');
ST2 = S0 * npr.lognormal((r - 0.5 * sigma ** 2) * T,
sigma * math.sqrt(T), size=I)
plt.figure(figsize=(10, 6))
plt.hist(ST2, bins=50)
plt.xlabel('index level')
plt.ylabel('frequency');
# plt.savefig('../../images/ch12/stoch_04.png');
import scipy.stats as scs
def print_statistics(a1, a2):
''' Prints selected statistics.
Parameters
==========
a1, a2: ndarray objects
results objects from simulation
'''
sta1 = scs.describe(a1)
sta2 = scs.describe(a2)
print('%14s %14s %14s' %
('statistic', 'data set 1', 'data set 2'))
print(45 * "-")
print('%14s %14.3f %14.3f' % ('size', sta1[0], sta2[0]))
print('%14s %14.3f %14.3f' % ('min', sta1[1][0], sta2[1][0]))
print('%14s %14.3f %14.3f' % ('max', sta1[1][1], sta2[1][1]))
print('%14s %14.3f %14.3f' % ('mean', sta1[2], sta2[2]))
print('%14s %14.3f %14.3f' % ('std', np.sqrt(sta1[3]), np.sqrt(sta2[3])))
print('%14s %14.3f %14.3f' % ('skew', sta1[4], sta2[4]))
print('%14s %14.3f %14.3f' % ('kurtosis', sta1[5], sta2[5]))
print_statistics(ST1, ST2)
```
### Stochastic Processes
#### Geometric Brownian Motion
```
I = 10000
M = 50
dt = T / M
S = np.zeros((M + 1, I))
S[0] = S0
for t in range(1, M + 1):
S[t] = S[t - 1] * np.exp((r - 0.5 * sigma ** 2) * dt +
sigma * math.sqrt(dt) * npr.standard_normal(I))
plt.figure(figsize=(10, 6))
plt.hist(S[-1], bins=50)
plt.xlabel('index level')
plt.ylabel('frequency');
# plt.savefig('../../images/ch12/stoch_05.png');
print_statistics(S[-1], ST2)
plt.figure(figsize=(10, 6))
plt.plot(S[:, :10], lw=1.5)
plt.xlabel('time')
plt.ylabel('index level');
# plt.savefig('../../images/ch12/stoch_06.png');
```
#### Square-Root Diffusion
```
x0 = 0.05
kappa = 3.0
theta = 0.02
sigma = 0.1
I = 10000
M = 50
dt = T / M
def srd_euler():
xh = np.zeros((M + 1, I))
x = np.zeros_like(xh)
xh[0] = x0
x[0] = x0
for t in range(1, M + 1):
xh[t] = (xh[t - 1] +
kappa * (theta - np.maximum(xh[t - 1], 0)) * dt +
sigma * np.sqrt(np.maximum(xh[t - 1], 0)) *
math.sqrt(dt) * npr.standard_normal(I))
x = np.maximum(xh, 0)
return x
x1 = srd_euler()
plt.figure(figsize=(10, 6))
plt.hist(x1[-1], bins=50)
plt.xlabel('value')
plt.ylabel('frequency');
# plt.savefig('../../images/ch12/stoch_07.png');
plt.figure(figsize=(10, 6))
plt.plot(x1[:, :10], lw=1.5)
plt.xlabel('time')
plt.ylabel('index level');
# plt.savefig('../../images/ch12/stoch_08.png');
def srd_exact():
x = np.zeros((M + 1, I))
x[0] = x0
for t in range(1, M + 1):
df = 4 * theta * kappa / sigma ** 2
c = (sigma ** 2 * (1 - np.exp(-kappa * dt))) / (4 * kappa)
nc = np.exp(-kappa * dt) / c * x[t - 1]
x[t] = c * npr.noncentral_chisquare(df, nc, size=I)
return x
x2 = srd_exact()
plt.figure(figsize=(10, 6))
plt.hist(x2[-1], bins=50)
plt.xlabel('value')
plt.ylabel('frequency');
# plt.savefig('../../images/ch12/stoch_09.png');
plt.figure(figsize=(10, 6))
plt.plot(x2[:, :10], lw=1.5)
plt.xlabel('time')
plt.ylabel('index level');
# plt.savefig('../../images/ch12/stoch_10.png');
print_statistics(x1[-1], x2[-1])
I = 250000
%time x1 = srd_euler()
%time x2 = srd_exact()
print_statistics(x1[-1], x2[-1])
x1 = 0.0; x2 = 0.0
```
#### Stochastic Volatility
```
S0 = 100.
r = 0.05
v0 = 0.1
kappa = 3.0
theta = 0.25
sigma = 0.1
rho = 0.6
T = 1.0
corr_mat = np.zeros((2, 2))
corr_mat[0, :] = [1.0, rho]
corr_mat[1, :] = [rho, 1.0]
cho_mat = np.linalg.cholesky(corr_mat)
cho_mat
M = 50
I = 10000
dt = T / M
ran_num = npr.standard_normal((2, M + 1, I))
v = np.zeros_like(ran_num[0])
vh = np.zeros_like(v)
v[0] = v0
vh[0] = v0
for t in range(1, M + 1):
ran = np.dot(cho_mat, ran_num[:, t, :])
vh[t] = (vh[t - 1] +
kappa * (theta - np.maximum(vh[t - 1], 0)) * dt +
sigma * np.sqrt(np.maximum(vh[t - 1], 0)) *
math.sqrt(dt) * ran[1])
v = np.maximum(vh, 0)
S = np.zeros_like(ran_num[0])
S[0] = S0
for t in range(1, M + 1):
ran = np.dot(cho_mat, ran_num[:, t, :])
S[t] = S[t - 1] * np.exp((r - 0.5 * v[t]) * dt +
np.sqrt(v[t]) * ran[0] * np.sqrt(dt))
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 6))
ax1.hist(S[-1], bins=50)
ax1.set_xlabel('index level')
ax1.set_ylabel('frequency')
ax2.hist(v[-1], bins=50)
ax2.set_xlabel('volatility');
# plt.savefig('../../images/ch12/stoch_11.png');
print_statistics(S[-1], v[-1])
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True,
figsize=(10, 6))
ax1.plot(S[:, :10], lw=1.5)
ax1.set_ylabel('index level')
ax2.plot(v[:, :10], lw=1.5)
ax2.set_xlabel('time')
ax2.set_ylabel('volatility');
# plt.savefig('../../images/ch12/stoch_12.png');
```
#### Jump-Diffusion
```
S0 = 100.
r = 0.05
sigma = 0.2
lamb = 0.75
mu = -0.6
delta = 0.25
rj = lamb * (math.exp(mu + 0.5 * delta ** 2) - 1)
T = 1.0
M = 50
I = 10000
dt = T / M
S = np.zeros((M + 1, I))
S[0] = S0
sn1 = npr.standard_normal((M + 1, I))
sn2 = npr.standard_normal((M + 1, I))
poi = npr.poisson(lamb * dt, (M + 1, I))
for t in range(1, M + 1, 1):
S[t] = S[t - 1] * (np.exp((r - rj - 0.5 * sigma ** 2) * dt +
sigma * math.sqrt(dt) * sn1[t]) +
(np.exp(mu + delta * sn2[t]) - 1) *
poi[t])
S[t] = np.maximum(S[t], 0)
plt.figure(figsize=(10, 6))
plt.hist(S[-1], bins=50)
plt.xlabel('value')
plt.ylabel('frequency');
# plt.savefig('../../images/ch12/stoch_13.png');
plt.figure(figsize=(10, 6))
plt.plot(S[:, :10], lw=1.5)
plt.xlabel('time')
plt.ylabel('index level');
# plt.savefig('../../images/ch12/stoch_14.png');
```
### Variance Reduction
```
print('%15s %15s' % ('Mean', 'Std. Deviation'))
print(31 * '-')
for i in range(1, 31, 2):
npr.seed(100)
sn = npr.standard_normal(i ** 2 * 10000)
print('%15.12f %15.12f' % (sn.mean(), sn.std()))
i ** 2 * 10000
sn = npr.standard_normal(int(10000 / 2))
sn = np.concatenate((sn, -sn))
np.shape(sn)
sn.mean()
print('%15s %15s' % ('Mean', 'Std. Deviation'))
print(31 * "-")
for i in range(1, 31, 2):
npr.seed(1000)
sn = npr.standard_normal(i ** 2 * int(10000 / 2))
sn = np.concatenate((sn, -sn))
print("%15.12f %15.12f" % (sn.mean(), sn.std()))
sn = npr.standard_normal(10000)
sn.mean()
sn.std()
sn_new = (sn - sn.mean()) / sn.std()
sn_new.mean()
sn_new.std()
def gen_sn(M, I, anti_paths=True, mo_match=True):
''' Function to generate random numbers for simulation.
Parameters
==========
M: int
number of time intervals for discretization
I: int
number of paths to be simulated
anti_paths: boolean
use of antithetic variates
mo_math: boolean
use of moment matching
'''
if anti_paths is True:
sn = npr.standard_normal((M + 1, int(I / 2)))
sn = np.concatenate((sn, -sn), axis=1)
else:
sn = npr.standard_normal((M + 1, I))
if mo_match is True:
sn = (sn - sn.mean()) / sn.std()
return sn
```
## Valuation
### European Options
```
S0 = 100.
r = 0.05
sigma = 0.25
T = 1.0
I = 50000
def gbm_mcs_stat(K):
''' Valuation of European call option in Black-Scholes-Merton
by Monte Carlo simulation (of index level at maturity)
Parameters
==========
K: float
(positive) strike price of the option
Returns
=======
C0: float
estimated present value of European call option
'''
sn = gen_sn(1, I)
# simulate index level at maturity
ST = S0 * np.exp((r - 0.5 * sigma ** 2) * T
+ sigma * math.sqrt(T) * sn[1])
# calculate payoff at maturity
hT = np.maximum(ST - K, 0)
# calculate MCS estimator
C0 = math.exp(-r * T) * np.mean(hT)
return C0
gbm_mcs_stat(K=105.)
M = 50
def gbm_mcs_dyna(K, option='call'):
''' Valuation of European options in Black-Scholes-Merton
by Monte Carlo simulation (of index level paths)
Parameters
==========
K: float
(positive) strike price of the option
option : string
type of the option to be valued ('call', 'put')
Returns
=======
C0: float
estimated present value of European call option
'''
dt = T / M
# simulation of index level paths
S = np.zeros((M + 1, I))
S[0] = S0
sn = gen_sn(M, I)
for t in range(1, M + 1):
S[t] = S[t - 1] * np.exp((r - 0.5 * sigma ** 2) * dt
+ sigma * math.sqrt(dt) * sn[t])
# case-based calculation of payoff
if option == 'call':
hT = np.maximum(S[-1] - K, 0)
else:
hT = np.maximum(K - S[-1], 0)
# calculation of MCS estimator
C0 = math.exp(-r * T) * np.mean(hT)
return C0
gbm_mcs_dyna(K=110., option='call')
gbm_mcs_dyna(K=110., option='put')
from bsm_functions import bsm_call_value
stat_res = []
dyna_res = []
anal_res = []
k_list = np.arange(80., 120.1, 5.)
np.random.seed(100)
for K in k_list:
stat_res.append(gbm_mcs_stat(K))
dyna_res.append(gbm_mcs_dyna(K))
anal_res.append(bsm_call_value(S0, K, T, r, sigma))
stat_res = np.array(stat_res)
dyna_res = np.array(dyna_res)
anal_res = np.array(anal_res)
plt.figure(figsize=(10, 6))
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(10, 6))
ax1.plot(k_list, anal_res, 'b', label='analytical')
ax1.plot(k_list, stat_res, 'ro', label='static')
ax1.set_ylabel('European call option value')
ax1.legend(loc=0)
ax1.set_ylim(bottom=0)
wi = 1.0
ax2.bar(k_list - wi / 2, (anal_res - stat_res) / anal_res * 100, wi)
ax2.set_xlabel('strike')
ax2.set_ylabel('difference in %')
ax2.set_xlim(left=75, right=125);
# plt.savefig('../../images/ch12/stoch_15.png');
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(10, 6))
ax1.plot(k_list, anal_res, 'b', label='analytical')
ax1.plot(k_list, dyna_res, 'ro', label='dynamic')
ax1.set_ylabel('European call option value')
ax1.legend(loc=0)
ax1.set_ylim(bottom=0)
wi = 1.0
ax2.bar(k_list - wi / 2, (anal_res - dyna_res) / anal_res * 100, wi)
ax2.set_xlabel('strike')
ax2.set_ylabel('difference in %')
ax2.set_xlim(left=75, right=125);
# plt.savefig('../../images/ch12/stoch_16.png');
```
### American Options
```
def gbm_mcs_amer(K, option='call'):
''' Valuation of American option in Black-Scholes-Merton
by Monte Carlo simulation by LSM algorithm
Parameters
==========
K : float
(positive) strike price of the option
option : string
type of the option to be valued ('call', 'put')
Returns
=======
C0 : float
estimated present value of European call option
'''
dt = T / M
df = math.exp(-r * dt)
# simulation of index levels
S = np.zeros((M + 1, I))
S[0] = S0
sn = gen_sn(M, I)
for t in range(1, M + 1):
S[t] = S[t - 1] * np.exp((r - 0.5 * sigma ** 2) * dt
+ sigma * math.sqrt(dt) * sn[t])
# case based calculation of payoff
if option == 'call':
h = np.maximum(S - K, 0)
else:
h = np.maximum(K - S, 0)
# LSM algorithm
V = np.copy(h)
for t in range(M - 1, 0, -1):
reg = np.polyfit(S[t], V[t + 1] * df, 7)
C = np.polyval(reg, S[t])
V[t] = np.where(C > h[t], V[t + 1] * df, h[t])
# MCS estimator
C0 = df * np.mean(V[1])
return C0
gbm_mcs_amer(110., option='call')
gbm_mcs_amer(110., option='put')
euro_res = []
amer_res = []
k_list = np.arange(80., 120.1, 5.)
for K in k_list:
euro_res.append(gbm_mcs_dyna(K, 'put'))
amer_res.append(gbm_mcs_amer(K, 'put'))
euro_res = np.array(euro_res)
amer_res = np.array(amer_res)
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(10, 6))
ax1.plot(k_list, euro_res, 'b', label='European put')
ax1.plot(k_list, amer_res, 'ro', label='American put')
ax1.set_ylabel('call option value')
ax1.legend(loc=0)
wi = 1.0
ax2.bar(k_list - wi / 2, (amer_res - euro_res) / euro_res * 100, wi)
ax2.set_xlabel('strike')
ax2.set_ylabel('early exercise premium in %')
ax2.set_xlim(left=75, right=125);
# plt.savefig('../../images/ch12/stoch_17.png');
```
## Risk Measures
### Value-at-Risk
```
S0 = 100
r = 0.05
sigma = 0.25
T = 30 / 365.
I = 10000
ST = S0 * np.exp((r - 0.5 * sigma ** 2) * T +
sigma * np.sqrt(T) * npr.standard_normal(I))
R_gbm = np.sort(ST - S0)
plt.figure(figsize=(10, 6))
plt.hist(R_gbm, bins=50)
plt.xlabel('absolute return')
plt.ylabel('frequency');
# plt.savefig('../../images/ch12/stoch_18.png');
import warnings
warnings.simplefilter('ignore')
percs = [0.01, 0.1, 1., 2.5, 5.0, 10.0]
var = scs.scoreatpercentile(R_gbm, percs)
print('%16s %16s' % ('Confidence Level', 'Value-at-Risk'))
print(33 * '-')
for pair in zip(percs, var):
print('%16.2f %16.3f' % (100 - pair[0], -pair[1]))
dt = 30. / 365 / M
rj = lamb * (math.exp(mu + 0.5 * delta ** 2) - 1)
S = np.zeros((M + 1, I))
S[0] = S0
sn1 = npr.standard_normal((M + 1, I))
sn2 = npr.standard_normal((M + 1, I))
poi = npr.poisson(lamb * dt, (M + 1, I))
for t in range(1, M + 1, 1):
S[t] = S[t - 1] * (np.exp((r - rj - 0.5 * sigma ** 2) * dt
+ sigma * math.sqrt(dt) * sn1[t])
+ (np.exp(mu + delta * sn2[t]) - 1)
* poi[t])
S[t] = np.maximum(S[t], 0)
R_jd = np.sort(S[-1] - S0)
plt.figure(figsize=(10, 6))
plt.hist(R_jd, bins=50)
plt.xlabel('absolute return')
plt.ylabel('frequency');
# plt.savefig('../../images/ch12/stoch_19.png');
percs = [0.01, 0.1, 1., 2.5, 5.0, 10.0]
var = scs.scoreatpercentile(R_jd, percs)
print('%16s %16s' % ('Confidence Level', 'Value-at-Risk'))
print(33 * '-')
for pair in zip(percs, var):
print('%16.2f %16.3f' % (100 - pair[0], -pair[1]))
percs = list(np.arange(0.0, 10.1, 0.1))
gbm_var = scs.scoreatpercentile(R_gbm, percs)
jd_var = scs.scoreatpercentile(R_jd, percs)
plt.figure(figsize=(10, 6))
plt.plot(percs, gbm_var, 'b', lw=1.5, label='GBM')
plt.plot(percs, jd_var, 'r', lw=1.5, label='JD')
plt.legend(loc=4)
plt.xlabel('100 - confidence level [%]')
plt.ylabel('value-at-risk')
plt.ylim(ymax=0.0);
# plt.savefig('../../images/ch12/stoch_20.png');
```
### Credit Value Adjustments
```
S0 = 100.
r = 0.05
sigma = 0.2
T = 1.
I = 100000
ST = S0 * np.exp((r - 0.5 * sigma ** 2) * T
+ sigma * np.sqrt(T) * npr.standard_normal(I))
L = 0.5
p = 0.01
D = npr.poisson(p * T, I)
D = np.where(D > 1, 1, D)
math.exp(-r * T) * np.mean(ST)
CVaR = math.exp(-r * T) * np.mean(L * D * ST)
CVaR
S0_CVA = math.exp(-r * T) * np.mean((1 - L * D) * ST)
S0_CVA
S0_adj = S0 - CVaR
S0_adj
np.count_nonzero(L * D * ST)
plt.figure(figsize=(10, 6))
plt.hist(L * D * ST, bins=50)
plt.xlabel('loss')
plt.ylabel('frequency')
plt.ylim(ymax=175);
# plt.savefig('../../images/ch12/stoch_21.png');
K = 100.
hT = np.maximum(ST - K, 0)
C0 = math.exp(-r * T) * np.mean(hT)
C0
CVaR = math.exp(-r * T) * np.mean(L * D * hT)
CVaR
C0_CVA = math.exp(-r * T) * np.mean((1 - L * D) * hT)
C0_CVA
np.count_nonzero(L * D * hT)
np.count_nonzero(D)
I - np.count_nonzero(hT)
plt.figure(figsize=(10, 6))
plt.hist(L * D * hT, bins=50)
plt.xlabel('loss')
plt.ylabel('frequency')
plt.ylim(ymax=350);
# plt.savefig('../../images/ch12/stoch_22.png');
```
<img src="http://hilpisch.com/tpq_logo.png" alt="The Python Quants" width="35%" align="right" border="0"><br>
<a href="http://tpq.io" target="_blank">http://tpq.io</a> | <a href="http://twitter.com/dyjh" target="_blank">@dyjh</a> | <a href="mailto:training@tpq.io">training@tpq.io</a>
| github_jupyter |
This tutorial trains a 3D densenet for lung lesion classification from CT image patches.
The goal is to demonstrate MONAI's class activation mapping functions for visualising the classification models.
For the demo data:
- Please see the `bbox_gen.py` script for generating the patch classification data from MSD task06_lung (available via `monai.apps.DecathlonDataset`).
- Alternatively, the patch dataset (~130MB) is available for direct downloading at: https://drive.google.com/drive/folders/1pQdzdkkC9c2GOblLgpGlG3vxsSK9NtDx
[](https://colab.research.google.com/github/Project-MONAI/tutorials/blob/master/modules/interpretability/class_lung_lesion.ipynb)
```
!python -c "import monai" || pip install -q "monai-weekly[tqdm]"
import glob
import os
import random
import tempfile
import matplotlib.pyplot as plt
import monai
import numpy as np
import torch
from IPython.display import clear_output
from monai.networks.utils import eval_mode
from monai.transforms import (
AddChanneld,
Compose,
LoadImaged,
RandFlipd,
RandRotate90d,
RandSpatialCropd,
Resized,
ScaleIntensityRanged,
EnsureTyped,
)
from monai.visualize import plot_2d_or_3d_image
from sklearn.metrics import (
ConfusionMatrixDisplay,
classification_report,
confusion_matrix,
)
from torch.utils.tensorboard import SummaryWriter
monai.config.print_config()
random_seed = 42
monai.utils.set_determinism(random_seed)
np.random.seed(random_seed)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
directory = os.environ.get("MONAI_DATA_DIRECTORY")
root_dir = (
tempfile.mkdtemp() if directory is None else os.path.expanduser(directory)
)
data_path = os.path.join(root_dir, "patch")
url = "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/lung_lesion_patches.tar.gz"
monai.apps.download_and_extract(url, output_dir=data_path)
lesion = glob.glob(os.path.join(data_path, "lesion_*"))
non_lesion = glob.glob(os.path.join(data_path, "norm_*"))
# optionally make sure there's 50:50 lesion vs non-lesion
balance_classes = True
if balance_classes:
print(
f"Before balance -- Num lesion: {len(lesion)},"
f" num non-lesion: {len(non_lesion)}"
)
num_to_keep = min(len(lesion), len(non_lesion))
lesion = lesion[:num_to_keep]
non_lesion = non_lesion[:num_to_keep]
print(
f"After balance -- Num lesion: {len(lesion)},"
f" num non-lesion: {len(non_lesion)}"
)
labels = np.asarray(
[[0.0, 1.0]] * len(lesion) + [[1.0, 0.0]] * len(non_lesion)
)
all_files = [
{"image": img, "label": label}
for img, label in zip(lesion + non_lesion, labels)
]
random.shuffle(all_files)
print(f"total items: {len(all_files)}")
```
Split the data into 80% training and 20% validation
```
train_frac, val_frac = 0.8, 0.2
n_train = int(train_frac * len(all_files)) + 1
n_val = min(len(all_files) - n_train, int(val_frac * len(all_files)))
train_files, val_files = all_files[:n_train], all_files[-n_val:]
train_labels = [data["label"] for data in train_files]
print(f"total train: {len(train_files)}")
val_labels = [data["label"] for data in val_files]
n_neg, n_pos = np.sum(np.asarray(val_labels) == 0), np.sum(
np.asarray(val_labels) == 1
)
print(f"total valid: {len(val_labels)}")
```
Create the data loaders. These loaders will be used for both training/validation, as well as visualisations.
```
# Define transforms for image
win_size = (196, 196, 144)
train_transforms = Compose(
[
LoadImaged("image"),
AddChanneld("image"),
ScaleIntensityRanged(
"image",
a_min=-1000.0,
a_max=500.0,
b_min=0.0,
b_max=1.0,
clip=True,
),
RandFlipd("image", spatial_axis=0, prob=0.5),
RandFlipd("image", spatial_axis=1, prob=0.5),
RandFlipd("image", spatial_axis=2, prob=0.5),
RandSpatialCropd("image", roi_size=(64, 64, 40)),
Resized("image", spatial_size=win_size, mode="trilinear", align_corners=True),
RandRotate90d("image", prob=0.5, spatial_axes=[0, 1]),
EnsureTyped("image"),
]
)
val_transforms = Compose(
[
LoadImaged("image"),
AddChanneld("image"),
ScaleIntensityRanged(
"image",
a_min=-1000.0,
a_max=500.0,
b_min=0.0,
b_max=1.0,
clip=True,
),
Resized("image", spatial_size=win_size, mode="trilinear", align_corners=True),
EnsureTyped(("image", "label")),
]
)
persistent_cache = os.path.join(root_dir, "persistent_cache")
train_ds = monai.data.PersistentDataset(
data=train_files, transform=train_transforms, cache_dir=persistent_cache
)
train_loader = monai.data.DataLoader(
train_ds, batch_size=2, shuffle=True, num_workers=2, pin_memory=True
)
val_ds = monai.data.PersistentDataset(
data=val_files, transform=val_transforms, cache_dir=persistent_cache
)
val_loader = monai.data.DataLoader(
val_ds, batch_size=2, num_workers=2, pin_memory=True
)
```
Start the model, loss function, and optimizer.
```
model = monai.networks.nets.DenseNet121(
spatial_dims=3, in_channels=1, out_channels=2
).to(device)
bce = torch.nn.BCEWithLogitsLoss()
def criterion(logits, target):
return bce(logits.view(-1), target.view(-1))
optimizer = torch.optim.Adam(model.parameters(), 1e-5)
```
Run training iterations.
```
# start training
val_interval = 1
max_epochs = 100
best_metric = best_metric_epoch = -1
epoch_loss_values = []
metric_values = []
scaler = torch.cuda.amp.GradScaler()
for epoch in range(max_epochs):
clear_output()
print("-" * 10)
print(f"epoch {epoch + 1}/{max_epochs}")
model.train()
epoch_loss = step = 0
for batch_data in train_loader:
inputs, labels = (
batch_data["image"].to(device),
batch_data["label"].to(device),
)
optimizer.zero_grad()
with torch.cuda.amp.autocast():
outputs = model(inputs)
loss = criterion(outputs.float(), labels.float())
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
epoch_loss += loss.item()
epoch_len = len(train_ds) // train_loader.batch_size
if step % 50 == 0:
print(f"{step}/{epoch_len}, train_loss: {loss.item():.4f}")
step += 1
epoch_loss /= step
epoch_loss_values.append(epoch_loss)
print(f"epoch {epoch + 1} average loss: {epoch_loss:.4f}")
if (epoch + 1) % val_interval == 0:
with eval_mode(model):
num_correct = 0.0
metric_count = 0
for val_data in val_loader:
val_images, val_labels = (
val_data["image"].to(device),
val_data["label"].to(device),
)
val_outputs = model(val_images)
value = torch.eq(
val_outputs.argmax(dim=1), val_labels.argmax(dim=1)
)
metric_count += len(value)
num_correct += value.sum().item()
metric = num_correct / metric_count
metric_values.append(metric)
if metric >= best_metric:
best_metric = metric
best_metric_epoch = epoch + 1
torch.save(
model.state_dict(),
"best_metric_model_classification3d_array.pth",
)
print(
f"current epoch: {epoch + 1} current accuracy: {metric:.4f}"
f" best accuracy: {best_metric:.4f}"
f" at epoch {best_metric_epoch}"
)
print(
f"train completed, best_metric: {best_metric:.4f} at"
f" epoch: {best_metric_epoch}"
)
plt.plot(epoch_loss_values, label="training loss")
val_epochs = np.linspace(
1, max_epochs, np.floor(max_epochs / val_interval).astype(np.int32)
)
plt.plot(val_epochs, metric_values, label="validation acc")
plt.legend()
plt.xlabel("Epoch")
plt.ylabel("Value")
# Reload the best network and display info
model_3d = monai.networks.nets.DenseNet121(
spatial_dims=3, in_channels=1, out_channels=2
).to(device)
model_3d.load_state_dict(
torch.load("best_metric_model_classification3d_array.pth")
)
model_3d.eval()
y_pred = torch.tensor([], dtype=torch.float32, device=device)
y = torch.tensor([], dtype=torch.long, device=device)
for val_data in val_loader:
val_images = val_data["image"].to(device)
val_labels = val_data["label"].to(device).argmax(dim=1)
outputs = model_3d(val_images)
y_pred = torch.cat([y_pred, outputs.argmax(dim=1)], dim=0)
y = torch.cat([y, val_labels], dim=0)
print(
classification_report(
y.cpu().numpy(),
y_pred.cpu().numpy(),
target_names=["non-lesion", "lesion"],
)
)
cm = confusion_matrix(
y.cpu().numpy(),
y_pred.cpu().numpy(),
normalize="true",
)
disp = ConfusionMatrixDisplay(
confusion_matrix=cm,
display_labels=["non-lesion", "lesion"],
)
disp.plot(ax=plt.subplots(1, 1, facecolor="white")[1])
```
# Interpretability
Use GradCAM and occlusion sensitivity for network interpretability.
The occlusion sensitivity returns two images: the sensitivity image and the most probable class.
* Sensitivity image -- how the probability of an inferred class changes as the corresponding part of the image is occluded.
* Big decreases in the probability imply that that region was important in inferring the given class
* The output is the same as the input, with an extra dimension of size N appended. Here, N is the number of inferred classes. To then see the sensitivity image of the class we're interested (maybe the true class, maybe the predcited class, maybe anything else), we simply do ``im[...,i]``.
* Most probable class -- if that part of the image is covered up, does the predicted class change, and if so, to what? This feature is not used in this notebook.
```
# cam = monai.visualize.CAM(nn_module=model_3d, target_layers="class_layers.relu", fc_layers="class_layers.out")
cam = monai.visualize.GradCAM(
nn_module=model_3d, target_layers="class_layers.relu"
)
# cam = monai.visualize.GradCAMpp(nn_module=model_3d, target_layers="class_layers.relu")
print(
"original feature shape",
cam.feature_map_size([1, 1] + list(win_size), device),
)
print("upsampled feature shape", [1, 1] + list(win_size))
occ_sens = monai.visualize.OcclusionSensitivity(
nn_module=model_3d, mask_size=12, n_batch=1, stride=28
)
# For occlusion sensitivity, inference must be run many times. Hence, we can use a
# bounding box to limit it to a 2D plane of interest (z=the_slice) where each of
# the arguments are the min and max for each of the dimensions (in this case CHWD).
the_slice = train_ds[0]["image"].shape[-1] // 2
occ_sens_b_box = [-1, -1, -1, -1, -1, -1, the_slice, the_slice]
train_transforms.set_random_state(42)
n_examples = 5
subplot_shape = [3, n_examples]
fig, axes = plt.subplots(*subplot_shape, figsize=(25, 15), facecolor="white")
items = np.random.choice(len(train_ds), size=len(train_ds), replace=False)
example = 0
for item in items:
data = train_ds[
item
] # this fetches training data with random augmentations
image, label = data["image"].to(device).unsqueeze(0), data["label"][1]
y_pred = model_3d(image)
pred_label = y_pred.argmax(1).item()
# Only display tumours images
if label != 1 or label != pred_label:
continue
img = image.detach().cpu().numpy()[..., the_slice]
name = "actual: "
name += "lesion" if label == 1 else "non-lesion"
name += "\npred: "
name += "lesion" if pred_label == 1 else "non-lesion"
name += f"\nlesion: {y_pred[0,1]:.3}"
name += f"\nnon-lesion: {y_pred[0,0]:.3}"
# run CAM
cam_result = cam(x=image, class_idx=None)
cam_result = cam_result[..., the_slice]
# run occlusion
occ_result, _ = occ_sens(x=image, b_box=occ_sens_b_box)
occ_result = occ_result[..., pred_label]
for row, (im, title) in enumerate(
zip(
[img, cam_result, occ_result],
[name, "CAM", "Occ. sens."],
)
):
cmap = "gray" if row == 0 else "jet"
ax = axes[row, example]
if isinstance(im, torch.Tensor):
im = im.cpu().detach()
im_show = ax.imshow(im[0][0], cmap=cmap)
ax.set_title(title, fontsize=25)
ax.axis("off")
fig.colorbar(im_show, ax=ax)
example += 1
if example == n_examples:
break
with SummaryWriter(log_dir="logs") as writer:
plot_2d_or_3d_image(img, step=0, writer=writer, tag="Input")
plot_2d_or_3d_image(cam_result, step=0, writer=writer, tag="CAM")
plot_2d_or_3d_image(occ_result, step=0, writer=writer, tag="OccSens")
%load_ext tensorboard
%tensorboard --logdir logs
```
| github_jupyter |
# Front Page DeepExplainer MNIST Example
A simple example showing how to explain an MNIST CNN trained using Keras with DeepExplainer.
```
# this is the code from https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
batch_size = 128
num_classes = 10
epochs = 12
# input image dimensions
img_rows, img_cols = 28, 28
# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
activation='relu',
input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# ...include code from https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py
import shap
import numpy as np
# select a set of background examples to take an expectation over
background = x_train[np.random.choice(x_train.shape[0], 100, replace=False)]
# explain predictions of the model on three images
e = shap.DeepExplainer(model, background)
# ...or pass tensors directly
# e = shap.DeepExplainer((model.layers[0].input, model.layers[-1].output), background)
shap_values = e.shap_values(x_test[1:5])
# plot the feature attributions
shap.image_plot(shap_values, -x_test[1:5])
```
The plot above shows the explanations for each class on four predictions. Note that the explanations are ordered for the classes 0-9 going left to right along the rows.
| github_jupyter |
```
directory = 'nn_leak/'
filename = 'nn_leak'
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import os
import datetime
import gc
from meteocalc import Temp, dew_point, heat_index, wind_chill, feels_like
# Any results you write to the current directory are saved as output.
from sklearn.metrics import mean_squared_error
from keras.models import Model, load_model
from keras.layers import Input, Dropout, Dense, Embedding, SpatialDropout1D, concatenate, BatchNormalization, Flatten, PReLU, CuDNNLSTM
from keras.preprocessing.sequence import pad_sequences
from keras.preprocessing import text, sequence
from keras.callbacks import Callback
from keras import backend as K
from keras.models import Model
from keras.losses import mean_squared_error as mse_loss
from keras import optimizers
from keras.optimizers import RMSprop, Adam
from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
from sklearn.preprocessing import LabelEncoder
import warnings
warnings.filterwarnings('ignore')
def fill_weather_dataset(weather):
zone_dict={0:4,1:0,2:7,3:4,4:7,5:0,6:4,7:4,8:4,9:5,10:7,11:4,12:0,13:5,14:4,15:4}
def set_localtime(df):
df['timestamp'] = pd.to_datetime(df['timestamp'])
for sid, zone in zone_dict.items():
sids = df.site_id == sid
df.loc[sids, 'timestamp'] = df[sids].timestamp - pd.offsets.Hour(zone)
df['timestamp'] = df['timestamp'].dt.strftime("%Y-%m-%d %H:%M:%S")
set_localtime(weather)
# Find Missing Dates
time_format = "%Y-%m-%d %H:%M:%S"
start_date = datetime.datetime.strptime(weather['timestamp'].min(),time_format)
end_date = datetime.datetime.strptime(weather['timestamp'].max(),time_format)
total_hours = int(((end_date - start_date).total_seconds() + 3600) / 3600)
hours_list = [(end_date - datetime.timedelta(hours=x)).strftime(time_format) for x in range(total_hours)]
missing_hours = []
for site_id in range(16):
site_hours = np.array(weather[weather['site_id'] == site_id]['timestamp'])
new_rows = pd.DataFrame(np.setdiff1d(hours_list,site_hours),columns=['timestamp'])
new_rows['site_id'] = site_id
weather = pd.concat([weather,new_rows])
weather = weather.reset_index(drop=True)
# Add new Features
weather["datetime"] = pd.to_datetime(weather["timestamp"])
weather["day"] = weather["datetime"].dt.day
weather["week"] = weather["datetime"].dt.week
weather["month"] = weather["datetime"].dt.month
# Reset Index for Fast Update
weather = weather.set_index(['site_id','day','month'])
air_temperature_filler = pd.DataFrame(weather.groupby(['site_id','day','month'])['air_temperature'].mean(),columns=["air_temperature"])
weather.update(air_temperature_filler,overwrite=False)
cloud_coverage_filler = weather.groupby(['site_id','day','month'])['cloud_coverage'].mean()
cloud_coverage_filler = pd.DataFrame(cloud_coverage_filler.fillna(method='ffill'),columns=["cloud_coverage"])
weather.update(cloud_coverage_filler,overwrite=False)
due_temperature_filler = pd.DataFrame(weather.groupby(['site_id','day','month'])['dew_temperature'].mean(),columns=["dew_temperature"])
weather.update(due_temperature_filler,overwrite=False)
sea_level_filler = weather.groupby(['site_id','day','month'])['sea_level_pressure'].mean()
sea_level_filler = pd.DataFrame(sea_level_filler.fillna(method='ffill'),columns=['sea_level_pressure'])
weather.update(sea_level_filler,overwrite=False)
wind_direction_filler = pd.DataFrame(weather.groupby(['site_id','day','month'])['wind_direction'].mean(),columns=['wind_direction'])
weather.update(wind_direction_filler,overwrite=False)
wind_speed_filler = pd.DataFrame(weather.groupby(['site_id','day','month'])['wind_speed'].mean(),columns=['wind_speed'])
weather.update(wind_speed_filler,overwrite=False)
precip_depth_filler = weather.groupby(['site_id','day','month'])['precip_depth_1_hr'].mean()
precip_depth_filler = pd.DataFrame(precip_depth_filler.fillna(method='ffill'),columns=['precip_depth_1_hr'])
weather.update(precip_depth_filler,overwrite=False)
weather = weather.reset_index()
weather = weather.drop(['datetime','day','week','month'],axis=1)
weather.loc[weather['dew_temperature'] > weather['air_temperature'], 'dew_temperature'] = weather['air_temperature']
weather['humidity'] = 100*(np.exp((17.625*weather['dew_temperature'])/(243.04+weather['dew_temperature']))/np.exp((17.625*weather['air_temperature'])/(243.04+weather['air_temperature'])))
weather['heat_index'] = weather.apply(lambda x: heat_index(temperature=x['air_temperature'], humidity=x['humidity']), axis=1)
weather['heat_index'] = weather['heat_index'].apply(lambda x: round(x, 2))
weather['feels_like'] = weather.apply(lambda x: feels_like(temperature=x['air_temperature'], humidity=x['humidity'], wind_speed=x['wind_speed']), axis=1)
weather['feels_like'] = weather['feels_like'].apply(lambda x: round(x, 2))
return weather
weather_train = pd.read_csv("../weather_train.csv")
weather_train = fill_weather_dataset(weather_train)
def create_lag_features(df, window):
df['ave_temp'] = df['air_temperature']/2 + df['dew_temperature']/2
feature_cols = ["air_temperature", "dew_temperature", "cloud_coverage", "precip_depth_1_hr","ave_temp",
"humidity",'heat_index']
df_site = df.groupby("site_id")
df_rolled = df_site[feature_cols].rolling(window=window, min_periods=0)
df_mean = df_rolled.mean().reset_index().astype(np.float16)
df_min = df_rolled.min().reset_index().astype(np.float16)
df_std = df_rolled.std().reset_index().astype(np.float16)
for feature in feature_cols:
df[f"{feature}_mean_lag{window}"] = df_mean[feature]
df[f"{feature}_min_lag{window}"] = df_min[feature]
df[f"{feature}_std_lag{window}"] = df_std[feature]
if window == 6:
for feature in feature_cols:
df[f"{feature}_diff1"] = df[feature].diff(1)
return df
weather_train = create_lag_features(weather_train, 6)
weather_test = pd.read_csv('../weather_test.csv')
weather_test = fill_weather_dataset(weather_test)
weather_test = create_lag_features(weather_test, 6)
weather = pd.concat([weather_train, weather_test])
def set_holiday2(dataframe):
# site 0
date1 = pd.date_range(start='1/1/2016',end='1/05/2016')
date2 = pd.date_range(start='3/21/2016', end='3/27/2016')
date3 = pd.date_range(start='11/24/2016', end='11/25/2016')
date4 = pd.date_range(start='12/19/2016',end='12/31/2016')
date5 = pd.date_range(start='1/1/2017', end='1/08/2017')
date6 = pd.date_range(start='3/13/2017', end='3/17/2017')
date7 = pd.date_range(start='11/23/2017', end='11/24/2017')
date8 = pd.date_range(start='12/19/2017',end='12/31/2017')
date9 = pd.date_range(start='1/1/2018', end='1/07/2018')
date10 = pd.date_range(start='3/12/2018', end='3/18/2018')
date11 = pd.date_range(start='11/22/2018', end='11/23/2018')
date12 = pd.date_range(start='12/19/2018',end='12/31/2018')
site0_hol = date1.union(date2).union(date3).union(date4).union(date5).union(date6).union(date7).union(date8).union(date9).union(date10).union(date11).union(date12)
sids = dataframe.site_id == 0
dataframe.loc[(sids) & (dataframe.timestamp.isin((site0_hol))), 'is_holiday'] = 1
# site 1
date1 = pd.date_range(start='1/1/2016',end='1/03/2016')
date2 = pd.date_range(start='3/25/2016', end='3/30/2016')
date3 = pd.date_range(start='12/24/2016',end='12/31/2016')
date4 = pd.date_range(start='1/1/2017', end='1/02/2017')
date5 = pd.date_range(start='3/13/2017', end='3/19/2017')
date6 = pd.date_range(start='12/23/2017',end='12/31/2017')
date7 = pd.date_range(start='3/29/2018', end='4/04/2018')
date8 = pd.date_range(start='12/22/2018',end='12/31/2018')
site1_hol = date1.union(date2).union(date3).union(date4).union(date5).union(date6).union(date7).union(date8)
sids = dataframe.site_id == 1
dataframe.loc[(sids) & (dataframe.timestamp.isin((site1_hol))), 'is_holiday'] = 1
# site 2
date1 = pd.date_range(start='1/1/2016',end='1/12/2016')
date2 = pd.date_range(start='3/12/2016', end='3/20/2016')
date3 = pd.date_range(start='11/24/2016', end='11/27/2016')
date4 = pd.date_range(start='12/26/2016',end='12/27/2016')
date5 = pd.date_range(start='1/1/2017', end='1/9/2017')
date6 = pd.date_range(start='3/11/2017', end='3/19/2017')
date7 = pd.date_range(start='11/23/2017', end='11/26/2017')
date8 = pd.date_range(start='12/25/2017',end='12/26/2017')
date9 = pd.date_range(start='1/1/2018', end='1/09/2018')
date10 = pd.date_range(start='3/5/2018', end='3/9/2018')
date11 = pd.date_range(start='11/22/2018', end='11/25/2018')
date12 = pd.date_range(start='12/24/2018',end='12/25/2018')
site2_hol = date1.union(date2).union(date3).union(date4).union(date5).union(date6).union(date7).union(date8).union(date9).union(date10).union(date11).union(date12)
sids = dataframe.site_id == 2
dataframe.loc[(sids) & (dataframe.timestamp.isin((site2_hol))), 'is_holiday'] = 1
# site 4
date1 = pd.date_range(start='1/1/2016',end='1/11/2016')
date2 = pd.date_range(start='3/21/2016', end='3/25/2016')
date3 = pd.date_range(start='11/24/2016', end='11/25/2016')
date4 = pd.date_range(start='12/26/2016',end='12/27/2016')
date5 = pd.date_range(start='1/1/2017', end='1/9/2017')
date6 = pd.date_range(start='3/27/2017', end='3/31/2017')
date7 = pd.date_range(start='11/23/2017', end='11/26/2017')
date8 = pd.date_range(start='12/25/2017',end='12/26/2017')
date9 = pd.date_range(start='12/29/2017',end='12/29/2017')
date10 = pd.date_range(start='1/1/2018', end='1/08/2018')
date11 = pd.date_range(start='3/26/2018', end='3/30/2018')
date12 = pd.date_range(start='11/22/2018', end='11/23/2018')
date13 = pd.date_range(start='12/24/2018',end='12/25/2018')
date14 = pd.date_range(start='12/31/2018',end='12/31/2018')
site4_hol = date1.union(date2).union(date3).union(date4).union(date5).union(date6).union(date7).union(date8).union(date9).union(date10).union(date11).union(date12).union(date13).union(date14)
sids = dataframe.site_id == 4
dataframe.loc[(sids) & (dataframe.timestamp.isin((site4_hol))), 'is_holiday'] = 1
# site 5
date1 = pd.date_range(start='1/1/2016',end='1/3/2016')
date2 = pd.date_range(start='3/19/2016', end='4/17/2016')
date3 = pd.date_range(start='6/11/2016', end='8/21/2016')
date4 = pd.date_range(start='1/1/2017',end='1/8/2017')
date5 = pd.date_range(start='3/23/2017', end='4/23/2017')
date6 = pd.date_range(start='6/17/2017', end='8/20/2017')
date7 = pd.date_range(start='1/1/2018',end='1/7/2018')
date8 = pd.date_range(start='3/17/2018', end='4/15/2018')
date9 = pd.date_range(start='6/16/2018', end='8/19/2018')
site5_hol = date1.union(date2).union(date3).union(date4).union(date5).union(date6).union(date7).union(date8).union(date9)
sids = dataframe.site_id == 5
dataframe.loc[(sids) & (dataframe.timestamp.isin((site5_hol))), 'is_holiday'] = 1
# site 7&11
date1 = pd.date_range(start='1/1/2016',end='1/06/2016')
date2 = pd.date_range(start='2/29/2016', end='3/4/2016')
date3 = pd.date_range(start='11/24/2016', end='11/25/2016')
date4 = pd.date_range(start='12/23/2016',end='12/31/2016')
date5 = pd.date_range(start='1/1/2017', end='1/03/2017')
date6 = pd.date_range(start='2/27/2017', end='3/3/2017')
date7 = pd.date_range(start='11/23/2017', end='11/24/2017')
date8 = pd.date_range(start='12/23/2017',end='12/31/2017')
date9 = pd.date_range(start='1/1/2018', end='1/07/2018')
date10 = pd.date_range(start='3/5/2018', end='3/9/2018')
date11 = pd.date_range(start='11/22/2018', end='11/23/2018')
date12 = pd.date_range(start='12/24/2018',end='12/31/2018')
site_hol = date1.union(date2).union(date3).union(date4).union(date5).union(date6).union(date7).union(date8).union(date9).union(date10).union(date11).union(date12)
sids = dataframe.site_id == 7
dataframe.loc[(sids) & (dataframe.timestamp.isin((site_hol))), 'is_holiday'] = 1
sids = dataframe.site_id == 11
dataframe.loc[(sids) & (dataframe.timestamp.isin((site_hol))), 'is_holiday'] = 1
# site 9
date1 = pd.date_range(start='1/1/2016',end='1/06/2016')
date2 = pd.date_range(start='3/14/2016', end='3/19/2016')
date3 = pd.date_range(start='11/23/2016', end='11/26/2016')
date4 = pd.date_range(start='12/23/2016',end='12/31/2016')
date5 = pd.date_range(start='1/1/2017', end='1/04/2017')
date6 = pd.date_range(start='3/13/2017', end='3/18/2017')
date7 = pd.date_range(start='11/22/2017', end='11/25/2017')
date8 = pd.date_range(start='12/23/2017',end='12/31/2017')
date9 = pd.date_range(start='1/1/2018', end='1/03/2018')
date10 = pd.date_range(start='3/12/2018', end='3/17/2018')
date11 = pd.date_range(start='11/21/2018', end='11/24/2018')
date12 = pd.date_range(start='12/24/2018',end='12/31/2018')
site9_hol = date1.union(date2).union(date3).union(date4).union(date5).union(date6).union(date7).union(date8).union(date9).union(date10).union(date11).union(date12)
sids = dataframe.site_id == 9
dataframe.loc[(sids) & (dataframe.timestamp.isin((site9_hol))), 'is_holiday'] = 1
# site 10
date1 = pd.date_range(start='1/1/2016',end='1/10/2016')
date2 = pd.date_range(start='3/5/2016', end='3/13/2016')
date3 = pd.date_range(start='11/24/2016', end='11/25/2016')
date4 = pd.date_range(start='12/23/2016',end='12/31/2016')
date5 = pd.date_range(start='1/1/2017', end='1/08/2017')
date6 = pd.date_range(start='3/4/2017', end='3/12/2017')
date7 = pd.date_range(start='11/23/2017', end='11/24/2017')
date8 = pd.date_range(start='12/24/2017',end='12/31/2017')
date9 = pd.date_range(start='1/1/2018', end='1/07/2018')
date10 = pd.date_range(start='3/3/2018', end='3/11/2018')
date11 = pd.date_range(start='11/22/2018', end='11/23/2018')
date12 = pd.date_range(start='12/24/2018',end='12/31/2018')
site10_hol = date1.union(date2).union(date3).union(date4).union(date5).union(date6).union(date7).union(date8).union(date9).union(date10).union(date11).union(date12)
sids = dataframe.site_id == 10
dataframe.loc[(sids) & (dataframe.timestamp.isin((site10_hol))), 'is_holiday'] = 1
# site 13
date1 = pd.date_range(start='1/1/2016',end='1/12/2016')
date2 = pd.date_range(start='3/7/2016', end='3/11/2016')
date3 = pd.date_range(start='10/27/2016', end='10/28/2016')
date4 = pd.date_range(start='11/24/2016', end='11/25/2016')
date5 = pd.date_range(start='12/23/2016',end='12/30/2016')
date6 = pd.date_range(start='1/1/2017',end='1/10/2017')
date7 = pd.date_range(start='3/6/2017', end='3/10/2017')
date8 = pd.date_range(start='10/26/2017', end='10/27/2017')
date9 = pd.date_range(start='11/23/2017', end='11/24/2017')
date10 = pd.date_range(start='12/25/2017',end='12/29/2017')
date11 = pd.date_range(start='1/1/2018',end='1/9/2018')
date12 = pd.date_range(start='3/5/2018', end='3/9/2018')
date13 = pd.date_range(start='10/25/2018', end='10/26/2018')
date14 = pd.date_range(start='11/22/2018', end='11/23/2018')
date15 = pd.date_range(start='12/25/2018',end='12/26/2018')
date16 = pd.date_range(start='12/31/2018',end='12/31/2018')
site13_hol = date1.union(date2).union(date3).union(date4).union(date5).union(date6).union(date7).union(date8).union(date9).union(date10).union(date11).union(date12).union(date13).union(date14).union(date15).union(date16)
sids = dataframe.site_id == 13
dataframe.loc[(sids) & (dataframe.timestamp.isin((site13_hol))), 'is_holiday'] = 1
# site 14
date1 = pd.date_range(start='1/1/2016',end='1/03/2016')
date2 = pd.date_range(start='3/5/2016', end='3/13/2016')
date3 = pd.date_range(start='11/23/2016', end='11/27/2016')
date4 = pd.date_range(start='1/1/2017', end='1/02/2017')
date5 = pd.date_range(start='3/4/2017', end='3/12/2017')
date6 = pd.date_range(start='11/22/2017', end='11/26/2017')
date7 = pd.date_range(start='1/1/2018', end='1/02/2018')
date8 = pd.date_range(start='3/3/2018', end='3/11/2018')
date9 = pd.date_range(start='11/21/2018', end='11/25/2018')
site14_hol = date1.union(date2).union(date3).union(date4).union(date5).union(date6).union(date7).union(date8).union(date9)
sids = dataframe.site_id == 14
dataframe.loc[(sids) & (dataframe.timestamp.isin((site14_hol))), 'is_holiday'] = 1
# site 15
date1 = pd.date_range(start='1/1/2016',end='1/03/2016')
date2 = pd.date_range(start='2/13/2016',end='2/17/2016')
date3 = pd.date_range(start='3/26/2016', end='4/3/2016')
date4 = pd.date_range(start='10/8/2016', end='10/11/2016')
date5 = pd.date_range(start='11/23/2016', end='11/27/2016')
date6 = pd.date_range(start='12/26/2016',end='12/31/2016')
date7 = pd.date_range(start='1/1/2017',end='1/02/2017')
date8 = pd.date_range(start='2/18/2017',end='2/21/2017')
date9 = pd.date_range(start='4/1/2017', end='4/9/2017')
date10 = pd.date_range(start='10/7/2017', end='10/10/2017')
date11 = pd.date_range(start='11/22/2017', end='11/26/2017')
date12 = pd.date_range(start='12/25/2017',end='12/31/2017')
date13 = pd.date_range(start='2/17/2018',end='2/20/2018')
date14 = pd.date_range(start='3/31/2018', end='4/8/2018')
date15 = pd.date_range(start='10/6/2018', end='10/9/2018')
date16 = pd.date_range(start='11/21/2018', end='11/25/2018')
date17 = pd.date_range(start='12/24/2018',end='12/31/2018')
site15_hol = date1.union(date2).union(date3).union(date4).union(date5).union(date6).union(date7).union(date8).union(date9).union(date10).union(date11).union(date12).union(date13).union(date14).union(date15).union(date16).union(date17)
sids = dataframe.site_id == 15
dataframe.loc[(sids) & (dataframe.timestamp.isin((site15_hol))), 'is_holiday'] = 1
return dataframe
def reduce_mem_usage(df):
start_mem_usg = df.memory_usage().sum() / 1024**2
print("Memory usage of properties dataframe is :",start_mem_usg," MB")
NAlist = [] # Keeps track of columns that have missing values filled in.
for col in df.columns:
if df[col].dtype != object: # Exclude strings
# Print current column type
print("******************************")
print("Column: ",col)
print("dtype before: ",df[col].dtype)
# make variables for Int, max and min
IsInt = False
mx = df[col].max()
mn = df[col].min()
print("min for this col: ",mn)
print("max for this col: ",mx)
# Integer does not support NA, therefore, NA needs to be filled
if not np.isfinite(df[col]).all():
NAlist.append(col)
df[col].fillna(mn-1,inplace=True)
# test if column can be converted to an integer
asint = df[col].fillna(0).astype(np.int64)
result = (df[col] - asint)
result = result.sum()
if result > -0.01 and result < 0.01:
IsInt = True
# Make Integer/unsigned Integer datatypes
if IsInt:
if mn >= 0:
if mx < 255:
df[col] = df[col].astype(np.uint8)
elif mx < 65535:
df[col] = df[col].astype(np.uint16)
elif mx < 4294967295:
df[col] = df[col].astype(np.uint32)
else:
df[col] = df[col].astype(np.uint64)
else:
if mn > np.iinfo(np.int8).min and mx < np.iinfo(np.int8).max:
df[col] = df[col].astype(np.int8)
elif mn > np.iinfo(np.int16).min and mx < np.iinfo(np.int16).max:
df[col] = df[col].astype(np.int16)
elif mn > np.iinfo(np.int32).min and mx < np.iinfo(np.int32).max:
df[col] = df[col].astype(np.int32)
elif mn > np.iinfo(np.int64).min and mx < np.iinfo(np.int64).max:
df[col] = df[col].astype(np.int64)
# Make float datatypes 32 bit
else:
df[col] = df[col].astype(np.float32)
# Print new column type
print("dtype after: ",df[col].dtype)
print("******************************")
# Print final result
print("___MEMORY USAGE AFTER COMPLETION:___")
mem_usg = df.memory_usage().sum() / 1024**2
print("Memory usage is: ",mem_usg," MB")
print("This is ",100*mem_usg/start_mem_usg,"% of the initial size")
return df, NAlist
leak_df = pd.read_feather('leak.feather')
leak_df.fillna(0, inplace=True)
leak_df = leak_df[(leak_df.timestamp.dt.year > 2016) & (leak_df.timestamp.dt.year < 2019)]
leak_df.loc[leak_df.meter_reading < 0, 'meter_reading'] = 0 # remove large negative values
leak_df = leak_df[leak_df.building_id!=245]
leak_df['timestamp'] = leak_df['timestamp'].astype(str)
building_df = pd.read_csv("../building_metadata.csv")
train = pd.read_csv("../train.csv")
bad_rows = pd.read_csv('../rows_to_drop.csv')
train = train.drop(index=bad_rows['0'].values)
del bad_rows
train = pd.concat([train, leak_df]).reset_index(drop = True)
train = train.merge(building_df, left_on = "building_id", right_on = "building_id", how = "left")
train = train.merge(weather, left_on = ["site_id", "timestamp"], right_on = ["site_id", "timestamp"])
del weather, weather_train, weather_test, leak_df
train["timestamp"] = pd.to_datetime(train["timestamp"])
train["hour"] = train["timestamp"].dt.hour
train["weekday"] = train["timestamp"].dt.weekday
us_holidays = ["2016-01-01", "2016-01-18", "2016-02-15", "2016-05-30", "2016-07-04",
"2016-09-05", "2016-10-10", "2016-11-11", "2016-11-24", "2016-12-26",
"2017-01-02", "2017-01-16", "2017-02-20", "2017-05-29", "2017-07-04",
"2017-09-04", "2017-10-09", "2017-11-10", "2017-11-23", "2017-12-25",
"2018-01-01", "2018-01-15", "2018-02-19", "2018-05-28", "2018-07-04",
"2018-09-03", "2018-10-08", "2018-11-12", "2018-11-22", "2018-12-25",
"2019-01-01"]
uk_holidays = ["2016-01-01", "2016-01-02", "2016-03-25", "2016-03-28", "2016-05-02",
"2016-05-30", "2016-08-29", "2016-12-25", "2016-12-26", "2016-12-27",
"2017-01-01", "2017-01-02", "2017-04-14", "2017-04-17", "2017-05-01",
"2017-05-29", "2017-08-28", "2017-12-25", "2017-12-26",
"2018-01-01", "2018-01-02", "2018-03-30", "2018-04-02", "2018-05-07",
"2018-05-28", "2018-08-27", "2018-12-25", "2018-12-26",
"2019-01-01"]
ir_holidays = ["2016-01-01", "2016-01-02", "2016-03-17", "2016-03-28", "2016-05-02",
"2016-06-02", "2016-08-01", "2016-10-31", "2016-12-26", "2016-12-27",
"2017-01-01", "2017-01-02", "2017-03-17", "2017-04-14", "2017-05-01",
"2017-06-05", "2017-08-07", "2017-10-30", "2017-12-25", "2017-12-26",
"2018-01-01", "2018-01-02", "2018-03-19", "2018-04-02", "2018-05-07",
"2018-06-04", "2018-08-06", "2018-10-29", "2018-12-25", "2018-12-26",
"2019-01-01"]
def set_holiday(train):
train["is_holiday"] = 0
train.loc[train.weekday.isin([5,6]), 'is_holiday'] = 1
us_zone = [0,2,3,4,6,7,8,9,10,11,13,14,15]
for sid in us_zone:
sids = train.site_id == sid
train.loc[(sids) & (train.timestamp.isin(us_holidays)), 'is_holiday'] = 1
uk_zone = [1,5]
for sid in uk_zone:
sids = train.site_id == sid
train.loc[(sids) & (train.timestamp.isin(uk_holidays)), 'is_holiday'] = 1
sids = train.site_id == 12
train.loc[(sids) & (train.timestamp.isin(ir_holidays)), 'is_holiday'] = 1
return train
train = set_holiday(train)
train = set_holiday2(train)
train['month'] = train['timestamp'].dt.month
train['month'].replace((1, 2, 3, 12), 1, inplace = True)
train['month'].replace((6, 7, 8, 9), 2, inplace = True)
train['month'].replace((10, 11, 4, 5), 3, inplace = True)
del train["timestamp"]
### new features
train["puse_hour"] = train["primary_use"].astype(str) + '_' + train["hour"].astype(str)
train["holiday_hour"] = train["is_holiday"].astype(str) + '_' + train["hour"].astype(str)
def generate_categorical_encoders(df, features):
encoders = {}
for feature in features:
df[feature] = df[feature].fillna('missing')
encoder = LabelEncoder()
encoder.fit(df[feature].values)
le_dict = dict(zip(encoder.classes_, encoder.transform(encoder.classes_)))
encoders[feature] = le_dict
return encoders
def encode_categorical_features(df, features, encoders):
for f in features:
df[f] = df[f].fillna('missing')
df[f] = df[f].map(encoders[f])
encoded_features = ["primary_use","puse_hour","holiday_hour"]
encoders = generate_categorical_encoders(train, encoded_features)
encode_categorical_features(train, encoded_features, encoders)
target = np.log1p(train["meter_reading"])
del train["meter_reading"]
drop_cols = ["sea_level_pressure", "wind_speed", "wind_direction"]
train = train.drop(drop_cols, axis = 1)
categoricals = ["site_id","building_id","primary_use","hour", "weekday", "meter","puse_hour","holiday_hour"]
numericals = [i for i in train.columns if i not in categoricals]
feat_cols = categoricals + numericals
train, NAlist = reduce_mem_usage(train)
def get_model():
#Inputs
site_id = Input(shape=[1], name="site_id")
building_id = Input(shape=[1], name="building_id")
meter = Input(shape=[1], name="meter")
primary_use = Input(shape=[1], name="primary_use")
hour = Input(shape=[1], name="hour")
weekday = Input(shape=[1], name="weekday")
puse_hour = Input(shape=[1], name="puse_hour")
holiday_hour = Input(shape=[1], name="holiday_hour")
num_input = Input(shape=(len(numericals),), name="num_input")
#Embeddings layers
emb_site_id = Embedding(16, 6)(site_id)
emb_building_id = Embedding(1449, 128)(building_id)
emb_meter = Embedding(4, 2)(meter)
emb_primary_use = Embedding(16, 6)(primary_use)
emb_hour = Embedding(24, 8)(hour)
emb_weekday = Embedding(7, 2)(weekday)
emb_puse_hour = Embedding(384, 16)(puse_hour)
emb_holiday_hour = Embedding(48, 12)(holiday_hour)
categ = concatenate([Flatten() (emb_site_id), Flatten() (emb_building_id), Flatten() (emb_meter),
Flatten() (emb_primary_use), Flatten() (emb_hour), Flatten() (emb_weekday),
Flatten() (emb_puse_hour), Flatten() (emb_holiday_hour)])
### Categorical
n_unit = 128
decay_rate = 0.5
for k in range(3):
categ = Dense(n_unit)(categ)
categ = PReLU()(categ)
categ = BatchNormalization()(categ)
categ = Dropout(0.1)(categ)
n_unit = int(n_unit * decay_rate)
### Dense
numerical = Dense(64)(num_input)
numerical = PReLU()(numerical)
numerical = BatchNormalization()(numerical)
numerical = Dropout(0.1)(numerical)
numerical = Dense(64)(numerical)
numerical = PReLU()(numerical)
numerical = BatchNormalization()(numerical)
numerical = Dropout(0.1)(numerical)
numerical = Dense(32)(numerical)
numerical = PReLU()(numerical)
numerical = BatchNormalization()(numerical)
numerical = Dropout(0.1)(numerical)
#main layer
x = concatenate([categ, numerical])
n_unit = 128
decay_rate = 0.5
for k in range(4):
x = Dense(n_unit)(x)
x = PReLU()(x)
x = BatchNormalization()(x)
x = Dropout(0.1)(x)
n_unit = int(n_unit * decay_rate)
#output
output = Dense(1)(x)
model = Model([site_id,building_id,meter,primary_use,hour,weekday,puse_hour,holiday_hour,
num_input], output)
model.compile(optimizer = Adam(lr=0.001, decay = 0.0001),
loss= mse_loss,
metrics=[root_mean_squared_error])
return model
def root_mean_squared_error(y_true, y_pred):
return K.sqrt(K.mean(K.square(y_pred - y_true), axis=0))
def get_keras_data(df, num_cols, cat_cols):
X = {col: np.array(df[col]) for col in cat_cols}
X['num_input'] = df[num_cols].values
return X
def train_model(keras_model, X_t, y_train, batch_size, epochs, X_v, y_valid, fold, patience=5):
if not os.path.exists(directory):
os.makedirs(directory)
early_stopping = EarlyStopping(patience=patience, verbose=1)
model_checkpoint = ModelCheckpoint(directory+"model_" + str(fold) + ".hdf5",
save_best_only=True, verbose=1, monitor='val_root_mean_squared_error', mode='min')
hist = keras_model.fit(X_t, y_train, batch_size=batch_size, epochs=epochs,
validation_data=(X_v, y_valid), verbose=1,
callbacks=[early_stopping, model_checkpoint])
keras_model = load_model(directory+"model_" + str(fold) + ".hdf5", custom_objects={'root_mean_squared_error': root_mean_squared_error})
return keras_model
from sklearn.model_selection import KFold, StratifiedKFold
batch_size = 1024
epochs = 100
models = []
folds = 5
kf = KFold(n_splits=folds)
for fold_n, (train_index, valid_index) in enumerate(kf.split(train, train['month'])):
print('Fold:', fold_n)
X_train, X_valid = train.iloc[train_index], train.iloc[valid_index]
y_train, y_valid = target.iloc[train_index], target.iloc[valid_index]
X_t = get_keras_data(X_train, numericals, categoricals)
X_v = get_keras_data(X_valid, numericals, categoricals)
del X_train, X_valid
keras_model = get_model()
mod = train_model(keras_model, X_t, y_train, batch_size, epochs, X_v, y_valid, fold_n, patience=3)
models.append(mod)
print('*'* 50)
del mod, X_t, X_v
del train, target, y_train, y_valid, kf
gc.collect()
test = pd.read_csv("../test.csv")
test = test.merge(building_df, left_on = "building_id", right_on = "building_id", how = "left")
del building_df
weather_test = pd.read_csv("../weather_test.csv")
weather_test = fill_weather_dataset(weather_test)
weather_test = create_lag_features(weather_test, 6)
test = test.merge(weather_test, left_on = ["site_id", "timestamp"], right_on = ["site_id", "timestamp"], how = "left")
del weather_test
gc.collect()
test["timestamp"] = pd.to_datetime(test["timestamp"])
test["hour"] = test["timestamp"].dt.hour
test["weekday"] = test["timestamp"].dt.weekday
test['month'] = test['timestamp'].dt.month
test['month'].replace((1, 2, 3, 12), 1, inplace = True)
test['month'].replace((6, 7, 8, 9), 2, inplace = True)
test['month'].replace((10, 11, 4, 5), 3, inplace = True)
test = set_holiday(test)
test = set_holiday2(test)
test["puse_hour"] = test["primary_use"].astype(str) + '_' + test["hour"].astype(str)
test["holiday_hour"] = test["is_holiday"].astype(str) + '_' + test["hour"].astype(str)
encode_categorical_features(test, encoded_features, encoders)
test = test[feat_cols]
test, NAlist = reduce_mem_usage(test)
from tqdm import tqdm
i=0
res=[]
step_size = 50000
for j in tqdm(range(int(np.ceil(test.shape[0]/50000)))):
for_prediction = get_keras_data(test.iloc[i:i+step_size], numericals, categoricals)
res.append(np.expm1(sum([model.predict(for_prediction, batch_size=1024) for model in models])/folds))
i+=step_size
res = np.concatenate(res)
submission = pd.read_csv('../sample_submission.csv')
submission['meter_reading'] = res
submission.loc[submission['meter_reading']<0, 'meter_reading'] = 0
submission.to_csv(f'{filename}.csv', index=False)
submission
# def build_model():
# model_input = Input(shape=(6,))
# num_input = Lambda(lambda x: x[:, :5], output_shape=(5,))(model_input)
# cat_input = Lambda(lambda x: x[:, 5:], output_shape=(1,))(model_input)
# x = num_input
# x = Dense(256)(num_input)
# x = PReLU()(x)
# x = BatchNormalization()(x)
# x = Dropout(rate=0.5)(x)
# emb_dim = 128
# y = Embedding(200, emb_dim, input_length=1)(cat_input)
# y = Flatten()(y)
# z = Concatenate()([x, y])
# z = Dense(256)(z)
# z = PReLU()(z)
# z = BatchNormalization()(z)
# z = Dropout(rate=0.5)(z)
# z = Dense(256)(z)
# z = PReLU()(z)
# z = BatchNormalization()(z)
# z = Dropout(rate=0.5)(z)
# z = Dense(256)(z)
# z = PReLU()(z)
# z = BatchNormalization()(z)
# output = Dense(1, activation="sigmoid")(z)
# model = Model(inputs=model_input, outputs=output)
# return model
# def get_model_3():
# inp = keras.layers.Input((num_features*num_preds,))
# x = keras.layers.Reshape((num_features*num_preds,1))(inp)
# x = keras.layers.Conv1D(32,num_preds,strides=num_preds, activation='elu')(x)
# x = keras.layers.BatchNormalization()(x)
# x = keras.layers.Conv1D(24,1, activation='elu')(x)
# x = keras.layers.BatchNormalization()(x)
# x = keras.layers.Conv1D(16,1, activation='elu')(x)
# x = keras.layers.BatchNormalization()(x)
# x = keras.layers.Conv1D(4,1, activation='elu')(x)
# x = keras.layers.Flatten()(x)
# x = keras.layers.Reshape((num_features*4,1))(x)
# x = keras.layers.AveragePooling1D(2)(x)
# x = keras.layers.Flatten()(x)
# x = keras.layers.BatchNormalization()(x)
# out = keras.layers.Dense(1, activation='sigmoid')(x)
# return keras.Model(inputs=inp, outputs=out)
```
| github_jupyter |
```
import cv2
import os
import numpy as np
from PIL import Image, ImageEnhance, ImageDraw
import albumentations as A
def data_read(transform):
base_dir='data/'
dirs=['train', 'test', 'validation']
data_dir = 'augmentHori/'
if not os.path.exists(data_dir):
os.mkdir(data_dir)
count = 1
for sub in dirs:
curr_dir = base_dir+sub
for i, j, k in os.walk(curr_dir):
for name in k:
image = Image.open(i+'/'+name)
image = np.array(image)
transformed = transform(image=image)
transformed_img = transformed["image"]
if transformed_img.shape[0] > 0:
transformed_img = Image.fromarray(transformed_img)
if not os.path.exists(data_dir+i.split('/')[2]):
os.mkdir(data_dir+i.split('/')[2]+'/')
transformed_img.save(data_dir+i.split('/')[2]+'/'+str(count)+'.jpeg', 'JPEG')
count += 1
```
### Horizontal Flip
```
transform = A.Compose([A.HorizontalFlip(p=1.0)])
data_read(transform)
```
### Brightness
```
def data_read2(transform):
base_dir='data/'
dirs=['train', 'test', 'validation']
data_dir = 'augmentBri/'
if not os.path.exists(data_dir):
os.mkdir(data_dir)
count = 1
for sub in dirs:
curr_dir = base_dir+sub
for i, j, k in os.walk(curr_dir):
for name in k:
image = Image.open(i+'/'+name)
image = np.array(image)
transformed = transform(image=image)
transformed_img = transformed["image"]
if transformed_img.shape[0] > 0:
transformed_img = Image.fromarray(transformed_img)
if not os.path.exists(data_dir+i.split('/')[2]):
os.mkdir(data_dir+i.split('/')[2]+'/')
transformed_img.save(data_dir+i.split('/')[2]+'/'+str(count)+'.jpeg', 'JPEG')
count += 1
transform = A.Compose([A.RandomBrightnessContrast(p=1.0)])
data_read2(transform)
```
### Rotate Right by 30
```
def data_read3(transform):
base_dir='data/'
dirs=['train', 'test', 'validation']
data_dir = 'augment30RightRot/'
if not os.path.exists(data_dir):
os.mkdir(data_dir)
count = 1
for sub in dirs:
curr_dir = base_dir+sub
for i, j, k in os.walk(curr_dir):
for name in k:
image = Image.open(i+'/'+name)
image = np.array(image)
transformed = transform(image=image)
transformed_img = transformed["image"]
if transformed_img.shape[0] > 0:
transformed_img = Image.fromarray(transformed_img)
if not os.path.exists(data_dir+i.split('/')[2]):
os.mkdir(data_dir+i.split('/')[2]+'/')
transformed_img.save(data_dir+i.split('/')[2]+'/'+str(count)+'.jpeg', 'JPEG')
count += 1
transform = A.Compose([A.Rotate(limit=(30,30), p=1.0)])
data_read3(transform)
```
### Rotate Left by 30
```
def data_read4(transform):
base_dir='data/'
dirs=['train', 'test', 'validation']
data_dir = 'augment30LeftRot/'
if not os.path.exists(data_dir):
os.mkdir(data_dir)
count = 1
for sub in dirs:
curr_dir = base_dir+sub
for i, j, k in os.walk(curr_dir):
for name in k:
image = Image.open(i+'/'+name)
image = np.array(image)
transformed = transform(image=image)
transformed_img = transformed["image"]
if transformed_img.shape[0] > 0:
transformed_img = Image.fromarray(transformed_img)
if not os.path.exists(data_dir+i.split('/')[2]):
os.mkdir(data_dir+i.split('/')[2]+'/')
transformed_img.save(data_dir+i.split('/')[2]+'/'+str(count)+'.jpeg', 'JPEG')
count += 1
transform = A.Compose([A.Rotate(limit=(-30,-30), p=1.0)])
data_read4(transform)
```
### Rotate Right by 15
```
def data_read5(transform):
base_dir='data/'
dirs=['train', 'test', 'validation']
data_dir = 'augment15RightRot/'
if not os.path.exists(data_dir):
os.mkdir(data_dir)
count = 1
for sub in dirs:
curr_dir = base_dir+sub
for i, j, k in os.walk(curr_dir):
for name in k:
image = Image.open(i+'/'+name)
image = np.array(image)
transformed = transform(image=image)
transformed_img = transformed["image"]
if transformed_img.shape[0] > 0:
transformed_img = Image.fromarray(transformed_img)
if not os.path.exists(data_dir+i.split('/')[2]):
os.mkdir(data_dir+i.split('/')[2]+'/')
transformed_img.save(data_dir+i.split('/')[2]+'/'+str(count)+'.jpeg', 'JPEG')
count += 1
transform = A.Compose([A.Rotate(limit=(15, 15), p=1.0)])
data_read5(transform)
```
### Rotate Left by 15
```
def data_read6(transform):
base_dir='data/'
dirs=['train', 'test', 'validation']
data_dir = 'augment15LeftRot/'
if not os.path.exists(data_dir):
os.mkdir(data_dir)
count = 1
for sub in dirs:
curr_dir = base_dir+sub
for i, j, k in os.walk(curr_dir):
for name in k:
image = Image.open(i+'/'+name)
image = np.array(image)
transformed = transform(image=image)
transformed_img = transformed["image"]
if transformed_img.shape[0] > 0:
transformed_img = Image.fromarray(transformed_img)
if not os.path.exists(data_dir+i.split('/')[2]):
os.mkdir(data_dir+i.split('/')[2]+'/')
transformed_img.save(data_dir+i.split('/')[2]+'/'+str(count)+'.jpeg', 'JPEG')
count += 1
transform = A.Compose([A.Rotate(limit=(-15, -15), p=1.0)])
data_read6(transform)
```
### CLAHE
```
def data_read7(transform):
base_dir='data/'
dirs=['train', 'test', 'validation']
data_dir = 'augmentCLAHE/'
if not os.path.exists(data_dir):
os.mkdir(data_dir)
count = 1
for sub in dirs:
curr_dir = base_dir+sub
for i, j, k in os.walk(curr_dir):
for name in k:
image = Image.open(i+'/'+name)
image = np.array(image)
transformed = transform(image=image)
transformed_img = transformed["image"]
if transformed_img.shape[0] > 0:
transformed_img = Image.fromarray(transformed_img)
if not os.path.exists(data_dir+i.split('/')[2]):
os.mkdir(data_dir+i.split('/')[2]+'/')
transformed_img.save(data_dir+i.split('/')[2]+'/'+str(count)+'.jpeg', 'JPEG')
count += 1
transform = A.Compose([A.CLAHE(p=1.0)])
data_read7(transform)
```
### Channel Dropout
```
def data_read8(transform):
base_dir='data/'
dirs=['train', 'test', 'validation']
data_dir = 'augmentChanDrop/'
if not os.path.exists(data_dir):
os.mkdir(data_dir)
count = 1
for sub in dirs:
curr_dir = base_dir+sub
for i, j, k in os.walk(curr_dir):
for name in k:
image = Image.open(i+'/'+name)
image = np.array(image)
transformed = transform(image=image)
transformed_img = transformed["image"]
if transformed_img.shape[0] > 0:
transformed_img = Image.fromarray(transformed_img)
if not os.path.exists(data_dir+i.split('/')[2]):
os.mkdir(data_dir+i.split('/')[2]+'/')
transformed_img.save(data_dir+i.split('/')[2]+'/'+str(count)+'.jpeg', 'JPEG')
count += 1
transform = A.Compose([A.ChannelDropout(p=1.0)])
data_read8(transform)
```
### Channel Shuffle
```
def data_read9(transform):
base_dir='data/'
dirs=['train', 'test', 'validation']
data_dir = 'augmentChanShuff/'
if not os.path.exists(data_dir):
os.mkdir(data_dir)
count = 1
for sub in dirs:
curr_dir = base_dir+sub
for i, j, k in os.walk(curr_dir):
for name in k:
image = Image.open(i+'/'+name)
image = np.array(image)
transformed = transform(image=image)
transformed_img = transformed["image"]
if transformed_img.shape[0] > 0:
transformed_img = Image.fromarray(transformed_img)
if not os.path.exists(data_dir+i.split('/')[2]):
os.mkdir(data_dir+i.split('/')[2]+'/')
transformed_img.save(data_dir+i.split('/')[2]+'/'+str(count)+'.jpeg', 'JPEG')
count += 1
transform = A.Compose([A.ChannelShuffle(p=1.0)])
data_read9(transform)
```
### Coarse DropOut
```
def data_read10(transform):
base_dir='data/'
dirs=['train', 'test', 'validation']
data_dir = 'augmentCoarseDrop/'
if not os.path.exists(data_dir):
os.mkdir(data_dir)
count = 1
for sub in dirs:
curr_dir = base_dir+sub
for i, j, k in os.walk(curr_dir):
for name in k:
image = Image.open(i+'/'+name)
image = np.array(image)
transformed = transform(image=image)
transformed_img = transformed["image"]
if transformed_img.shape[0] > 0:
transformed_img = Image.fromarray(transformed_img)
if not os.path.exists(data_dir+i.split('/')[2]):
os.mkdir(data_dir+i.split('/')[2]+'/')
transformed_img.save(data_dir+i.split('/')[2]+'/'+str(count)+'.jpeg', 'JPEG')
count += 1
transform = A.Compose([A.CoarseDropout(p=1.0)])
data_read10(transform)
```
| github_jupyter |
## Training Notebook
This notebook is a tool to train the neural network for binary classification using the LFW Dataset.
```
# Import thrid party libraries
import numpy as np
from matplotlib import pyplot as plt
import tensorflow as tf
from tensorflow.keras.callbacks import LearningRateScheduler, EarlyStopping
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.optimizers import Adam
# Import utility libraries
from src.utils.triplet_generator import TripletGenerator
# Import the core library from Precencia
from src.core.face_encoder import FaceEncoder
triplet_generator = TripletGenerator()
face_encoder = FaceEncoder()
# Generate triplets pairs to ease the setting up the data for training
triplet_generator.lfw_dataset_source('\data\lfw')
(anchors, positives, negatives) = triplet_generator.create_triplets()
# Visualize Training Data Positive Pair and Negative Pair
from random import seed
from random import randint
target_shape = (160, 160)
def preprocess_image(filename):
image_string = tf.io.read_file(filename)
image = tf.image.decode_jpeg(image_string, channels=3)
image = tf.image.convert_image_dtype(image, tf.float32)
image = tf.image.resize(image, target_shape)
return image
def show(ax, image):
ax.imshow(preprocess_image(image))
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
fig = plt.figure(figsize=(4, 16))
axs = fig.subplots(8, 2)
seed(5)
for i in range(8):
value = randint(0, len(anchors))
show(axs[i, 0], anchors[value])
show(axs[i, 1], negatives[value])
plt.show()
print("Anchor: {}".format(np.shape(anchors)))
print("Positive: {}".format(np.shape(positives)))
print("Negative: {}".format(np.shape(negatives)))
# Feature extraction to get face embedding vectors, in (anchor, positive) and (anchor, negative) pair
pair_embeddings = []
y = []
length = len(anchors)
for idx in range(length):
anchor_embedding = face_encoder.get_embedding(image_path=anchors[idx])
positive_embedding = face_encoder.get_embedding(image_path=positives[idx])
negative_embedding = face_encoder.get_embedding(image_path=negatives[idx])
pair_embeddings.append((anchor_embedding, positive_embedding))
y.append(1)
pair_embeddings.append((anchor_embedding, negative_embedding))
y.append(0)
np.save('./data/encodings/lfw_face_embeddings.npy', pair_embeddings)
# Load face embedding pairs
pair_embeddings = np.load('./data/encodings/lfw_face_embeddings.npy')
X = []
y = []
length = len(anchors)
for _ in range(length):
y.append(1)
y.append(0)
for embedding in pair_embeddings:
X.append(np.array(embedding[0] - embedding[1]).reshape(-1))
X_train = np.array(X)
y_train = np.array(y).reshape(-1)
def classifier_scheduler(epoch, lr):
if (epoch % 5 == 0):
return lr * tf.math.exp(-0.1)
return lr
ClassifierLearningRateScheduler = LearningRateScheduler(classifier_scheduler, verbose=1)
ClassifierCustomEarlyStopping = EarlyStopping(monitor='loss', patience=3)
classifier = Sequential([
Input(shape=(128,)),
Dense(32, activation='relu'),
Dense(1, activation='sigmoid')
])
classifier.compile(loss='binary_crossentropy', optimizer=Adam(0.002), metrics=['accuracy'])
classifier_training_history = classifier.fit(X_train, y_train, validation_split=0.2, callbacks=[
ClassifierLearningRateScheduler, ClassifierCustomEarlyStopping], epochs=20, verbose=1)
print(classifier_training_history.history.keys())
plt.plot(classifier_training_history.history['accuracy'])
plt.plot(classifier_training_history.history['val_accuracy'])
plt.title('Model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
plt.plot(classifier_training_history.history['loss'])
plt.plot(classifier_training_history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
plt.plot(classifier_training_history.history['lr'])
plt.title('Learning rate')
plt.ylabel('learning rate')
plt.xlabel('epoch')
plt.legend(['lr'], loc='upper left')
plt.show()
classifier.summary()
classifier.save("./data/models/classifier_keras_weights.h5")
```
| github_jupyter |
<a href="https://colab.research.google.com/github/satyajitghana/TSAI-DeepNLP-END2.0/blob/main/08_TorchText/END2_0_Seq2Seq_1_Modern.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
%%bash
python -m spacy download en
python -m spacy download de
import spacy
# not using legacy stuff
# from torchtext.legacy.datasets import Multi30k
# from torchtext.legacy.data import Field, BucketIterator
!pip install torchtext
from torchtext.data.utils import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator
from torchtext.datasets import Multi30k
from typing import Iterable, List
SRC_LANGUAGE = 'de'
TGT_LANGUAGE = 'en'
# Place-holders
token_transform = {}
vocab_transform = {}
# Create source and target language tokenizer. Make sure to install the dependencies.
token_transform[SRC_LANGUAGE] = get_tokenizer('spacy', language='de')
token_transform[TGT_LANGUAGE] = get_tokenizer('spacy', language='en')
# helper function to yield list of tokens
def yield_tokens(data_iter: Iterable, language: str) -> List[str]:
language_index = {SRC_LANGUAGE: 0, TGT_LANGUAGE: 1}
for data_sample in data_iter:
yield token_transform[language](data_sample[language_index[language]])
# Define special symbols and indices
UNK_IDX, PAD_IDX, BOS_IDX, EOS_IDX = 0, 1, 2, 3
# Make sure the tokens are in order of their indices to properly insert them in vocab
special_symbols = ['<unk>', '<pad>', '<bos>', '<eos>']
for ln in [SRC_LANGUAGE, TGT_LANGUAGE]:
# Training data Iterator
train_iter = Multi30k(split='train', language_pair=(SRC_LANGUAGE, TGT_LANGUAGE))
# Create torchtext's Vocab object
vocab_transform[ln] = build_vocab_from_iterator(yield_tokens(train_iter, ln),
min_freq=1,
specials=special_symbols,
special_first=True)
# Set UNK_IDX as the default index. This index is returned when the token is not found.
# If not set, it throws RuntimeError when the queried token is not found in the Vocabulary.
for ln in [SRC_LANGUAGE, TGT_LANGUAGE]:
vocab_transform[ln].set_default_index(UNK_IDX)
import random
from typing import Tuple
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch import Tensor
class Encoder(nn.Module):
def __init__(self, input_dim, emb_dim, hid_dim, n_layers, dropout):
super().__init__()
self.hid_dim = hid_dim
self.n_layers = n_layers
self.embedding = nn.Embedding(input_dim, emb_dim)
self.rnn = nn.LSTM(emb_dim, hid_dim, n_layers, dropout = dropout)
self.dropout = nn.Dropout(dropout)
def forward(self, src):
#src = [src len, batch size]
embedded = self.dropout(self.embedding(src))
#embedded = [src len, batch size, emb dim]
outputs, (hidden, cell) = self.rnn(embedded)
#outputs = [src len, batch size, hid dim * n directions]
#hidden = [n layers * n directions, batch size, hid dim]
#cell = [n layers * n directions, batch size, hid dim]
#outputs are always from the top hidden layer
return hidden, cell
class Decoder(nn.Module):
def __init__(self, output_dim, emb_dim, hid_dim, n_layers, dropout):
super().__init__()
self.output_dim = output_dim
self.hid_dim = hid_dim
self.n_layers = n_layers
self.embedding = nn.Embedding(output_dim, emb_dim)
self.rnn = nn.LSTM(emb_dim, hid_dim, n_layers, dropout = dropout)
self.fc_out = nn.Linear(hid_dim, output_dim)
self.dropout = nn.Dropout(dropout)
def forward(self, input, hidden, cell):
#input = [batch size]
#hidden = [n layers * n directions, batch size, hid dim]
#cell = [n layers * n directions, batch size, hid dim]
#n directions in the decoder will both always be 1, therefore:
#hidden = [n layers, batch size, hid dim]
#context = [n layers, batch size, hid dim]
input = input.unsqueeze(0)
#input = [1, batch size]
embedded = self.dropout(self.embedding(input))
#embedded = [1, batch size, emb dim]
output, (hidden, cell) = self.rnn(embedded, (hidden, cell))
#output = [seq len, batch size, hid dim * n directions]
#hidden = [n layers * n directions, batch size, hid dim]
#cell = [n layers * n directions, batch size, hid dim]
#seq len and n directions will always be 1 in the decoder, therefore:
#output = [1, batch size, hid dim]
#hidden = [n layers, batch size, hid dim]
#cell = [n layers, batch size, hid dim]
prediction = self.fc_out(output.squeeze(0))
#prediction = [batch size, output dim]
return prediction, hidden, cell
class Seq2Seq(nn.Module):
def __init__(self, encoder, decoder, device):
super().__init__()
self.encoder = encoder
self.decoder = decoder
self.device = device
assert encoder.hid_dim == decoder.hid_dim, \
"Hidden dimensions of encoder and decoder must be equal!"
assert encoder.n_layers == decoder.n_layers, \
"Encoder and decoder must have equal number of layers!"
def forward(self, src, trg, teacher_forcing_ratio = 0.5):
#src = [src len, batch size]
#trg = [trg len, batch size]
#teacher_forcing_ratio is probability to use teacher forcing
#e.g. if teacher_forcing_ratio is 0.75 we use ground-truth inputs 75% of the time
batch_size = trg.shape[1]
trg_len = trg.shape[0]
trg_vocab_size = self.decoder.output_dim
#tensor to store decoder outputs
outputs = torch.zeros(trg_len, batch_size, trg_vocab_size).to(self.device)
#last hidden state of the encoder is used as the initial hidden state of the decoder
hidden, cell = self.encoder(src)
#first input to the decoder is the <sos> tokens
input = trg[0,:]
for t in range(1, trg_len):
#insert input token embedding, previous hidden and previous cell states
#receive output tensor (predictions) and new hidden and cell states
output, hidden, cell = self.decoder(input, hidden, cell)
#place predictions in a tensor holding predictions for each token
outputs[t] = output
#decide if we are going to use teacher forcing or not
teacher_force = random.random() < teacher_forcing_ratio
#get the highest predicted token from our predictions
top1 = output.argmax(1)
#if teacher forcing, use actual next token as next input
#if not, use predicted token
input = trg[t] if teacher_force else top1
return outputs
import torch
INPUT_DIM = len(vocab_transform[SRC_LANGUAGE])
OUTPUT_DIM = len(vocab_transform[TGT_LANGUAGE])
ENC_EMB_DIM = 32
DEC_EMB_DIM = 32
HID_DIM = 512
N_LAYERS = 2
ENC_DROPOUT = 0.5
DEC_DROPOUT = 0.5
BATCH_SIZE = 128
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
enc = Encoder(INPUT_DIM, ENC_EMB_DIM, HID_DIM, N_LAYERS, ENC_DROPOUT)
dec = Decoder(OUTPUT_DIM, DEC_EMB_DIM, HID_DIM, N_LAYERS, DEC_DROPOUT)
model = Seq2Seq(enc, dec, device).to(device)
def init_weights(m: nn.Module):
for name, param in m.named_parameters():
if 'weight' in name:
nn.init.normal_(param.data, mean=0, std=0.01)
else:
nn.init.constant_(param.data, 0)
model.apply(init_weights)
optimizer = optim.Adam(model.parameters())
def count_parameters(model: nn.Module):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f'The model has {count_parameters(model):,} trainable parameters')
loss_fn = torch.nn.CrossEntropyLoss(ignore_index=PAD_IDX)
optimizer = torch.optim.Adam(model.parameters(), lr=0.0001, betas=(0.9, 0.98), eps=1e-9)
######################################################################
# Collation
# ---------
#
# As seen in the ``Data Sourcing and Processing`` section, our data iterator yields a pair of raw strings.
# We need to convert these string pairs into the batched tensors that can be processed by our ``Seq2Seq`` network
# defined previously. Below we define our collate function that convert batch of raw strings into batch tensors that
# can be fed directly into our model.
#
from torch.nn.utils.rnn import pad_sequence
# helper function to club together sequential operations
def sequential_transforms(*transforms):
def func(txt_input):
for transform in transforms:
txt_input = transform(txt_input)
return txt_input
return func
# function to add BOS/EOS and create tensor for input sequence indices
def tensor_transform(token_ids: List[int]):
return torch.cat((torch.tensor([BOS_IDX]),
torch.tensor(token_ids),
torch.tensor([EOS_IDX])))
# src and tgt language text transforms to convert raw strings into tensors indices
text_transform = {}
for ln in [SRC_LANGUAGE, TGT_LANGUAGE]:
text_transform[ln] = sequential_transforms(token_transform[ln], #Tokenization
vocab_transform[ln], #Numericalization
tensor_transform) # Add BOS/EOS and create tensor
# function to collate data samples into batch tesors
def collate_fn(batch):
src_batch, tgt_batch = [], []
for src_sample, tgt_sample in batch:
src_batch.append(text_transform[SRC_LANGUAGE](src_sample.rstrip("\n")))
tgt_batch.append(text_transform[TGT_LANGUAGE](tgt_sample.rstrip("\n")))
src_batch = pad_sequence(src_batch, padding_value=PAD_IDX)
tgt_batch = pad_sequence(tgt_batch, padding_value=PAD_IDX)
return src_batch, tgt_batch
######################################################################
# Let's define training and evaluation loop that will be called for each
# epoch.
#
from torch.utils.data import DataLoader
def train_epoch(model, optimizer):
model.train()
losses = 0
train_iter = Multi30k(split='train', language_pair=(SRC_LANGUAGE, TGT_LANGUAGE))
train_dataloader = DataLoader(train_iter, batch_size=BATCH_SIZE, collate_fn=collate_fn)
for src, tgt in train_dataloader:
src = src.to(device)
tgt = tgt.to(device)
optimizer.zero_grad()
output = model(src, tgt)
output = output[1:].view(-1, output.shape[-1])
tgt = tgt[1:].view(-1)
loss = loss_fn(output, tgt)
loss.backward()
clip = 1
torch.nn.utils.clip_grad_norm_(model.parameters(), clip)
optimizer.step()
losses += loss.item()
return losses / len(train_dataloader)
def evaluate(model):
model.eval()
losses = 0
val_iter = Multi30k(split='valid', language_pair=(SRC_LANGUAGE, TGT_LANGUAGE))
val_dataloader = DataLoader(val_iter, batch_size=BATCH_SIZE, collate_fn=collate_fn)
for src, tgt in val_dataloader:
src = src.to(device)
tgt = tgt.to(device)
output = model(src, tgt)
output = output[1:].view(-1, output.shape[-1])
tgt = tgt[1:].view(-1)
loss = loss_fn(output, tgt)
losses += loss.item()
return losses / len(val_dataloader)
from timeit import default_timer as timer
NUM_EPOCHS = 18
for epoch in range(1, NUM_EPOCHS+1):
start_time = timer()
train_loss = train_epoch(model, optimizer)
end_time = timer()
val_loss = evaluate(model)
print((f"Epoch: {epoch}, Train loss: {train_loss:.3f}, Val loss: {val_loss:.3f}, "f"Epoch time = {(end_time - start_time):.3f}s"))
```
| github_jupyter |
# Demo of script to get specific subsequence from FASTA file
In order to demonstrate the use of my script `extract_subsequence_from_FASTA.py`, found [here](https://github.com/fomightez/sequencework/tree/master/Extract_from_FASTA), I'll use it to collect protein sequences from a collection of sequencs derived from PacBio sequenced yeast genomes from [Yue et al 2017](https://www.ncbi.nlm.nih.gov/pubmed/28416820).
Reference for sequence data:
[Contrasting evolutionary genome dynamics between domesticated and wild yeasts.
Yue JX, Li J, Aigrain L, Hallin J, Persson K, Oliver K, Bergström A, Coupland P, Warringer J, Lagomarsino MC, Fischer G, Durbin R, Liti G. Nat Genet. 2017 Jun;49(6):913-924. doi: 10.1038/ng.3847. Epub 2017 Apr 17. PMID: 28416820](https://www.ncbi.nlm.nih.gov/pubmed/28416820)
------
<div class="alert alert-block alert-warning">
<p>If you haven't used one of these notebooks before, they're basically web pages in which you can write, edit, and run live code. They're meant to encourage experimentation, so don't feel nervous. Just try running a few cells and see what happens!.</p>
<p>
Some tips:
<ul>
<li>Code cells have boxes around them. When you hover over them a <i class="fa-step-forward fa"></i> icon appears.</li>
<li>To run a code cell either click the <i class="fa-step-forward fa"></i> icon, or click on the cell and then hit <b>Shift+Enter</b>. The <b>Shift+Enter</b> combo will also move you to the next cell, so it's a quick way to work through the notebook.</li>
<li>While a cell is running a <b>*</b> appears in the square brackets next to the cell. Once the cell has finished running the asterisk will be replaced with a number.</li>
<li>In most cases you'll want to start from the top of notebook and work your way down running each cell in turn. Later cells might depend on the results of earlier ones.</li>
<li>To edit a code cell, just click on it and type stuff. Remember to run the cell once you've finished editing.</li>
</ul>
</p>
</div>
---
## Basic use
This script gets a sequence from a sequence file in FASTA format. It can be either a single sequence or more. You provide an indentifier to specify which sequence in the multiFASTA file to mine. In fact you always need to provide something for the indentifier parameter when calling this script or the main function of it, but that text can be nonseniscal if there is only one sequence in the sequence file. It disregards anything provided if there is only one.
The only other thing necessary is providing start and end positions to specify the subsequence. Positions are to be specified in typical position terms where the first residue is numbered one.
```
# Get the script
!curl -O https://raw.githubusercontent.com/fomightez/sequencework/master/Extract_from_FASTA/extract_subsequence_from_FASTA.py
#install a necessary dependency
!pip install pyfaidx
```
#### Display USAGE block
```
!python extract_subsequence_from_FASTA.py -h
```
Next, we'll get example data and extract a sequence.
```
# Get files of sequences
!curl -OL http://yjx1217.github.io/Yeast_PacBio_2016/data/Nuclear_Genome/SK1.genome.fa.gz
!gunzip SK1.genome.fa.gz
!curl -OL http://yjx1217.github.io/Yeast_PacBio_2016/data/Nuclear_CDS/SK1.cds.fa.gz
!gunzip SK1.cds.fa.gz
!curl -o S288C_YOR270C_VPH1_protein.fsa https://gist.githubusercontent.com/fomightez/f46b0624f1d8e3abb6ff908fc447e63b/raw/7ef7cfdaa2c9f9974f22fd60be3cfe7d1935cd86/ux_S288C_YOR270C_VPH1_protein.fsa
# Extract
!python extract_subsequence_from_FASTA.py SK1.genome.fa chrIII 101-200
```
The next cell shows it worked.
```
!head seq_extractedchrIII.fa
```
Sometimes the record identifier can be complex and it seems adding quotes around it can make it work when it won't work without it. The first cell below will fail to run. Just adding quotes allows it to work in the cell after that one.
```
!python extract_subsequence_from_FASTA.py SK1.cds.fa SK1_01G00030|SK1_01T00030.1|YHR213W 1-50
!python extract_subsequence_from_FASTA.py SK1.cds.fa "SK1_01G00030|SK1_01T00030.1|YHR213W" 1-50
!head "seq_extractedSK1_01G00030|SK1_01T00030.1|YHR213W.fa"
```
There is an optional flag `keep_description` that can be added to make the result keep the entire description line.
```
!python extract_subsequence_from_FASTA.py S288C_YOR270C_VPH1_protein.fsa VPH1 201-300 --keep_description
!head seq_extractedVPH1.fa
```
Note if it had been done without the flag, this sould have been the result.
```
!python extract_subsequence_from_FASTA.py S288C_YOR270C_VPH1_protein.fsa VPH1 201-300
!head seq_extractedVPH1.fa
```
The description line without the `-kd` flag ends at the point the first space occurs in the original description line of the single entry in `S288C_YOR270C_VPH1_protein.fsa`.
```
!head -n 1 S288C_YOR270C_VPH1_protein.fsa
```
Note that because `S288C_YOR270C_VPH1_protein.fsa` we can enter any arbitrary text for the record identifier argument as it is disregarded.
```
%run extract_subsequence_from_FASTA.py S288C_YOR270C_VPH1_protein.fsa SUPER_DUPER_NONSENSE 501-800
```
## Use script in a Jupyter notebook
This will demonstrate importing the main function into a notebook.
```
# Get the script if the above section wasn't run
import os
file_needed = "extract_subsequence_from_FASTA.py"
if not os.path.isfile(file_needed):
!curl -O https://raw.githubusercontent.com/fomightez/sequencework/master/Extract_from_FASTA/extract_subsequence_from_FASTA.py
```
Let's make the example `!python extract_subsequence_from_FASTA.py SK1.genome.fa chrIII 101-200` from above work here to get the result directly into the notebook environment as a python object.
First we need to import the main function from the script file.
```
from extract_subsequence_from_FASTA import extract_subsequence_from_FASTA
```
Now to try using that.
```
result = extract_subsequence_from_FASTA("SK1.genome.fa", "chrIII",region_str="101-200", return_record_as_string=True)
```
We now have that as `result` and we can use it for further steps. For example, we can use the produced Python string to parse it farther to get the last ten residues.
```
end_of_seq = result.split()[1][-10:]
end_of_seq
```
Note that the `keep_description` flag can also be used; it needs to be set to `True` when calling the main function.
```
fasta = extract_subsequence_from_FASTA("S288C_YOR270C_VPH1_protein.fsa", "blahBLAHblah",region_str="201-300", keep_description = True, return_record_as_string=True)
fasta
```
The next cell shows that result without the flag.
```
fasta = extract_subsequence_from_FASTA("S288C_YOR270C_VPH1_protein.fsa", "blahBLAHblah",region_str="201-300", return_record_as_string=True)
fasta
```
If you wanted to save the object from within the notebook, you can do that too.
```
%store end_of_seq > end.fa
```
Let's check that:
```
!head end.fa
```
Save your file to your local machine.
Enjoy!
| github_jupyter |
# About this kernel
+ resnext50_32x4d
+ CurricularFace
+ Mish() activation
+ Ranger (RAdam + Lookahead) optimizer
+ margin = 0.5
## Imports
```
import sys
sys.path.append('../input/shopee-competition-utils')
sys.path.insert(0,'../input/pytorch-image-models')
import numpy as np
import pandas as pd
import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader
import albumentations
from albumentations.pytorch.transforms import ToTensorV2
from custom_scheduler import ShopeeScheduler
from custom_activation import replace_activations, Mish
from custom_optimizer import Ranger
import math
import cv2
import timm
import os
import random
import gc
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import GroupKFold
from sklearn.neighbors import NearestNeighbors
from tqdm.notebook import tqdm
```
## Config
```
class CFG:
DATA_DIR = '../input/shopee-product-matching/train_images'
TRAIN_CSV = '../input/shopee-product-matching/train.csv'
# data augmentation
IMG_SIZE = 512
MEAN = [0.485, 0.456, 0.406]
STD = [0.229, 0.224, 0.225]
SEED = 2021
# data split
N_SPLITS = 5
TEST_FOLD = 0
VALID_FOLD = 1
EPOCHS = 8
BATCH_SIZE = 8
NUM_WORKERS = 4
DEVICE = 'cuda:2'
CLASSES = 6609
SCALE = 30
MARGIN = 0.5
MODEL_NAME = 'resnext50_32x4d'
MODEL_PATH = f'{MODEL_NAME}_curricular_face_epoch_{EPOCHS}_bs_{BATCH_SIZE}_margin_{MARGIN}.pt'
FC_DIM = 512
SCHEDULER_PARAMS = {
"lr_start": 1e-5,
"lr_max": 1e-5 * 32,
"lr_min": 1e-6,
"lr_ramp_ep": 5,
"lr_sus_ep": 0,
"lr_decay": 0.8,
}
```
## Augmentations
```
def get_train_transforms():
return albumentations.Compose(
[
albumentations.Resize(CFG.IMG_SIZE,CFG.IMG_SIZE,always_apply=True),
albumentations.HorizontalFlip(p=0.5),
albumentations.VerticalFlip(p=0.5),
albumentations.Rotate(limit=120, p=0.8),
albumentations.RandomBrightness(limit=(0.09, 0.6), p=0.5),
albumentations.Normalize(mean=CFG.MEAN, std=CFG.STD),
ToTensorV2(p=1.0),
]
)
def get_valid_transforms():
return albumentations.Compose(
[
albumentations.Resize(CFG.IMG_SIZE,CFG.IMG_SIZE,always_apply=True),
albumentations.Normalize(mean=CFG.MEAN, std=CFG.STD),
ToTensorV2(p=1.0)
]
)
def get_test_transforms():
return albumentations.Compose(
[
albumentations.Resize(CFG.IMG_SIZE,CFG.IMG_SIZE,always_apply=True),
albumentations.Normalize(mean=CFG.MEAN, std=CFG.STD),
ToTensorV2(p=1.0)
]
)
```
## Reproducibility
```
def seed_everything(seed):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = True # set True to be faster
seed_everything(CFG.SEED)
```
## Dataset
```
class ShopeeDataset(torch.utils.data.Dataset):
"""for training
"""
def __init__(self,df, transform = None):
self.df = df
self.root_dir = CFG.DATA_DIR
self.transform = transform
def __len__(self):
return len(self.df)
def __getitem__(self,idx):
row = self.df.iloc[idx]
img_path = os.path.join(self.root_dir,row.image)
image = cv2.imread(img_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
label = row.label_group
if self.transform:
augmented = self.transform(image=image)
image = augmented['image']
return {
'image' : image,
'label' : torch.tensor(label).long()
}
class ShopeeImageDataset(torch.utils.data.Dataset):
"""for validating and test
"""
def __init__(self,df, transform = None):
self.df = df
self.root_dir = CFG.DATA_DIR
self.transform = transform
def __len__(self):
return len(self.df)
def __getitem__(self,idx):
row = self.df.iloc[idx]
img_path = os.path.join(self.root_dir,row.image)
image = cv2.imread(img_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
label = row.label_group
if self.transform:
augmented = self.transform(image=image)
image = augmented['image']
return image,torch.tensor(1)
```
## Curricular Face + NFNet-L0
```
'''
credit : https://github.com/HuangYG123/CurricularFace/blob/8b2f47318117995aa05490c05b455b113489917e/head/metrics.py#L70
'''
def l2_norm(input, axis = 1):
norm = torch.norm(input, 2, axis, True)
output = torch.div(input, norm)
return output
class CurricularFace(nn.Module):
def __init__(self, in_features, out_features, s = 30, m = 0.50):
super(CurricularFace, self).__init__()
print('Using Curricular Face')
self.in_features = in_features
self.out_features = out_features
self.m = m
self.s = s
self.cos_m = math.cos(m)
self.sin_m = math.sin(m)
self.threshold = math.cos(math.pi - m)
self.mm = math.sin(math.pi - m) * m
self.kernel = nn.Parameter(torch.Tensor(in_features, out_features))
self.register_buffer('t', torch.zeros(1))
nn.init.normal_(self.kernel, std=0.01)
def forward(self, embbedings, label):
embbedings = l2_norm(embbedings, axis = 1)
kernel_norm = l2_norm(self.kernel, axis = 0)
cos_theta = torch.mm(embbedings, kernel_norm)
cos_theta = cos_theta.clamp(-1, 1) # for numerical stability
with torch.no_grad():
origin_cos = cos_theta.clone()
target_logit = cos_theta[torch.arange(0, embbedings.size(0)), label].view(-1, 1)
sin_theta = torch.sqrt(1.0 - torch.pow(target_logit, 2))
cos_theta_m = target_logit * self.cos_m - sin_theta * self.sin_m #cos(target+margin)
mask = cos_theta > cos_theta_m
final_target_logit = torch.where(target_logit > self.threshold, cos_theta_m, target_logit - self.mm)
hard_example = cos_theta[mask]
with torch.no_grad():
self.t = target_logit.mean() * 0.01 + (1 - 0.01) * self.t
cos_theta[mask] = hard_example * (self.t + hard_example)
cos_theta.scatter_(1, label.view(-1, 1).long(), final_target_logit)
output = cos_theta * self.s
return output, nn.CrossEntropyLoss()(output,label)
class ShopeeModel(nn.Module):
def __init__(
self,
n_classes = CFG.CLASSES,
model_name = CFG.MODEL_NAME,
fc_dim = CFG.FC_DIM,
margin = CFG.MARGIN,
scale = CFG.SCALE,
use_fc = True,
pretrained = True):
super(ShopeeModel,self).__init__()
print('Building Model Backbone for {} model'.format(model_name))
self.backbone = timm.create_model(model_name, pretrained=pretrained)
if 'efficientnet' in model_name:
final_in_features = self.backbone.classifier.in_features
self.backbone.classifier = nn.Identity()
self.backbone.global_pool = nn.Identity()
elif 'resnet' in model_name:
final_in_features = self.backbone.fc.in_features
self.backbone.fc = nn.Identity()
self.backbone.global_pool = nn.Identity()
elif 'resnext' in model_name:
final_in_features = self.backbone.fc.in_features
self.backbone.fc = nn.Identity()
self.backbone.global_pool = nn.Identity()
elif 'nfnet' in model_name:
final_in_features = self.backbone.head.fc.in_features
self.backbone.head.fc = nn.Identity()
self.backbone.head.global_pool = nn.Identity()
self.pooling = nn.AdaptiveAvgPool2d(1)
self.use_fc = use_fc
if use_fc:
self.dropout = nn.Dropout(p=0.0)
self.fc = nn.Linear(final_in_features, fc_dim)
self.bn = nn.BatchNorm1d(fc_dim)
self._init_params()
final_in_features = fc_dim
self.final = CurricularFace(final_in_features,
n_classes,
s=scale,
m=margin)
def _init_params(self):
nn.init.xavier_normal_(self.fc.weight)
nn.init.constant_(self.fc.bias, 0)
nn.init.constant_(self.bn.weight, 1)
nn.init.constant_(self.bn.bias, 0)
def forward(self, image, label):
feature = self.extract_feat(image)
logits = self.final(feature,label)
return logits
def extract_feat(self, x):
batch_size = x.shape[0]
x = self.backbone(x)
x = self.pooling(x).view(batch_size, -1)
if self.use_fc:
x = self.dropout(x)
x = self.fc(x)
x = self.bn(x)
return x
```
## Engine
```
def train_fn(model, data_loader, optimizer, scheduler, i):
model.train()
fin_loss = 0.0
tk = tqdm(data_loader, desc = "Epoch" + " [TRAIN] " + str(i+1))
for t,data in enumerate(tk):
for k,v in data.items():
data[k] = v.to(CFG.DEVICE)
optimizer.zero_grad()
_, loss = model(**data)
loss.backward()
optimizer.step()
fin_loss += loss.item()
tk.set_postfix({'loss' : '%.6f' %float(fin_loss/(t+1)), 'LR' : optimizer.param_groups[0]['lr']})
scheduler.step()
return fin_loss / len(data_loader)
def eval_fn(model, data_loader, i):
model.eval()
fin_loss = 0.0
tk = tqdm(data_loader, desc = "Epoch" + " [VALID] " + str(i+1))
with torch.no_grad():
for t,data in enumerate(tk):
for k,v in data.items():
data[k] = v.to(CFG.DEVICE)
_, loss = model(**data)
fin_loss += loss.item()
tk.set_postfix({'loss' : '%.6f' %float(fin_loss/(t+1))})
return fin_loss / len(data_loader)
def read_dataset():
df = pd.read_csv(CFG.TRAIN_CSV)
df['matches'] = df.label_group.map(df.groupby('label_group').posting_id.agg('unique').to_dict())
df['matches'] = df['matches'].apply(lambda x: ' '.join(x))
gkf = GroupKFold(n_splits=CFG.N_SPLITS)
df['fold'] = -1
for i, (train_idx, valid_idx) in enumerate(gkf.split(X=df, groups=df['label_group'])):
df.loc[valid_idx, 'fold'] = i
labelencoder= LabelEncoder()
df['label_group'] = labelencoder.fit_transform(df['label_group'])
train_df = df[df['fold']!=CFG.TEST_FOLD].reset_index(drop=True)
train_df = train_df[train_df['fold']!=CFG.VALID_FOLD].reset_index(drop=True)
valid_df = df[df['fold']==CFG.VALID_FOLD].reset_index(drop=True)
test_df = df[df['fold']==CFG.TEST_FOLD].reset_index(drop=True)
train_df['label_group'] = labelencoder.fit_transform(train_df['label_group'])
return train_df, valid_df, test_df
def precision_score(y_true, y_pred):
y_true = y_true.apply(lambda x: set(x.split()))
y_pred = y_pred.apply(lambda x: set(x.split()))
intersection = np.array([len(x[0] & x[1]) for x in zip(y_true, y_pred)])
len_y_pred = y_pred.apply(lambda x: len(x)).values
precision = intersection / len_y_pred
return precision
def recall_score(y_true, y_pred):
y_true = y_true.apply(lambda x: set(x.split()))
y_pred = y_pred.apply(lambda x: set(x.split()))
intersection = np.array([len(x[0] & x[1]) for x in zip(y_true, y_pred)])
len_y_true = y_true.apply(lambda x: len(x)).values
recall = intersection / len_y_true
return recall
def f1_score(y_true, y_pred):
y_true = y_true.apply(lambda x: set(x.split()))
y_pred = y_pred.apply(lambda x: set(x.split()))
intersection = np.array([len(x[0] & x[1]) for x in zip(y_true, y_pred)])
len_y_pred = y_pred.apply(lambda x: len(x)).values
len_y_true = y_true.apply(lambda x: len(x)).values
f1 = 2 * intersection / (len_y_pred + len_y_true)
return f1
def get_valid_embeddings(df, model):
model.eval()
image_dataset = ShopeeImageDataset(df,transform=get_valid_transforms())
image_loader = torch.utils.data.DataLoader(
image_dataset,
batch_size=CFG.BATCH_SIZE,
pin_memory=True,
num_workers = CFG.NUM_WORKERS,
drop_last=False
)
embeds = []
with torch.no_grad():
for img,label in tqdm(image_loader):
img = img.to(CFG.DEVICE)
label = label.to(CFG.DEVICE)
feat,_ = model(img,label)
image_embeddings = feat.detach().cpu().numpy()
embeds.append(image_embeddings)
del model
image_embeddings = np.concatenate(embeds)
print(f'Our image embeddings shape is {image_embeddings.shape}')
del embeds
gc.collect()
return image_embeddings
def get_neighbors(df, embeddings, KNN = 50, image = True):
'''
https://www.kaggle.com/ragnar123/unsupervised-baseline-arcface?scriptVersionId=57121538
'''
model = NearestNeighbors(n_neighbors = KNN, metric = 'cosine')
model.fit(embeddings)
distances, indices = model.kneighbors(embeddings)
# Iterate through different thresholds to maximize cv, run this in interactive mode, then replace else clause with a solid threshold
if image:
thresholds = list(np.arange(0.2,0.4,0.01))
else:
thresholds = list(np.arange(0.1, 1, 0.1))
scores_f1 = []
scores_recall = []
scores_precision = []
for threshold in thresholds:
predictions = []
for k in range(embeddings.shape[0]):
idx = np.where(distances[k,] < threshold)[0]
ids = indices[k,idx]
posting_ids = ' '.join(df['posting_id'].iloc[ids].values)
predictions.append(posting_ids)
df['pred_matches'] = predictions
df['f1'] = f1_score(df['matches'], df['pred_matches'])
df['recall'] = recall_score(df['matches'], df['pred_matches'])
df['precision'] = precision_score(df['matches'], df['pred_matches'])
score_f1 = df['f1'].mean()
score_recall = df['recall'].mean()
score_precision = df['precision'].mean()
print(f'Our f1 score for threshold {threshold} is {score_f1}, recall score is {score_recall}, mAP score is {score_precision}')
scores_f1.append(score_f1)
scores_recall.append(score_recall)
scores_precision.append(score_precision)
# create a dataframe to store threshold and scores
thresholds_scores = pd.DataFrame({'thresholds': thresholds, 'scores_f1': scores_f1, 'scores_recall': scores_recall, 'scores_precision': scores_precision})
# obtain best f1 score
max_score = thresholds_scores[thresholds_scores['scores_f1'] == thresholds_scores['scores_f1'].max()]
# obtain best threshold and scores
best_threshold = max_score['thresholds'].values[0]
best_score_f1 = max_score['scores_f1'].values[0]
best_score_recall = max_score['scores_recall'].values[0]
best_score_precision = max_score['scores_precision'].values[0]
print(f'Our best f1 score is {best_score_f1} and has a threshold {best_threshold}, corresponding recall score is {best_score_recall}, mAP score is {best_score_precision}')
# Use threshold
predictions = []
for k in range(embeddings.shape[0]):
# Because we are predicting the test set that have 70K images and different label groups, confidence should be smaller
if image:
idx = np.where(distances[k,] < best_threshold)[0]
else:
idx = np.where(distances[k,] < best_threshold)[0]
ids = indices[k,idx]
posting_ids = ' '.join(df['posting_id'].iloc[ids].values)
predictions.append(posting_ids)
df['pred_matches'] = predictions
df['f1'] = f1_score(df['matches'], df['pred_matches'])
df['recall'] = recall_score(df['matches'], df['pred_matches'])
df['precision'] = precision_score(df['matches'], df['pred_matches'])
del model, distances, indices
gc.collect()
return df, predictions
def get_valid_neighbors(df, embeddings, KNN = 50, threshold = 0.36):
model = NearestNeighbors(n_neighbors = KNN, metric = 'cosine')
model.fit(embeddings)
distances, indices = model.kneighbors(embeddings)
predictions = []
for k in range(embeddings.shape[0]):
idx = np.where(distances[k,] < threshold)[0]
ids = indices[k,idx]
posting_ids = ' '.join(df['posting_id'].iloc[ids].values)
predictions.append(posting_ids)
df['pred_matches'] = predictions
df['f1'] = f1_score(df['matches'], df['pred_matches'])
df['recall'] = recall_score(df['matches'], df['pred_matches'])
df['precision'] = precision_score(df['matches'], df['pred_matches'])
del model, distances, indices
gc.collect()
return df, predictions
```
# Training
```
def run_training():
train_df, valid_df, test_df = read_dataset()
train_dataset = ShopeeDataset(train_df, transform = get_train_transforms())
train_dataloader = torch.utils.data.DataLoader(
train_dataset,
batch_size = CFG.BATCH_SIZE,
pin_memory = True,
num_workers = CFG.NUM_WORKERS,
shuffle = True,
drop_last = True
)
print(train_df['label_group'].nunique())
model = ShopeeModel()
model = replace_activations(model, torch.nn.SiLU, Mish())
model.to(CFG.DEVICE)
optimizer = Ranger(model.parameters(), lr = CFG.SCHEDULER_PARAMS['lr_start'])
#optimizer = torch.optim.Adam(model.parameters(), lr = config.SCHEDULER_PARAMS['lr_start'])
scheduler = ShopeeScheduler(optimizer,**CFG.SCHEDULER_PARAMS)
best_valid_f1 = 0.
for i in range(CFG.EPOCHS):
avg_loss_train = train_fn(model, train_dataloader, optimizer, scheduler, i)
valid_embeddings = get_valid_embeddings(valid_df, model)
valid_df, valid_predictions = get_valid_neighbors(valid_df, valid_embeddings)
valid_f1 = valid_df.f1.mean()
valid_recall = valid_df.recall.mean()
valid_precision = valid_df.precision.mean()
print(f'Valid f1 score = {valid_f1}, recall = {valid_recall}, precision = {valid_precision}')
if valid_f1 > best_valid_f1:
best_valid_f1 = valid_f1
print('Valid f1 score improved, model saved')
torch.save(model.state_dict(),CFG.MODEL_PATH)
run_training()
def get_test_embeddings(test_df):
model = ShopeeModel()
model.eval()
model = replace_activations(model, torch.nn.SiLU, Mish())
model.load_state_dict(torch.load(CFG.MODEL_PATH))
model = model.to(CFG.DEVICE)
image_dataset = ShopeeImageDataset(test_df,transform=get_test_transforms())
image_loader = torch.utils.data.DataLoader(
image_dataset,
batch_size=CFG.BATCH_SIZE,
pin_memory=True,
num_workers = CFG.NUM_WORKERS,
drop_last=False
)
embeds = []
with torch.no_grad():
for img,label in tqdm(image_loader):
img = img.cuda()
label = label.cuda()
feat,_ = model(img,label)
image_embeddings = feat.detach().cpu().numpy()
embeds.append(image_embeddings)
del model
image_embeddings = np.concatenate(embeds)
print(f'Our image embeddings shape is {image_embeddings.shape}')
del embeds
gc.collect()
return image_embeddings
```
## Best threshold Search
```
train_df, valid_df, test_df = read_dataset()
print("Searching best threshold...")
search_space = np.arange(10, 50, 1)
model = ShopeeModel()
model.eval()
model = replace_activations(model, torch.nn.SiLU, Mish())
model.load_state_dict(torch.load(CFG.MODEL_PATH))
model = model.to(CFG.DEVICE)
valid_embeddings = get_valid_embeddings(valid_df, model)
best_f1_valid = 0.
best_threshold = 0.
for i in search_space:
threshold = i / 100
valid_df, valid_predictions = get_valid_neighbors(valid_df, valid_embeddings, threshold=threshold)
valid_f1 = valid_df.f1.mean()
valid_recall = valid_df.recall.mean()
valid_precision = valid_df.precision.mean()
print(f"threshold = {threshold} -> f1 score = {valid_f1}, recall = {valid_recall}, precision = {valid_precision}")
if (valid_f1 > best_f1_valid):
best_f1_valid = valid_f1
best_threshold = threshold
print("Best threshold =", best_threshold)
print("Best f1 score =", best_f1_valid)
BEST_THRESHOLD = best_threshold
print("Searching best knn...")
search_space = np.arange(40, 80, 2)
best_f1_valid = 0.
best_knn = 0
for knn in search_space:
valid_df, valid_predictions = get_valid_neighbors(valid_df, valid_embeddings, KNN=knn, threshold=BEST_THRESHOLD)
valid_f1 = valid_df.f1.mean()
valid_recall = valid_df.recall.mean()
valid_precision = valid_df.precision.mean()
print(f"knn = {knn} -> f1 score = {valid_f1}, recall = {valid_recall}, precision = {valid_precision}")
if (valid_f1 > best_f1_valid):
best_f1_valid = valid_f1
best_knn = knn
print("Best knn =", best_knn)
print("Best f1 score =", best_f1_valid)
BEST_KNN = best_knn
test_embeddings = get_valid_embeddings(test_df,model)
test_df, test_predictions = get_valid_neighbors(test_df, test_embeddings, KNN = BEST_KNN, threshold = BEST_THRESHOLD)
test_f1 = test_df.f1.mean()
test_recall = test_df.recall.mean()
test_precision = test_df.precision.mean()
print(f'Test f1 score = {test_f1}, recall = {test_recall}, precision = {test_precision}')
```
| github_jupyter |

[](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/jupyter/training/english/dl-ner/ner_albert.ipynb)
## 0. Colab Setup
```
import os
# Install java
! apt-get install -y openjdk-8-jdk-headless -qq > /dev/null
os.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64"
os.environ["PATH"] = os.environ["JAVA_HOME"] + "/bin:" + os.environ["PATH"]
! java -version
# Install pyspark
! pip install --ignore-installed -q pyspark==2.4.4
# Install Spark NLP
! pip install --ignore-installed -q spark-nlp==2.5
```
# How to train a NER classifier with Albert embeddings based on Char CNNs - BiLSTM - CRF
## Download the file into the local File System
### It is a standard conll2003 format training file
```
# Download CoNLL 2003 Dataset
import os
from pathlib import Path
import urllib.request
download_path = "./eng.train"
if not Path(download_path).is_file():
print("File Not found will downloading it!")
url = "https://github.com/patverga/torch-ner-nlp-from-scratch/raw/master/data/conll2003/eng.train"
urllib.request.urlretrieve(url, download_path)
else:
printalbert("File already present.")
```
# Read CoNLL Dataset into Spark dataframe and automagically generate features for futures tasks
The readDataset method of the CoNLL class handily adds all the features required in the next steps
```
import sparknlp
from sparknlp.training import CoNLL
spark = sparknlp.start()
training_data = CoNLL().readDataset(spark, './eng.train')
training_data.show()
```
# Define the NER Pipeline
### This pipeline defines a pretrained Albert component and a trainable NerDLApproach which is based on the Char CNN - BiLSTM - CRF
Usually you have to add additional pipeline components before the Albert for the document, sentence and token columns. But Spark NLPs CoNLL class took already care of this for us, awesome!
```
from pyspark.ml import Pipeline
from sparknlp.annotator import *
from sparknlp.common import *
from sparknlp.base import *
# Define the pretrained Albert model.
albert = AlbertEmbeddings.pretrained().setInputCols("sentence", "token")\
.setOutputCol("albert")\
# Define the Char CNN - BiLSTM - CRF model. We will feed it the Albert tokens
nerTagger = NerDLApproach()\
.setInputCols(["sentence", "token", "albert"])\
.setLabelColumn("label")\
.setOutputCol("ner")\
.setMaxEpochs(1)\
.setRandomSeed(0)\
.setVerbose(0)
# put everything into the pipe
pipeline = Pipeline(
stages = [
albert ,
nerTagger
])
```
# Fit the Pipeline and get results
```
ner_df = pipeline.fit(training_data.limit(10)).transform(training_data.limit(50))
ner_df.show()
```
### Checkout only result columns
```
ner_df.select(*['text', 'ner']).limit(1).show(truncate=False)
```
## Alternative Albert models
checkout https://github.com/JohnSnowLabs/spark-nlp-models for alternative models, the following are available :
* albert_base_uncased = https://tfhub.dev/google/albert_base/3 | 768-embed-dim, 12-layer, 12-heads, 12M parameters
* albert_large_uncased = https://tfhub.dev/google/albert_large/3 | 1024-embed-dim, 24-layer, 16-heads, 18M parameters
* albert_xlarge_uncased = https://tfhub.dev/google/albert_xlarge/3 | 2048-embed-dim, 24-layer, 32-heads, 60M parameters
* albert_xxlarge_uncased = https://tfhub.dev/google/albert_xxlarge/3 | 4096-embed-dim, 12-layer, 64-heads, 235M parameters
```
from pyspark.ml import Pipeline
from sparknlp.annotator import *
from sparknlp.common import *
from sparknlp.base import *
# Define the pretrained Albert model.
abert_variant = 'albert_xxlarge_uncased'
albert = AlbertEmbeddings.pretrained(abert_variant ).setInputCols("sentence", "token")\
.setOutputCol("albert")\
# Define the Char CNN - BiLSTM - CRF model. We will feed it the Albert tokens
nerTagger = NerDLApproach()\
.setInputCols(["sentence", "token", "albert"])\
.setLabelColumn("label")\
.setOutputCol("ner")\
.setMaxEpochs(1)\
.setRandomSeed(0)\
.setVerbose(0)
# put everything into the pipe
pipeline = Pipeline(
stages = [
albert ,
nerTagger
])
ner_df = pipeline.fit(training_data.limit(10)).transform(training_data.limit(50))
ner_df.show()
ner_df.select(*['text', 'ner']).limit(1).show(truncate=False)
```
| github_jupyter |
# XGBOOST BASELINE for Semeval - Laptops 2016
```
from google.colab import drive
drive.mount('/content/drive/', force_remount=True)
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from xgboost import XGBClassifier
from sklearn.multiclass import OneVsRestClassifier
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.metrics import multilabel_confusion_matrix, classification_report
```
## Preprocessing
Function to add [CLS] and [SEP] as separator tokens at beginning/ending of each text item and to format aspect and polarity columns as lists:
```
def changeFormat(dataset):
df = pd.DataFrame(dataset)
text = df['text']
aspect = df['aspect']
polarity = df['polarity']
df2 = pd.DataFrame({'text': '[CLS] ' + text + ' [SEP]',
'aspect': aspect,
'polarity': polarity})
df2['polarity'] = [x.split(',') for x in df2['polarity']]
df2['aspect'] = [x.split(',') for x in df2['aspect']]
return df2
```
Read csv files from Google Drive (directly from shared group drive "NLP Lab"):
```
L16_train = pd.read_csv("/content/drive/My Drive/NLP Lab/Colab Notebooks/semeval/DataPreprocessing/stratified/semevalLaptops_combi16_train_stratify.csv")
```
Overwrite "text" column by applying "appSep" function:
```
L16_train = changeFormat(L16_train)
L16_train.head()
L16_test = pd.read_csv("/content/drive/My Drive/NLP Lab/Colab Notebooks/semeval/DataPreprocessing/stratified/semevalLaptops_combi16_test_stratify.csv")
L16_test = changeFormat(L16_test)
L16_test.head()
```
Shape of the train and test data:
```
L16_train.shape
L16_test.shape
```
##**BERT embeddings**
Preprocessing to import BERT embeddings file of group in Colab
```
!pip install pytorch-pretrained-bert
!pwd
%cd "/content/drive/My Drive/NLP Lab/Colab Notebooks/semeval/baseline"
!ls
from embeddings import Embeddings
embed = Embeddings()
```
Get BERT embeddings for train and test data:
```
L16_train_embeddings = embed.get_embeddings(L16_train.text, all=False)
L16_test_embeddings = embed.get_embeddings(L16_test.text, all=False)
```
Plausibility check
```
# number of vectors
len(L16_train_embeddings[0])
#string is counted letter per letter
len(L16_train['text'][0])
# original text
L16_train['text'][0]
# vectors
L16_train_embeddings[0]
len(L16_test_embeddings[0])
L16_test['text'][0]
L16_train['embeddings'] = [e[0].numpy() for e in L16_train_embeddings]
L16_test['embeddings'] = [e[0].numpy() for e in L16_test_embeddings]
```
##**XGBOOST Baseline Model for Aspect**
```
L16_aspect = MultiLabelBinarizer()
L16_aspect.fit(L16_train.aspect)
L16_aspect.classes_
y_L16_train_aspect = L16_aspect.transform(L16_train.aspect)
y_L16_test_aspect = L16_aspect.transform(L16_test.aspect)
y_L16_train_aspect[3]
L16_xgb_aspect = OneVsRestClassifier(XGBClassifier(objective='binary:logistic', n_estimators=500 , max_depth=3,
learning_rate=0.05, n_jobs=24, verbosity=1,
min_child_weight=20, scale_pos_weight=6, base_score=0.2))
L16_xgb_aspect.fit(np.array(list(L16_train.embeddings)), y_L16_train_aspect)
L16_aspect_report = classification_report(y_L16_test_aspect, L16_xgb_aspect.predict(np.array(list(L16_test.embeddings))),
target_names=L16_aspect.classes_, output_dict=True)
L16_f1s_aspect = []
for key in L16_aspect_report.keys():
L16_f1s_aspect.append(L16_aspect_report.get(key).get('f1-score'))
sns.set_style("whitegrid")
sns.set(rc={'figure.figsize':(20,8)})
sns.barplot(list(L16_aspect_report.keys())[:-2], L16_f1s_aspect[:-2], palette='deep')
plt.xticks(rotation=90)
plt.xlabel('Class')
plt.ylabel('F1-Score')
plt.title('Multi-label aspect classification performance')
```
##**XGBOOST Baseline Model for Polarity**
```
L16_polarity = MultiLabelBinarizer()
L16_polarity.fit(L16_train.polarity)
L16_polarity.classes_
y_L16_train_polarity = L16_polarity.transform(L16_train.polarity)
y_L16_test_polarity = L16_polarity.transform(L16_test.polarity)
y_L16_train_polarity[3]
L16_xgb_polarity = OneVsRestClassifier(XGBClassifier(objective='binary:logistic', n_estimators=500 , max_depth=3,
learning_rate=0.05, n_jobs=24, verbosity=1, min_child_weight=50,
scale_pos_weight=6, base_score=0.3))
L16_xgb_polarity.fit(np.array(list(L16_train.embeddings)), y_L16_train_polarity)
L16_polarity_report = classification_report(y_L16_test_polarity, L16_xgb_polarity.predict(np.array(list(L16_test.embeddings))),
target_names=L16_polarity.classes_, output_dict=True)
L16_f1s_polarity = []
for key in L16_polarity_report.keys():
L16_f1s_polarity.append(L16_polarity_report.get(key).get('f1-score'))
sns.set_style("whitegrid")
sns.set(rc={'figure.figsize':(12,8)})
sns.barplot(list(L16_polarity_report.keys())[:-2], L16_f1s_polarity[:-2], palette='deep')
plt.xticks(rotation=90)
plt.xlabel('Class')
plt.ylabel('F1-Score')
plt.title('Multi-label polarity classification performance')
```
| github_jupyter |
<table class="ee-notebook-buttons" align="left">
<td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/ImageCollection/linear_fit.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td>
<td><a target="_blank" href="https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/ImageCollection/linear_fit.ipynb"><img width=26px src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png" />Notebook Viewer</a></td>
<td><a target="_blank" href="https://mybinder.org/v2/gh/giswqs/earthengine-py-notebooks/master?filepath=ImageCollection/linear_fit.ipynb"><img width=58px src="https://mybinder.org/static/images/logo_social.png" />Run in binder</a></td>
<td><a target="_blank" href="https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/ImageCollection/linear_fit.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a></td>
</table>
## Install Earth Engine API
Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geehydro](https://github.com/giswqs/geehydro). The **geehydro** Python package builds on the [folium](https://github.com/python-visualization/folium) package and implements several methods for displaying Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, `Map.centerObject()`, and `Map.setOptions()`.
The magic command `%%capture` can be used to hide output from a specific cell. Uncomment these lines if you are running this notebook for the first time.
```
# %%capture
# !pip install earthengine-api
# !pip install geehydro
```
Import libraries
```
import ee
import folium
import geehydro
```
Authenticate and initialize Earth Engine API. You only need to authenticate the Earth Engine API once. Uncomment the line `ee.Authenticate()`
if you are running this notebook for the first time or if you are getting an authentication error.
```
# ee.Authenticate()
ee.Initialize()
```
## Create an interactive map
This step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function.
The optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `ESRI`.
```
Map = folium.Map(location=[40, -100], zoom_start=4)
Map.setOptions('HYBRID')
```
## Add Earth Engine Python script
```
# Compute the trend of nighttime lights from DMSP.
# Add a band containing image date as years since 1990.
def createTimeBand(img):
year = img.date().difference(ee.Date('1990-01-01'), 'year')
return ee.Image(year).float().addBands(img)
# function createTimeBand(img) {
# year = img.date().difference(ee.Date('1990-01-01'), 'year')
# return ee.Image(year).float().addBands(img)
# }
# Fit a linear trend to the nighttime lights collection.
collection = ee.ImageCollection('NOAA/DMSP-OLS/CALIBRATED_LIGHTS_V4') \
.select('avg_vis') \
.map(createTimeBand)
fit = collection.reduce(ee.Reducer.linearFit())
# Display a single image
Map.addLayer(ee.Image(collection.select('avg_vis').first()),
{'min': 0, 'max': 63},
'stable lights first asset')
# Display trend in red/blue, brightness in green.
Map.setCenter(30, 45, 4)
Map.addLayer(fit,
{'min': 0, 'max': [0.18, 20, -0.18], 'bands': ['scale', 'offset', 'scale']},
'stable lights trend')
```
## Display Earth Engine data layers
```
Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True)
Map
```
| github_jupyter |
#Assignment 2
##DSC 478 - Programming ML Apps
##Alex Teboul
## Assignment Background
For this assignment you will experiment with various classification models using subsets of some real-world data sets. In particular, you will use the K-Nearest-Neighbor algorithm to classify text documents, experiment with and compare classifiers that are part of the scikit-learn machine learning package for Python, and use some additional preprocessing capabilities of pandas and scikit-learn packages. You will use the data from the data sub-module as well as the existing bank_data file.
```
```
## Problem 1
##K-Nearest-Neighbor (KNN) classification on Newsgroups
[Dataset: newsgroups.zip]
For this problem you will use a subset of the 20 Newsgroup data set. The full data set contains 20,000 newsgroup documents, partitioned (nearly) evenly across 20 different newsgroups and has been often used for experiments in text applications of machine learning techniques, such as text classification and text clustering (see the description of the full dataset). The assignment data set contains a subset of 1000 documents and a vocabulary of terms. Each document belongs to one of two classes Hockey (class label 1) and Microsoft Windows (class label 0). The data has already been split (80%, 20%) into training and test data. The class labels for the training and test data are also provided in separate files. The training and test data contain a row for each term in the vocabulary and a column for each document. The values in the table represent raw term frequencies. The data has already been preprocessed to extract terms, remove stop words and perform stemming (so, the vocabulary contains stems not full terms). Please be sure to read the readme.txt file in the distribution.
Your tasks in this problem are the following [Note: for this problem you should not use scikit-learn for classification, but create your own KNN classifer. You may use Pandas, NumPy, standard Python libraries, and Matplotlib.]
1. trainMatrixModified.txt: the term-document frequency matrix for the training documents. Each row of this matrix corresponds
to one the terms and each column corresponds to one the documents and the (i,j)th element of the matrix shows the frequency of the
ith term in the jth document. This matrix contains 5500 rows and 800 columns.
2. testMatrixModified.txt: the term-document frequency for the test documents. The matrix contains 5500 rows and 200 columns.
3. trainClasses.txt: This file contains the labels associated with each training document. Each line is in the format of documentIndex \t
classId where the documentIndex is in the range of [0,800) and refers to the index of the document in the term-document frequency matrix for train documents.
The classId refers to one of the two classes and takes one of the values 0 (for Windows) or 1 (for Hockey).
4. testClasses.txt: This file contains the labels associated with each test document. Each line is in the format of documentIndex \t classId where the
documentIndex is in the range of [0,200) and refers to the index of the document in the term-document frequency matrix for test documents
5. modifiedterms.txt: This file contains the set of 5500 terms in the vocabulary. Each line contains a term and corresponds to the corresponding rows
in term-document frequency matrices.
### a.
Create your own KNN classifier function. Your classifier should allow as input the training data matrix, the training labels, the instance to be classified, the value of K, and should return the predicted class for the instance and the top K neighbors. Your classifier should work with Euclidean distance as well as Cosine Similarity. You may create two separate classifiers, or add this capability as a parameter for the classifier function.
```
#Imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings
from math import sqrt
from collections import Counter
import matplotlib.pyplot as plt
#Mount Google Drive to get files
from google.colab import drive
drive.mount('/content/drive')
#Files
#train_matrix
train_matrix_path = '/content/drive/My Drive/Colab Notebooks/datasets/newsgroups/trainMatrixModified.txt'
train_matrix = pd.read_csv(train_matrix_path, sep="\t", header=None )
train_matrix.shape
#train_matrix.head()
#train_classes
train_classes_path = '/content/drive/My Drive/Colab Notebooks/datasets/newsgroups/trainClasses.txt'
train_classes = pd.read_csv(train_classes_path, sep="\t", header=None )
train_classes.shape
#train_classes.head()
#test_matrix
test_matrix_path = '/content/drive/My Drive/Colab Notebooks/datasets/newsgroups/testMatrixModified.txt'
test_matrix = pd.read_csv(test_matrix_path, sep="\t", header=None )
test_matrix.shape
#test_matrix.head()
#test_classes
test_classes_path = '/content/drive/My Drive/Colab Notebooks/datasets/newsgroups/testClasses.txt'
test_classes = pd.read_csv(test_classes_path, sep="\t", header=None )
test_classes.shape
#test_classes.head(15)
#test_matrix
mod_terms_path = '/content/drive/My Drive/Colab Notebooks/datasets/newsgroups/modifiedterms.txt'
mod_terms = pd.read_csv(mod_terms_path, sep="\t", header=None )
modt2 = mod_terms.loc[:,0]
mod_terms.head()
mod_terms.shape
#transpositions
train_matrix_t = np.array(train_matrix.T)
test_matrix_t = np.array(test_matrix.T)
#Classes in arrays
train_classes = np.array(train_classes)
test_classes = np.array(test_classes)
def knn_clf(training_matrix, training_labels, instance_to_be_classified, k, distance_measure):
''' This function takes in a training matrix, training labels/classes, a new data point to be classified,
the number of nearest neighbors, and the distance measure "euclidean" or "cosine_similarity". The function
returns the predicted class of the point and its top k nearest neighbors.'''
#distance calculation
if distance_measure == "Euclidean":
distances = np.sqrt(((training_matrix - instance_to_be_classified)**2).sum(axis=1))
elif distance_measure =="Cosine_Similarity":
matrix_norm = np.array([np.linalg.norm(training_matrix[i]) for i in range(len(training_matrix))])
instance_norm = np.linalg.norm(instance_to_be_classified)
sim = np.dot(training_matrix,instance_to_be_classified)/(matrix_norm * instance_norm)
distances = 1 - sim
else:
print("Error - Please enter Euclidean or Cosine_Similarity")
index = np.argsort(distances)
values = []
for i in index:
for j in training_labels:
if any(i==j):
values.append(j[1])
#Classes 0 and 1
zero_count = 0
one_count = 0
#class logic: add up classes to pick most common amongst neighbors
for value in values[:k]:
if value == 0:
zero_count +=1
elif value == 1:
one_count +=1
#getclass
predicted_class = ''
if zero_count > one_count:
predicted_class = 0
elif zero_count < one_count:
predicted_class = 1
else:
print('choose an odd k - there was a tie. or something else broke')
top_k_neighbors = index[:k]
#top_k_distances = sorted(distances)[:k] for distances check
return predicted_class, top_k_neighbors
#trial run
sample = train_matrix_t[[120]]
mat_wosample = np.delete(train_matrix_t,(120),axis=0)
#trial run
pred_class, top_ks = knn_clf(mat_wosample, train_classes, sample, 5, "Euclidean")
#trial run results
print("Predicted Class: {}".format(pred_class))
print("Top K-Neighbors Index: {}".format(top_ks))
```
### b.
Create a function to compute the classification accuracy over the test data set (ratio of correct predictions to the number of test instances). This function will call the classifier function in part a on all the test instances and in each case compares the actual test class label to the predicted class label.
```
def knn_accuracy(data_matrix, class_labels, k, distance_measure):
''' Computes classification accuracy over a test data set. Calls the knn_clf function from part a. A super slow - not optimized knn. But works.'''
predicted_dict = {}
actual_dict = {}
predicted_list = []
count = -1
for instance_to_be_classified in data_matrix:
count += 1
pred_class, top_ks = knn_clf(data_matrix, class_labels, instance_to_be_classified, k, distance_measure)
predicted_dict[count] = pred_class
for l in class_labels:
actual_dict[l[0]] = l[1]
#pull out predicted and actuals
for keyi, valuei in predicted_dict.items():
for keyj, valuej in actual_dict.items():
if keyi == keyj:
predicted_list.append([valuei,valuej])
tally_correct = 0
total_tested = 0
for keyi, valuei in predicted_list:
if keyi == valuei:
tally_correct += 1
total_tested += 1
accuracy = tally_correct/total_tested
return accuracy
#trial run - pretty slow but it runs
knn_accuracy(test_matrix_t, test_classes, 5, "Euclidean")
```
### c.
Run your accuracy function on a range of values for K in order to compare accuracy values for different numbers of neighbors. Do this both using Euclidean Distance as well as Cosine similarity measure. [For example, you can try evaluating your classifiers on a range of values of K from 1 through 20 and present the results as a table or a graph].
```
# Euclidean:
euclidean_accuracies = []
for knum in range(1,20):
if knum %2 !=0:
euclidean_accuracies.append(knn_accuracy(test_matrix_t,test_classes,knum, "Euclidean"))
euclidean_accuracies
# Cosine Similarity:
cosinesim_accuracies = []
for knum in range(1,20):
if knum %2 !=0:
cosinesim_accuracies.append(knn_accuracy(test_matrix_t,test_classes,knum, "Cosine_Similarity"))
cosinesim_accuracies
#Get into a dataframe
ks = [1,3,5,7,9,11,13,15,17,19]
euclidean_col = [0.995, 0.77, 0.83, 0.92, 0.89, 0.9, 0.93, 0.9, 0.88, 0.875]
cosinesim_col = [0.995, 0.99, 0.98, 0.955, 0.935, 0.91, 0.9, 0.855, 0.84, 0.81]
ks_data = list(zip(ks, euclidean_col, cosinesim_col))
ks_summary_columns = ['k','euclidean','cosinesim']
ks_summary_df = pd.DataFrame(ks_data, columns = ks_summary_columns)
ks_summary_df
#summarize findings plot
ks_summary_df.plot(x="k", y=["euclidean", "cosinesim"])
plt.title("euclidean v. cosinesim")
plt.ylabel('accuracy')
plt.show()
```
### d.
Using Python, modify the training and test data sets so that term weights are converted to TFxIDF weights (instead of raw term frequencies). [See class notes on text categorization]. Then, rerun your evaluation on the range of K values (as above) and compare the results to the results without using TFxIDF weights.
```
# first let's find the doc count for each term
DF_train = np.array([(train_matrix!=0).sum(1)]).T
DF_test = np.array([(test_matrix!=0).sum(1)]).T
NDocs_train = 800
NDocs_test = 200
NMatrix_train = np.ones(np.shape(train_matrix), dtype=float)*NDocs_train
NMatrix_test = np.ones(np.shape(test_matrix), dtype=float)*NDocs_test
np.set_printoptions(precision=2,suppress=True,linewidth=120)
IDF_train = np.log2(np.divide(NMatrix_train, DF_train))
IDF_test = np.log2(np.divide(NMatrix_test, DF_test))
tfidf_train = train_matrix * IDF_train
tfidf_test = test_matrix * IDF_test
# Each term in x must be multiplied by the corresponding idf value
#test_tfidf = test_matrix * IDF_test[0]
#print (test_tfidf)
# Testclasses ????
#testclasses_tfidf = test_classes * IDF_test
#testclasses_tfidf
# The KNN Search function expects a doc x term matrix as an np array
tfidf_test_t = np.array(tfidf_test.T)
#Method 2 bc method 1 from notes doesn't seem to be working correctly.
def grab_termfreqs(df, r):
for c in range(0, df.shape[1]):
termfreqs = df[r,c]
return termfreqs ## for each row
def grab_idf(df, c):
listidf = []
b = 0
for rv in range(0, df.shape[0]):
z = df[rv, c]
listidf.append(z)
for i in listidf:
if i != 0:
b += 1
if b == 0:
b = 1
return b
def grab_tfidf(df):
tfidf_list = []
nums = df.shape[0]
for c in range(0, df.shape[1]):
b = grab_idf(df, c)
for r in range(0, df.shape[0]):
temp = grab_termfreqs(df, r)
tfidf = temp * np.log(nums/b)
tfidf_list.append(tfidf)
matrix_fixed = np.array(tfidf_list)
useable_matrix = matrix_fixed.reshape(df.shape[0], df.shape[1])
return useable_matrix
test_tfidf_fixed = grab_tfidf(test_matrix_t)
# Euclidean - TFxIDF:
euclidean_accuracies_tfidf = []
for knum in range(1,20):
if knum %2 !=0:
euclidean_accuracies_tfidf.append(knn_accuracy(test_tfidf_fixed,test_classes,knum, "Euclidean"))
euclidean_accuracies_tfidf
# Cosine Similarity TFxIDF:
cosinesim_accuracies_tfidf = []
for knum in range(1,20):
if knum %2 !=0:
cosinesim_accuracies_tfidf.append(knn_accuracy(test_tfidf_fixed,test_classes,knum, "Cosine_Similarity"))
cosinesim_accuracies_tfidf
#Get into a dataframe
ks_tfidf = [1,3,5,7,9,11,13,15,17,19]
euclidean_col_tfidf = [0.995, 0.78, 0.695, 0.635, 0.615, 0.58, 0.555, 0.535, 0.57, 0.565]
cosinesim_col_tfidf = [0.995, 0.795, 0.75, 0.67, 0.66, 0.62, 0.62, 0.625, 0.595, 0.585]
ks_data_tfidf = list(zip(ks_tfidf, euclidean_col_tfidf, cosinesim_col_tfidf))
ks_summary_columns_tfidf = ['k','euclidean_tfidf','cosinesim_tfidf']
ks_summary_df_tfidf = pd.DataFrame(ks_data_tfidf, columns = ks_summary_columns_tfidf)
ks_summary_df_tfidf
#summarize findings plot
ks_summary_df_tfidf.plot(x="k", y=["euclidean_tfidf", "cosinesim_tfidf"])
plt.title("euclidean_tfidf v. cosinesim_tfidf")
plt.ylabel('accuracy')
plt.show()
```
* Not really sure how to interpret this difference. Seems strange that the accuracy drops so much with increasing k. I think I may have erred in my matrix calculation with the tfidfs. I tried two methods, the first produced a flatline for both measures around 0.5 accuracy so I assumed I'd made a mistake. From scratch method 2 also seems to have poor performance.
* Based on these results I would not use the TFxIDF but I presume there is a bug in my code I have been unable to locate.
### e.
Create a new classifier based on the Rocchio Method adapted for text categorization [See class notes on text categorization]. You should separate the training function from the classification function. The training part for the classifier can be implemented as a function that takes as input the training data matrix and the training labels, returning the prototype vectors for each class. The classification part can be implemented as another function that would take as input the prototypes returned from the training function and the instance to be classified. This function should measure Cosine similarity of the test instance to each prototype vector. Your output should indicate the predicted class for the test instance and the similarity values of the instance to each of the category prototypes. Finally, compute the classification accuracy using the test instances and compare your results to the best KNN approach you tried earlier.
```
#From class notes
#d = tfidf_test_t
#m=-2
#for i in range(1,n):
# s=cosSim(d,p)
#if s>m:
#m=s
#r=c
#return class_r
#X : Training vector {array-like, sparse matrix}, shape (n_samples, n_features).
#y : Target vector relative to X array-like, shape (n_samples,).
X = test_matrix_t
y = test_classes[:,0]
from sklearn.neighbors.nearest_centroid import NearestCentroid
clf_nc=NearestCentroid()
clf_nc.fit(X,y)
#test_matrix_t.shape
#y.shape
print (clf_nc.score(X, y)*100, "%")
```
* Not sure what went wrong here to end up with 100 percent...
* Assuming it's actually 100%, which I doubt because I probably have an error - then it is the best method. Compared to the best from before of Euclidean, this is an improvement of at least 10%accuracy.
## Problem 2
## Classification using scikit-learn
[Dataset: bank_data.csv]
For this problem you will experiment with various classifiers provided as part of the scikit-learn (sklearn) machine learning module, as well as with some of its preprocessing and model evaluation capabilities. [Note: This module is already part of the Anaconda distributions. However, if you are using standalone Python distributions, you will need to first obtain and install it]. You will work with a modified subset of a real data set of customers for a bank. This is the same data set used in Assignment 1. The data is provided in a CSV formatted file with the first row containing the attribute names. The description of the the different fields in the data are provided in the data section.
Your tasks in this problem are the following:
### a.
Load and preprocess the data using Numpy or Pandas and the preprocessing functions from scikit-learn. Specifically, you need to separate the target attribute ("pep") from the portion of the data to be used for training and testing. You will need to convert the selected dataset into the Standard Spreadsheet format (scikit-learn functions generally assume that all attributes are in numeric form). Finally, you need to split the transformed data into training and test sets (using 80%-20% randomized split). [Review Ipython Notebook examples from Week 4 for different ways to perform these tasks.]
```
#Imports
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import neighbors, tree, naive_bayes
from sklearn import preprocessing
import matplotlib.pyplot as plt
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
#Mounts the Google Drive so I can pull the bank_data.csv file from my drive. Like setting working directory.
from google.colab import drive
drive.mount('/content/drive')
#File_path
file_path = '/content/drive/My Drive/Colab Notebooks/datasets/bank_data.csv'
#Load in the Dataset
bank_data = pd.read_csv(file_path)
bank_data.head()
#We don't need that ID column for anything
bank_data.drop('id', axis=1, inplace=True)
bank_data.head(1)
#PEP Target Set
pep_target = bank_data.pep
pep_target.head()
#Attribute Set
bank_attributes = bank_data[['age','income','children','gender','region','married','car','savings_acct','current_acct','mortgage']]
bank_attributes.head()
bank_dummy = pd.get_dummies(bank_attributes)
bank_dummy.head()
#Split the data into train/test sets
bank_train, bank_test, pep_target_train, pep_target_test = train_test_split(bank_dummy, pep_target, test_size=0.2, random_state=7)
#Inspect bank Test set
print (bank_test.shape)
bank_test[0:5]
#Inspect bank Train set - can confirm that 480 train to 120 test is 80:20 split.
print (bank_train.shape)
bank_train[0:5]
```
### b.
Run scikit-learn's KNN classifier on the test set. Note: in the case of KNN, you should first normalize the data so that all attributes are in the same scale (normalize so that the values are between 0 and 1). Generate the confusion matrix (visualize it using Matplotlib), as well as the classification report. Also, compute the average accuracy score. Experiment with different values of K and the weight parameter (i.e., with or without distance weighting) for KNN to see if you can improve accuracy (you do not need to provide the details of all of your experimentation, but provide a short discussion on what parameters worked best as well as your final results).
```
#Normalize the dummy matrix range (0,1)
min_max_scaler = preprocessing.MinMaxScaler().fit(bank_train)
bank_train_norm = min_max_scaler.transform(bank_train)
bank_test_norm = min_max_scaler.transform(bank_test)
print("bank_train_norm = ", bank_train_norm[0:5])
print("")
print( "bank_test_norm = ", bank_test_norm[0:5])
#Run KNN
n_neighbors = 5
bank_knn_5_w = neighbors.KNeighborsClassifier(n_neighbors, weights='distance')
bank_knn_5_w.fit(bank_train_norm, pep_target_train)
#Get predicted classes
bank_knn_5_w_preds_test = bank_knn_5_w.predict(bank_test_norm)
print(bank_knn_5_w_preds_test)
#Generate the confusion matrix
bank_knn_5_w_cm = confusion_matrix(pep_target_test, bank_knn_5_w_preds_test)
print (bank_knn_5_w_cm)
#Plot it
plt.matshow(bank_knn_5_w_cm)
plt.title('Confusion matrix')
plt.colorbar()
plt.ylabel('Actual')
plt.xlabel('Predicted')
plt.show()
#Classification Report
print(classification_report(pep_target_test, bank_knn_5_w_preds_test))
#Average Accuracy Score
print (bank_knn_5_w.score(bank_test_norm, pep_target_test)*100, "%")
#K's and W/ & W/o Weight Parameter Testing
#Run KNN
n_neighbors = 7
bank_knn = neighbors.KNeighborsClassifier(n_neighbors)
bank_knn.fit(bank_train_norm, pep_target_train)
#Get predicted classes
bank_knn_preds_test = bank_knn.predict(bank_test_norm)
print(bank_knn_preds_test)
#Generate the confusion matrix
bank_knn_cm = confusion_matrix(pep_target_test, bank_knn_preds_test)
print (bank_knn_cm)
#Classification Report
print(classification_report(pep_target_test, bank_knn_preds_test))
#Average Accuracy Score
print (bank_knn.score(bank_test_norm, pep_target_test)*100, "%")
#Best Model
n_neighbors_list = [1,1,3,3,5,5,7,7,9,9,11,11]
weights_list = ["yes","no","yes","no","yes","no","yes","no","yes","no","yes","no","yes","no"]
accuracy_scores_list = [60.8,60.8,56.7,56.7,55.8,55.8,64.2,68.3,65.0,68.3,64.2,68.3]
knn_data = list(zip(n_neighbors_list, weights_list, accuracy_scores_list))
knn_summary_columns = ['k','weight parameter','accuracy']
knn_summary_df = pd.DataFrame(knn_data, columns = knn_summary_columns)
knn_summary_df
#summarize findings plot
knnplt_df = knn_summary_df.pivot(index='k', columns='weight parameter', values='accuracy')
knnplt_df.plot()
```
**Discussion**
* KNN with k=7 and no weight parameter achieved the highest accuracy of 68.3%.
* It also yielded the highest precision/recall figures as well. I would pick this k and weight paraemter set. The chart above shows the summary of parameters tested.
### c.
Repeat the classification using scikit-learn's decision tree classifier (using the default parameters) and the Naive Bayes (Gaussian) classifier. As above, generate the confusion matrix, classification report, and average accuracy scores for each classifier. For each model, compare the average accuracy scores on the test and the training data sets. What does the comparison tell you in terms of bias-variance trade-off?
**Decision Tree Classifier**
```
#Run Descision Tree
treeclf = tree.DecisionTreeClassifier(criterion='entropy', min_samples_split=12)
treeclf = treeclf.fit(bank_train, pep_target_train)
treepreds_test = treeclf.predict(bank_test)
print (treepreds_test)
#Confusion Matrix
treecm = confusion_matrix(pep_target_test, treepreds_test)
print (treecm)
plt.matshow(treecm)
plt.title('Confusion matrix')
plt.colorbar()
plt.ylabel('Actual')
plt.xlabel('Predicted')
plt.show()
#Classification Report
print(classification_report(pep_target_test, treepreds_test))
#Average Accuracy Scores
print ("train accuracy: ", treeclf.score(bank_train, pep_target_train)*100)
print ("test accuracy: ", treeclf.score(bank_test, pep_target_test)*100)
```
* Was overfitting badly with lower min_samples_split. Could be reasonable now as train and test accuracies are much closer.
**Decision Tree Classifier - Train vs. Test Accuracy**
* Train Accuracy: 92.5%
* Test Accuracy: 90.0%
* This is a pretty solid accuracy, a larger dataset is needed to determine whether or not overfitting is taking place now, but it doesn't appear to be the case.
**Naive Bayes (Gaussian) Classifier**
```
#Run Naive Bayes
nbclf = naive_bayes.GaussianNB()
nbclf = nbclf.fit(bank_train, pep_target_train)
nbpreds_test = nbclf.predict(bank_test)
print (nbpreds_test)
#Confusion Matrix
nbcm = confusion_matrix(pep_target_test, nbpreds_test)
print (nbcm)
plt.matshow(nbcm)
plt.title('Confusion matrix')
plt.colorbar()
plt.ylabel('Actual')
plt.xlabel('Predicted')
plt.show()
#Classfication Report
print(classification_report(pep_target_test, nbpreds_test))
#Average Accuracy Scores
print ("train accuracy: ",nbclf.score(bank_train, pep_target_train)*100)
print ("test accuracy: ",nbclf.score(bank_test, pep_target_test)*100)
```
**Naive Bayes (Gaussian) Classifier - Train vs. Test Accuracy**
* Train Accuracy: 66.3 %
* Test Accuracy: 61.7 %
* This is a pretty weak result, Naive Bayes like this should not be used on this particular dataset.
**Train/Test Accuracy and Bias-Variance Trade-Off**
* Bias Definition: The difference between the average prediction of the model and the correct value the model attempts to predict.
* Variance Definition: The variability of model prediction for a given data point or a value which indicates the spread of the data.
* High Bias means the model may be oversimplified and show in high errors in train and test. The Naive Bayes model above could be said to have high bias.
* High Variance means the model pays too much attention to the training data and fails to generalize to the test data. This was apparent in the initial trials for the decision tree model I ran with min_samples_split of 3. Specifically, training accuracy was 99%, while testing was mid-80%s. To address this, I increased the min samples to split on, such that training accuracy decreased while testing accuracy increased. In the end settled on 12 samples to split on and had close train/test accuracy around 90%.
* KNN is different in how to think about train/test accuracy but the model could still be said to have High Bias as well because it didn't fit the data well, shown by low accuracy.
### d.
Discuss your observations based on the above experiments.
**Further Observations**
* Decision Trees: Best Model achieved 90% test accuracy. For this dataset, Decision Trees or similar variants could prove useful. KNN and Naive Bayes were less successful in the classification task. Better Precision/Recall with DT than the other models as well and for such a small dataset, the computational tradeoffs of these different models are negligible. Took some parameter tuning to get this better model result though, and no parameter tuning was done for Naive Bayes while parameter tuning was done for KNN.
* KNN: Best Model achieved 68% test accuracy.
* Naive Bayes: Best Model achieved 62% test accuracy.
## Problem 3
## Data Analysis and Predictive Modeling on Census data
[Dataset: adult-modified.csv]
For this problem you will use a simplified version of the Adult Census Data Set. In the subset provided here, some of the attributes have been removed and some preprocessing has been performed.
Your tasks in this problem are the following:
### a. Preprocessing and data analysis:
#### 1. Examine the data for missing values. In case of categorical attributes, remove instances with missing values. In the case of numeric attributes, impute and fill-in the missing values using the attribute mean.
```
#Imports
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import neighbors, tree, naive_bayes
from sklearn import preprocessing
import matplotlib.pyplot as plt
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
import seaborn as sns
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
import graphviz
from sklearn.tree import export_graphviz
from sklearn import model_selection
#Mounts the Google Drive so I can pull the bank_data.csv file from my drive. Like setting working directory.
from google.colab import drive
drive.mount('/content/drive')
#File_path
file_path_census = '/content/drive/My Drive/Colab Notebooks/datasets/adult-modified.csv'
#Load in the Dataset
census_data_pre = pd.read_csv(file_path_census,na_values=["?"])
census_data_pre.head()
```
**To Do**
* Numeric: Impute and fill in the missing values with the attribute means for age, education, hours-per-week (one by one)
* Categorical: Remove missing value rows for workclass, marital-status, race, sex, income (dropna)
* age - 198 na
* workclass - 588 na
```
#shape check
census_data_pre.shape
#Numeric
census_data = census_data_pre
age_mean = census_data.age.mean() #actually the only numeric with na but I'll do the others anyways..
education_mean = census_data.education.mean()
hpw_mean = census_data['hours-per-week'].mean()
census_data.age.fillna(age_mean, axis=0, inplace=True)
census_data.education.fillna(education_mean, axis=0, inplace=True)
census_data['hours-per-week'].fillna(hpw_mean, axis=0, inplace=True)
census_data.isnull().sum()
#shape check
census_data.shape
#Categorical
census_data = census_data.dropna()
census_data.isnull().sum()
census_data.shape
```
* Great. Missing values dealt with.
#### 2. Examine the characteristics of the attributes, including relevant statistics for each attribute, histograms illustrating the distributions of numeric attributes, bar graphs showing value counts for categorical attributes, etc.
```
#Numeric Attributes Histograms
census_data.hist()
#Numeric Attributes Description
census_data.describe().T
#Categorical Attributes Bar Graphs
#workclass
census_data['workclass'].value_counts().plot(kind='bar')
census_data['workclass'].value_counts()
#marital-status
census_data['marital-status'].value_counts().plot(kind='bar')
census_data['marital-status'].value_counts()
#race
census_data['race'].value_counts().plot(kind='bar')
census_data['race'].value_counts()
#sex
census_data['sex'].value_counts().plot(kind='bar')
census_data['sex'].value_counts()
#income
census_data['income'].value_counts().plot(kind='bar')
census_data['income'].value_counts()
```
#### 3. Perform the following cross-tabulations (including generating bar charts): education+race, work-class+income, work-class+race, and race+income. In the latter case (race+income) also create a table or chart showing percentages of each race category that fall in the low-income group. Discuss your observations from this analysis.
```
#education + race cross-tabulation
pd.crosstab(census_data.education,census_data.race)
#education + race bar chart
plt.figure(figsize=(12,6))
race_edu_comp = sns.countplot(x="education", hue="race", data=census_data)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
#work-class + income cross-tabulation
pd.crosstab(census_data.workclass,census_data.income)
#work-class + income bar chart
plt.figure(figsize=(12,6))
work_inc_comp = sns.countplot(x="workclass", hue="income", data=census_data)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
#work-class + race cross-tabulation
pd.crosstab(census_data.workclass,census_data.race)
#work-class + race bar chart
plt.figure(figsize=(12,6))
work_rCE_comp = sns.countplot(x="workclass", hue="race", data=census_data)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
#race + income cross-tabulation
pd.crosstab(census_data.race,census_data.income)
#race + income bar chart
plt.figure(figsize=(12,6))
race_inc_comp = sns.countplot(x="race", hue="income", data=census_data)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
#Show the percentages of each race that end up in the low-income category:
#Clean it up (manually):
# intialise data of lists.
race_lowinc_data = {'Race':['White', 'Black', 'Asian', 'Amer-Indian', 'Hispanic'],
'Percentage_LowIncome':[73.7, 86.7, 77.0, 90.2, 92.0]}
# Create DataFrame
race_lowinc_df = pd.DataFrame(race_lowinc_data)
race_lowinc_df = race_lowinc_df.sort_values('Percentage_LowIncome')
# Print the output.
race_lowinc_df
plt.figure(figsize=(12,6))
race_lowinc_df.plot(kind='bar',x='Race',y='Percentage_LowIncome')
plt.title('Percentage Low Income by Race')
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
```
**Observations**
* education + race: In this sample dataset, there are significantly more white in the dataset compared to the other races. When looking at counts of race in each education level, whitehave far larger counts, but relatively it seems that most of the races follow a similar distribution of education received. The greatest counts for each race are around8-9 years of education which is compulsory in the United States. The distributions also appear to be bimodal as a secondary maximum appears around 13 for education. This makes sense because many people go to college. Peaks around graduation milestones (Middle school, High School, College).
* workclass + income: Public and Self-Employed share similar income outcomes. In the Private Sector there is a greater number of <=50k jobs and in higher proportion to >=50k jobs, but more people in general are also employed in the private sector compared to public and self-employed.
* workclass + race: Not much insight available when looking at just counts here. Similar distribution across races.
* race + income: Hard to interpret because of the scale, which is why the percentage bar plot that follows is better.
* Percentage Low Income by Race: Here we see that for the dataset, White race has the lowest percentage of people with LowIncome or income <=50k. For the White race the figure is 73.7%, followed by Asian, then Black, Amer-Indian, and finally Hispanic with 92.0% earning <=50k. Assuming this data scales and explains the greater picture of earnings by Americans across the country, it is a clear sign of the economic disparity that exists by race in the US.
#### 4. Compare and contrast the characteristics of the low-income and high-income categories across the different attributes.
```
#Extra for analysis:
#education + income bar chart
plt.figure(figsize=(12,6))
race_edu_comp = sns.countplot(x="education", hue="income", data=census_data)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
#Extra for analysis:
#workclass + income bar chart
plt.figure(figsize=(12,6))
race_edu_comp = sns.countplot(x="workclass", hue="income", data=census_data)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
#Extra for analysis:
#sex + income bar chart
plt.figure(figsize=(12,6))
race_edu_comp = sns.countplot(x="sex", hue="income", data=census_data)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
#Extra for analysis:
#marital status + income bar chart
plt.figure(figsize=(12,6))
race_edu_comp = sns.countplot(x="marital-status", hue="income", data=census_data)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
#sex + income cross-tabulation
pd.crosstab(census_data.sex,census_data.income)
```
* More on this was explained above, but some main take-aways are:
* Race seems to play a strong predictive role in low-income vs. high-income figures in the dataset.
* Education is also very important as seen above. For people who receive similar amounts of education, receiving more education increases the likelihood of earning >50k.
* Workclass shows that self-emp people are more likely to earn >50k relative to their peers who are also self employed than private or public employies are relative to other private/public employees. Public is next, followed by private. There are far more private jobs though, so the predictive power of this attribute is lower than say education.
* Sex is also an important indicator of income. Females are 88% low-income while only 69% of Male is low-income in this dataset.
* Marital-Status is actually the most predictive of income. Splitting on this in a Decision Tree would probably give pretty solid accuracy. Married individuals are more likely to earn high income.
### b. Predictive Modeling and Model Evaluation:
#### 1. Using either Pandas or Scikit-learn, create dummy variables for the categorical attributes. Then separate the target attribute ("income_>50K") from the attributes used for training. [Note: you need to drop "income_<=50K" which is also created as a dummy variable in earlier steps).
```
#Create dummy set
census_dummy = pd.get_dummies(census_data)
#Drop the income_<=50K column
census_dummy = census_dummy.drop(['income_<=50K'],axis=1)
census_dummy.head()
#Target Attribute Set
census_target = census_dummy[['income_>50K']]
census_target.head()
#Training Attributes Set
training_attributes = census_dummy.drop(['income_>50K'], axis=1)
training_attributes.head()
```
#### 2. Use scikit-learn to build classifiers uisng Naive Bayes (Gaussian), decision tree (using "entropy" as selection criteria), and linear discriminant analysis (LDA). For each of these perform 10-fold cross-validation (using cross-validation module in scikit-learn) and report the overall average accuracy.
```
#Train/Test Split
census_train, census_test, census_target_train, census_target_test = train_test_split(training_attributes, census_target, test_size=0.2, random_state=7)
print (census_test.shape)
census_test[0:5]
print (census_train.shape)
census_train[0:5]
```
**Naive Bayes (Gaussian)**
```
census_nbclf = naive_bayes.GaussianNB()
#census_nbclf = census_nbclf.fit(census_train, census_target_train)
#print ("Score on Training: ", census_nbclf.score(census_train, census_target_train))
#print ("Score on Test: ", census_nbclf.score(census_test, census_target_test))
census_cv_scores_nb = model_selection.cross_val_score(census_nbclf, training_attributes, census_target, cv=10)
print("Overall Accuracy on X-Val: %0.2f (+/- %0.2f)" % (census_cv_scores_nb.mean(), census_cv_scores_nb.std() * 2))
```
**Decision Tree using Entropy**
```
census_treeclf = tree.DecisionTreeClassifier(criterion='entropy', min_samples_split=100, max_depth=2)
census_cv_scores_tree = model_selection.cross_val_score(census_treeclf, training_attributes, census_target, cv=10)
print("Overall Accuracy on X-Val: %0.2f (+/- %0.2f)" % (census_cv_scores_tree.mean(), census_cv_scores_tree.std() * 2))
```
**Linear Discriminant Analysis (LDA)**
```
import warnings
warnings.filterwarnings('ignore')
census_ldclf = LinearDiscriminantAnalysis()
#census_ldclf = census_ldclf.fit(census_train, census_target_train)
#print ("Score on Training: ", census_ldclf.score(census_train, census_target_train))
#print ("Score on Test: ", census_ldclf.score(census_test, census_target_test))
census_cv_scores_ld = model_selection.cross_val_score(census_ldclf, training_attributes, census_target, cv=10)
print("Overall Accuracy on X-Val: %0.2f (+/- %0.2f)" % (census_cv_scores_ld.mean(), census_cv_scores_ld.std() * 2))
```
* The LDA was warning of collinearity, this should probably be addressed if a regression like technique is to be used.
* Naive Bayes: 0.72 (+/- 0.02)
* Decision Tree: 0.81 (+/- 0.02)
* LDA: 0.81 (+/- 0.02)
#### 3. For the decision tree model (generated on the full training data), generate a visualization of tree and submit it as a separate file (png, jpg, or pdf) or embed it in the Jupyter Notebook.
```
census_treeclf = census_treeclf.fit(census_train, census_target_train)
export_graphviz(census_treeclf,out_file='tree.dot', feature_names=census_train.columns)
with open("tree.dot") as f:
dot_graph = f.read()
graphviz.Source(dot_graph)
```
* Set a lower max depth and didn't lose any accuracy. Simpler model works just as well it appears.
| github_jupyter |
##### Copyright 2021 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# Simple TFX Pipeline for Vertex Pipelines
This notebook-based tutorial will create a simple TFX pipeline and run it using
Google Cloud Vertex Pipelines. This notebook is based on the TFX pipeline
built in
[Simple TFX Pipeline Tutorial](https://www.tensorflow.org/tfx/tutorials/tfx/penguin_simple).
Google Cloud Vertex Pipelines helps you to automate, monitor, and govern
your ML systems by orchestrating your ML workflow in a serverless manner. You
can define your ML pipelines using Python with TFX, and then execute your
pipelines on Google Cloud. See
[Vertex Pipelines introduction](https://cloud.google.com/vertex-ai/docs/pipelines/introduction)
to learn more about Vertex Pipelines.
## Setup
### Install python packages
We will install required Python packages including TFX and KFP to author ML
pipelines and submit jobs to Vertex Pipelines.
```
# Use the latest version of pip.
!pip install --upgrade pip
!pip install --upgrade "tfx[kfp]<2"
```
#### Restart the runtime
Restart the runtime to ensure the following cells use the updated versions.
You can restart the runtime with following cell:
```
# docs_infra: no_execute
import sys
if not 'google.colab' in sys.modules:
# Automatically restart kernel after installs
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)
```
Check the package versions.
```
import tensorflow as tf
print('TensorFlow version: {}'.format(tf.__version__))
from tfx import v1 as tfx
print('TFX version: {}'.format(tfx.__version__))
import kfp
print('KFP version: {}'.format(kfp.__version__))
```
### Set up variables
We will set up some variables used to customize the pipelines below. Following
information is required:
* GCP Project id. You can find your Project ID in the panel with your lab instructions.
* GCP Region to run pipelines. For more information about the regions that
Vertex Pipelines is available in, see the
[Vertex AI locations guide](https://cloud.google.com/vertex-ai/docs/general/locations#feature-availability).
* Google Cloud Storage Bucket to store pipeline outputs.
**Enter required values in the cell below before running it**.
```
GOOGLE_CLOUD_PROJECT = '' # <--- ENTER THIS
GOOGLE_CLOUD_REGION = 'us-central1'
GCS_BUCKET_NAME = GOOGLE_CLOUD_PROJECT + '-gcs'
if not (GOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_REGION and GCS_BUCKET_NAME):
from absl import logging
logging.error('Please set all required parameters.')
```
Set `gcloud` to use your project.
```
!gcloud config set project {GOOGLE_CLOUD_PROJECT}
PIPELINE_NAME = 'penguin-vertex-pipelines'
# Path to various pipeline artifact.
PIPELINE_ROOT = 'gs://{}/pipeline_root/{}'.format(
GCS_BUCKET_NAME, PIPELINE_NAME)
# Paths for users' Python module.
MODULE_ROOT = 'gs://{}/pipeline_module/{}'.format(
GCS_BUCKET_NAME, PIPELINE_NAME)
# Paths for input data.
DATA_ROOT = 'gs://{}/data/{}'.format(GCS_BUCKET_NAME, PIPELINE_NAME)
# This is the path where your model will be pushed for serving.
SERVING_MODEL_DIR = 'gs://{}/serving_model/{}'.format(
GCS_BUCKET_NAME, PIPELINE_NAME)
print('PIPELINE_ROOT: {}'.format(PIPELINE_ROOT))
```
### Prepare example data
The dataset we are using is the
[Palmer Penguins dataset](https://allisonhorst.github.io/palmerpenguins/articles/intro.html).
There are four numeric features in this dataset:
* culmen_length_mm
* culmen_depth_mm
* flipper_length_mm
* body_mass_g
All features were already normalized
to have range [0,1]. We will build a classification model which predicts the
`species` of penguins.
We need to make our own copy of the dataset. Because TFX ExampleGen reads
inputs from a directory, we need to create a directory and copy dataset to it
on GCS.
```
!gsutil cp gs://download.tensorflow.org/data/palmer_penguins/penguins_processed.csv {DATA_ROOT}/
```
Take a quick look at the CSV file.
```
!gsutil cat {DATA_ROOT}/penguins_processed.csv | head
```
You should be able to see five values. `species` is one of 0, 1 or 2, and all other features should have values between 0 and 1.
## Create a pipeline
TFX pipelines are defined using Python APIs. We will define a pipeline which
consists of three components:
* CsvExampleGen: Reads in data files and convert them to TFX internal format for further processing. There are multiple ExampleGens for various formats. In this tutorial, we will use CsvExampleGen which takes CSV file input.
* Trainer: Trains an ML model. Trainer component requires a model definition code from users. You can use TensorFlow APIs to specify how to train a model and save it in a _savedmodel format.
* Pusher: Copies the trained model outside of the TFX pipeline. Pusher component can be thought of an deployment process of the trained ML model.
Our pipeline will be almost identical to a basic [TFX pipeline](https://www.tensorflow.org/tfx/tutorials/tfx/penguin_simple).
The only difference is that we don't need to set `metadata_connection_config`
which is used to locate
[ML Metadata](https://www.tensorflow.org/tfx/guide/mlmd) database. Because
Vertex Pipelines uses a managed metadata service, users don't need to care
of it, and we don't need to specify the parameter.
Before actually define the pipeline, we need to write a model code for the
Trainer component first.
### Write model code.
We will create a simple DNN model for classification using TensorFlow Keras API. This model training code will be saved to a separate file.
In this tutorial we will use __Generic Trainer__ of TFX which support Keras-based models. You need to write a Python file containing run_fn function, which is the entrypoint for the `Trainer` component.
```
_trainer_module_file = 'penguin_trainer.py'
%%writefile {_trainer_module_file}
# Copied from https://www.tensorflow.org/tfx/tutorials/tfx/penguin_simple
from typing import List
from absl import logging
import tensorflow as tf
from tensorflow import keras
from tensorflow_transform.tf_metadata import schema_utils
from tfx import v1 as tfx
from tfx_bsl.public import tfxio
from tensorflow_metadata.proto.v0 import schema_pb2
_FEATURE_KEYS = [
'culmen_length_mm', 'culmen_depth_mm', 'flipper_length_mm', 'body_mass_g'
]
_LABEL_KEY = 'species'
_TRAIN_BATCH_SIZE = 20
_EVAL_BATCH_SIZE = 10
# Since we're not generating or creating a schema, we will instead create
# a feature spec. Since there are a fairly small number of features this is
# manageable for this dataset.
_FEATURE_SPEC = {
**{
feature: tf.io.FixedLenFeature(shape=[1], dtype=tf.float32)
for feature in _FEATURE_KEYS
},
_LABEL_KEY: tf.io.FixedLenFeature(shape=[1], dtype=tf.int64)
}
def _input_fn(file_pattern: List[str],
data_accessor: tfx.components.DataAccessor,
schema: schema_pb2.Schema,
batch_size: int) -> tf.data.Dataset:
"""Generates features and label for training.
Args:
file_pattern: List of paths or patterns of input tfrecord files.
data_accessor: DataAccessor for converting input to RecordBatch.
schema: schema of the input data.
batch_size: representing the number of consecutive elements of returned
dataset to combine in a single batch
Returns:
A dataset that contains (features, indices) tuple where features is a
dictionary of Tensors, and indices is a single Tensor of label indices.
"""
return data_accessor.tf_dataset_factory(
file_pattern,
tfxio.TensorFlowDatasetOptions(
batch_size=batch_size, label_key=_LABEL_KEY),
schema=schema).repeat()
def _make_keras_model() -> tf.keras.Model:
"""Creates a DNN Keras model for classifying penguin data.
Returns:
A Keras Model.
"""
# The model below is built with Functional API, please refer to
# https://www.tensorflow.org/guide/keras/overview for all API options.
inputs = [keras.layers.Input(shape=(1,), name=f) for f in _FEATURE_KEYS]
d = keras.layers.concatenate(inputs)
for _ in range(2):
d = keras.layers.Dense(8, activation='relu')(d)
outputs = keras.layers.Dense(3)(d)
model = keras.Model(inputs=inputs, outputs=outputs)
model.compile(
optimizer=keras.optimizers.Adam(1e-2),
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=[keras.metrics.SparseCategoricalAccuracy()])
model.summary(print_fn=logging.info)
return model
# TFX Trainer will call this function.
def run_fn(fn_args: tfx.components.FnArgs):
"""Train the model based on given args.
Args:
fn_args: Holds args used to train the model as name/value pairs.
"""
# This schema is usually either an output of SchemaGen or a manually-curated
# version provided by pipeline author. A schema can also derived from TFT
# graph if a Transform component is used. In the case when either is missing,
# `schema_from_feature_spec` could be used to generate schema from very simple
# feature_spec, but the schema returned would be very primitive.
schema = schema_utils.schema_from_feature_spec(_FEATURE_SPEC)
train_dataset = _input_fn(
fn_args.train_files,
fn_args.data_accessor,
schema,
batch_size=_TRAIN_BATCH_SIZE)
eval_dataset = _input_fn(
fn_args.eval_files,
fn_args.data_accessor,
schema,
batch_size=_EVAL_BATCH_SIZE)
model = _make_keras_model()
model.fit(
train_dataset,
steps_per_epoch=fn_args.train_steps,
validation_data=eval_dataset,
validation_steps=fn_args.eval_steps)
# The result of the training should be saved in `fn_args.serving_model_dir`
# directory.
model.save(fn_args.serving_model_dir, save_format='tf')
```
Copy the module file to GCS which can be accessed from the pipeline components.
Because model training happens on GCP, we need to upload this model definition.
Otherwise, you might want to build a container image including the module file
and use the image to run the pipeline.
```
!gsutil cp {_trainer_module_file} {MODULE_ROOT}/
```
### Write a pipeline definition
We will define a function to create a TFX pipeline.
```
# Copied from https://www.tensorflow.org/tfx/tutorials/tfx/penguin_simple and
# slightly modified because we don't need `metadata_path` argument.
def _create_pipeline(pipeline_name: str, pipeline_root: str, data_root: str,
module_file: str, serving_model_dir: str,
) -> tfx.dsl.Pipeline:
"""Creates a three component penguin pipeline with TFX."""
# Brings data into the pipeline.
example_gen = tfx.components.CsvExampleGen(input_base=data_root)
# Uses user-provided Python function that trains a model.
trainer = tfx.components.Trainer(
module_file=module_file,
examples=example_gen.outputs['examples'],
train_args=tfx.proto.TrainArgs(num_steps=100),
eval_args=tfx.proto.EvalArgs(num_steps=5))
# Pushes the model to a filesystem destination.
pusher = tfx.components.Pusher(
model=trainer.outputs['model'],
push_destination=tfx.proto.PushDestination(
filesystem=tfx.proto.PushDestination.Filesystem(
base_directory=serving_model_dir)))
# Following three components will be included in the pipeline.
components = [
example_gen,
trainer,
pusher,
]
return tfx.dsl.Pipeline(
pipeline_name=pipeline_name,
pipeline_root=pipeline_root,
components=components)
```
## Run the pipeline on Vertex Pipelines.
TFX provides multiple orchestrators to run your pipeline. In this tutorial we
will use the Vertex Pipelines together with the Kubeflow V2 dag runner.
We need to define a runner to actually run the pipeline. You will compile
your pipeline into our pipeline definition format using TFX APIs.
```
import os
PIPELINE_DEFINITION_FILE = PIPELINE_NAME + '_pipeline.json'
runner = tfx.orchestration.experimental.KubeflowV2DagRunner(
config=tfx.orchestration.experimental.KubeflowV2DagRunnerConfig(),
output_filename=PIPELINE_DEFINITION_FILE)
# Following function will write the pipeline definition to PIPELINE_DEFINITION_FILE.
_ = runner.run(
_create_pipeline(
pipeline_name=PIPELINE_NAME,
pipeline_root=PIPELINE_ROOT,
data_root=DATA_ROOT,
module_file=os.path.join(MODULE_ROOT, _trainer_module_file),
serving_model_dir=SERVING_MODEL_DIR))
```
The generated definition file can be submitted using kfp client.
```
# docs_infra: no_execute
from google.cloud import aiplatform
from google.cloud.aiplatform import pipeline_jobs
aiplatform.init(project=GOOGLE_CLOUD_PROJECT, location=GOOGLE_CLOUD_REGION)
job = pipeline_jobs.PipelineJob(template_path=PIPELINE_DEFINITION_FILE,
display_name=PIPELINE_NAME)
job.run(sync=False)
```
Now you can visit the link in the output above or visit
'Vertex AI > Pipelines' in
[Google Cloud Console](https://console.cloud.google.com/) to see the
progress.
| github_jupyter |
##### Copyright 2019 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# TensorFlow 2 quickstart untuk tingkat lanjut
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/tutorials/quickstart/advanced"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />Lihat di TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/id/tutorials/quickstart/advanced.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Jalankan di Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/id/tutorials/quickstart/advanced.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />Lihat sumber kode di GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/docs/site/id/tutorials/quickstart/advanced.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Unduh notebook</a>
</td>
</table>
Note: Komunitas TensorFlow kami telah menerjemahkan dokumen-dokumen ini. Tidak ada jaminan bahwa translasi ini akurat, dan translasi terbaru dari [Official Dokumentasi - Bahasa Inggris](https://www.tensorflow.org/?hl=en) karena komunitas translasi ini adalah usaha terbaik dari komunitas translasi.
Jika Anda memiliki saran untuk meningkatkan terjemahan ini, silakan kirim pull request ke [tensorflow/docs](https://github.com/tensorflow/docs) repositori GitHub.
Untuk menjadi sukarelawan untuk menulis atau memeriksa terjemahan komunitas, hubungi
[daftar docs@tensorflow.org](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs).
Ini adalah file notebook [Google Colaboratory](https://colab.research.google.com/notebooks/welcome.ipynb). Program python akan dijalankan langsung dari browser — cara yang bagus untuk mempelajari dan menggunakan TensorFlow. Untuk mengikuti tutorial ini, jalankan notebook di Google Colab dengan mengklik tombol di bagian atas halaman ini.
1. Di halaman Colab, sambungkan ke runtime Python: Di menu sebelah kanan atas, pilih * CONNECT *.
2. Untuk menjalankan semua sel kode pada notebook: Pilih * Runtime *> * Run all *.
Download dan instal TensorFlow 2 dan impor TensorFlow ke dalam program Anda:
```
try:
# %tensorflow_version hanya ada di Colab.
%tensorflow_version 2.x
except Exception:
pass
```
Impor TensorFlow ke dalam program Anda:
```
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model
```
Siapkan [dataset MNIST](http://yann.lecun.com/exdb/mnist/).
```
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# Tambahkan dimensi chanel
x_train = x_train[..., tf.newaxis]
x_test = x_test[..., tf.newaxis]
```
Gunakan `tf.data` untuk mengelompokkan dan mengatur kembali dataset:
```
train_ds = tf.data.Dataset.from_tensor_slices(
(x_train, y_train)).shuffle(10000).batch(32)
test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)
```
Buat model `tf.keras` menggunakan Keras [model subclassing API](https://www.tensorflow.org/guide/keras#model_subclassing):
```
class MyModel(Model):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = Conv2D(32, 3, activation='relu')
self.flatten = Flatten()
self.d1 = Dense(128, activation='relu')
self.d2 = Dense(10, activation='softmax')
def call(self, x):
x = self.conv1(x)
x = self.flatten(x)
x = self.d1(x)
return self.d2(x)
# Buat sebuah contoh dari model
model = MyModel()
```
Pilih fungsi untuk mengoptimalkan dan fungsi untuk menilai loss dari hasil pelatihan:
```
loss_object = tf.keras.losses.SparseCategoricalCrossentropy()
optimizer = tf.keras.optimizers.Adam()
```
Pilih metrik untuk mengukur loss dan keakuratan model. Metrik ini mengakumulasi nilai di atas epochs dan kemudian mencetak hasil secara keseluruhan.
```
train_loss = tf.keras.metrics.Mean(name='train_loss')
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')
test_loss = tf.keras.metrics.Mean(name='test_loss')
test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')
```
Gunakan `tf.GradientTape` untuk melatih model:
```
@tf.function
def train_step(images, labels):
with tf.GradientTape() as tape:
predictions = model(images)
loss = loss_object(labels, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
train_loss(loss)
train_accuracy(labels, predictions)
```
Tes modelnya:
```
@tf.function
def test_step(images, labels):
predictions = model(images)
t_loss = loss_object(labels, predictions)
test_loss(t_loss)
test_accuracy(labels, predictions)
EPOCHS = 5
for epoch in range(EPOCHS):
for images, labels in train_ds:
train_step(images, labels)
for test_images, test_labels in test_ds:
test_step(test_images, test_labels)
template = 'Epoch {}, Loss: {}, Accuracy: {}, Test Loss: {}, Test Accuracy: {}'
print(template.format(epoch+1,
train_loss.result(),
train_accuracy.result()*100,
test_loss.result(),
test_accuracy.result()*100))
# Menghitung ulang metrik untuk epoch selanjutnya
train_loss.reset_states()
train_accuracy.reset_states()
test_loss.reset_states()
test_accuracy.reset_states()
```
Penggolong gambar tersebut, sekarang dilatih untuk akurasi ~ 98% pada dataset ini. Untuk mempelajari lebih lanjut, baca [tutorial TensorFlow](https://www.tensorflow.org/tutorials/).
| github_jupyter |
```
%matplotlib inline
import functools
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpy as np
from jax.scipy.special import expit
from jax.scipy.stats import bernoulli, norm
from samplers import get_min_ess, make_samplers
@jax.jit
def joint_energy(q_hmc, q_other):
return (
-norm.logpdf(q_hmc[0])
- norm.logpdf(q_hmc[1], loc=q_hmc[0], scale=0.04)
- jnp.sum(bernoulli.logpmf(q_other, p=expit(-q_hmc[0])))
)
@jax.jit
def sample_q_other(q_hmc, key):
key, subkey = jax.random.split(key)
q_other = jax.random.bernoulli(subkey, p=expit(-q_hmc[0]), shape=(20,))
return q_other, key
(
mala_within_gibbs,
hmc_within_gibbs,
mahmc_within_gibbs,
mala_persistent_within_gibbs,
mala_persistent_nonreversible_within_gibbs,
) = make_samplers(joint_energy, sample_q_other)
n_samples, n_warm_up_samples = int(1e6), int(1e5)
L = 10
n_chains = 16
```
# MALA within Gibbs
```
epsilon = 0.03
@jax.jit
@functools.partial(jax.vmap, in_axes=(0, None), out_axes=0)
def get_mala_within_gibbs_samples(key, epsilon):
def scan_f(carry, ii):
uv, w, key = carry
uv, w, key, accept = mala_within_gibbs(uv, w, key, epsilon, L)
return (uv, w, key), (uv, w, accept)
key, subkey = jax.random.split(key)
uv = jax.random.normal(subkey, shape=(2,))
uv = uv.at[1].set((uv[1] + uv[0]) * 0.04)
key, subkey = jax.random.split(key)
w = jax.random.bernoulli(subkey, shape=(20,))
_, samples = jax.lax.scan(scan_f, (uv, w, key), jnp.arange(n_samples))
samples = jax.tree_util.tree_map(lambda x: x[n_warm_up_samples:], samples)
return samples
key = jax.random.PRNGKey(np.random.randint(int(1e5)))
keys = jax.random.split(key, n_chains)
samples = get_mala_within_gibbs_samples(keys, epsilon)
print(
f"""
### MALA-within-Gibbs, epsilon: {epsilon}
u_ess: {get_min_ess(samples[0].copy()[..., [0]])}
acceptance: {np.mean(samples[2])}
"""
)
fig, ax = plt.subplots(1, 1, figsize=(10, 10))
ax.hist(samples[0][0, ..., 0].copy(), bins=200, density=True)
x = np.linspace(-5, 5, int(1e5))
ax.plot(x, norm.pdf(x))
```
# HMC-within-Gibbs
```
N = 4
epsilon = 0.035
@functools.partial(jax.jit, static_argnames="N")
@functools.partial(jax.vmap, in_axes=(0, None, None), out_axes=0)
def get_hmc_within_gibbs_samples(key, N, epsilon):
def scan_f(carry, ii):
uv, w, key = carry
uv, w, key, accept = hmc_within_gibbs(uv, w, key, epsilon, L * N)
return (uv, w, key), (uv, w, accept)
key, subkey = jax.random.split(key)
uv = jax.random.normal(subkey, shape=(2,))
uv = uv.at[1].set((uv[1] + uv[0]) * 0.04)
key, subkey = jax.random.split(key)
w = jax.random.bernoulli(subkey, shape=(20,))
_, samples = jax.lax.scan(scan_f, (uv, w, key), jnp.arange(n_samples))
samples = jax.tree_util.tree_map(lambda x: x[n_warm_up_samples:], samples)
return samples
key = jax.random.PRNGKey(np.random.randint(int(1e5)))
keys = jax.random.split(key, n_chains)
samples = get_hmc_within_gibbs_samples(keys, N, epsilon)
print(
f"""
### HMC-within-Gibbs, N: {N}, epsilon: {epsilon}
u_ess: {get_min_ess(samples[0].copy()[..., [0]]) / N}
acceptance: {np.mean(samples[2])}
"""
)
fig, ax = plt.subplots(1, 1, figsize=(10, 10))
ax.hist(samples[0][0, ..., 0].copy(), bins=200, density=True)
x = np.linspace(-5, 5, int(1e5))
ax.plot(x, norm.pdf(x))
```
# MAHMC
```
N = 10
epsilon = 0.04
@functools.partial(jax.jit, static_argnames="N")
@functools.partial(jax.vmap, in_axes=(0, None, None), out_axes=0)
def get_mahmc_within_gibbs_samples(key, N, epsilon):
def scan_f(carry, ii):
uv, w, key = carry
uv, w, key, accept = mahmc_within_gibbs(uv, w, key, epsilon, L, N)
return (uv, w, key), (uv, w, accept)
key, subkey = jax.random.split(key)
uv = jax.random.normal(subkey, shape=(2,))
uv = uv.at[1].set((uv[1] + uv[0]) * 0.04)
key, subkey = jax.random.split(key)
w = jax.random.bernoulli(subkey, shape=(20,))
_, samples = jax.lax.scan(scan_f, (uv, w, key), jnp.arange(n_samples))
samples = jax.tree_util.tree_map(lambda x: x[n_warm_up_samples:], samples)
return samples
key = jax.random.PRNGKey(np.random.randint(int(1e5)))
keys = jax.random.split(key, n_chains)
samples = get_mahmc_within_gibbs_samples(keys, N, epsilon)
print(
f"""
### MAHMC-within-Gibbs, N: {N}, epsilon: {epsilon}
u_ess: {get_min_ess(samples[0].copy()[..., [0]]) / N}
acceptance: {np.mean(samples[2])}
"""
)
fig, ax = plt.subplots(1, 1, figsize=(10, 10))
ax.hist(samples[0][0, ..., 0].copy(), bins=200, density=True)
x = np.linspace(-5, 5, int(1e5))
ax.plot(x, norm.pdf(x))
```
# MALA with persistent momentum
```
epsilon = 0.03
alpha = 0.995
@jax.jit
@functools.partial(jax.vmap, in_axes=(0, None, None), out_axes=0)
def get_mala_persistent_within_gibbs_samples(key, epsilon, alpha):
def scan_f(carry, ii):
uv, p, w, key = carry
uv, p, w, key, accept = mala_persistent_within_gibbs(
uv, p, w, key, epsilon, L, alpha
)
return (uv, p, w, key), (uv, w, accept)
key, subkey = jax.random.split(key)
uv = jax.random.normal(subkey, shape=(2,))
uv = uv.at[1].set((uv[1] + uv[0]) * 0.04)
key, subkey = jax.random.split(key)
w = jax.random.bernoulli(subkey, shape=(20,))
key, subkey = jax.random.split(key)
p = jax.random.normal(subkey, shape=uv.shape)
_, samples = jax.lax.scan(scan_f, (uv, p, w, key), jnp.arange(n_samples))
samples = jax.tree_util.tree_map(lambda x: x[n_warm_up_samples:], samples)
return samples
key = jax.random.PRNGKey(np.random.randint(int(1e5)))
keys = jax.random.split(key, n_chains)
samples = get_mala_persistent_within_gibbs_samples(keys, epsilon, alpha)
print(
f"""
### MALA-P-within-Gibbs, epsilon: {epsilon}, alpha: {alpha}
u_ess: {get_min_ess(samples[0].copy()[..., [0]])}
acceptance: {np.mean(samples[2])}
"""
)
fig, ax = plt.subplots(1, 1, figsize=(10, 10))
ax.hist(samples[0][0, ..., 0].copy(), bins=200, density=True)
x = np.linspace(-5, 5, int(1e5))
ax.plot(x, norm.pdf(x))
```
# MALA with persistent momentum and non-reversible Metropolis accept/reject
```
epsilon = 0.03
alpha = 0.995
delta = 0.01
@jax.jit
@functools.partial(jax.vmap, in_axes=(0, None, None, None), out_axes=0)
def get_mala_persistent_nonreversible_within_gibbs_samples(key, epsilon, alpha, delta):
def scan_f(carry, ii):
uv, p, w, v, key = carry
uv, p, w, v, key, accept = mala_persistent_nonreversible_within_gibbs(
uv, p, w, v, key, epsilon, L, alpha, delta
)
return (uv, p, w, v, key), (uv, w, accept)
key, subkey = jax.random.split(key)
uv = jax.random.normal(subkey, shape=(2,))
uv = uv.at[1].set((uv[1] + uv[0]) * 0.04)
key, subkey = jax.random.split(key)
w = jax.random.bernoulli(subkey, shape=(20,))
key, subkey = jax.random.split(key)
p = jax.random.normal(subkey, shape=uv.shape)
key, subkey = jax.random.split(key)
v = jax.random.uniform(subkey) * 2 - 1
_, samples = jax.lax.scan(scan_f, (uv, p, w, v, key), jnp.arange(n_samples))
samples = jax.tree_util.tree_map(lambda x: x[n_warm_up_samples:], samples)
return samples
key = jax.random.PRNGKey(np.random.randint(int(1e5)))
keys = jax.random.split(key, n_chains)
samples = get_mala_persistent_nonreversible_within_gibbs_samples(
keys, epsilon, alpha, delta
)
print(
f"""
### MALA-P-N-within-Gibbs, epsilon: {epsilon}, alpha: {alpha}, delta: {delta}
u_ess: {get_min_ess(samples[0].copy()[..., [0]])}
acceptance: {np.mean(samples[2])}
"""
)
fig, ax = plt.subplots(1, 1, figsize=(10, 10))
ax.hist(samples[0][0, ..., 0].copy(), bins=200, density=True)
x = np.linspace(-5, 5, int(1e5))
ax.plot(x, norm.pdf(x))
```
| github_jupyter |
```
import delfi.distribution as dd
import delfi.generator as dg
import delfi.inference as infer
import delfi.utils.io as io
import delfi.summarystats as ds
import model.utils as utils
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pickle
from delfi.simulator import TransformedSimulator
from delfi.utils.bijection import named_bijection
from model.HodgkinHuxley import HodgkinHuxley
from model.HodgkinHuxleyStatsMoments import HodgkinHuxleyStatsMoments
import sys; sys.path.append('../')
from common import plot_pdf, samples_nd, col, svg
%matplotlib inline
!mkdir -p support_files
seed = 1
pilot_samples = 1000
n_sims = 100000
n_rounds = 1
n_components = 2
n_hiddens = [50]*2
n_xcorr = 0
n_mom = 4
n_summary = 7
summary_stats = 1
true_params, labels_params = utils.obs_params(reduced_model=False)
I, t_on, t_off, dt = utils.syn_current()
obs = utils.syn_obs_data(I, dt, true_params, seed=seed, cython=True)
obs_stats = utils.syn_obs_stats(data=obs,I=I, t_on=t_on, t_off=t_off, dt=dt, params=true_params,
seed=seed, n_xcorr=n_xcorr, n_mom=n_mom, cython=True,
summary_stats=summary_stats,n_summary=n_summary)
p = utils.prior(true_params=true_params, prior_uniform=True,
prior_extent=True, prior_log=False, seed=seed)
n_processes = 5
seeds_model = np.arange(1,n_processes+1,1)
m = []
for i in range(n_processes):
sim = HodgkinHuxley(I, dt, V0=obs['data'][0], reduced_model=False, seed=seeds_model[i], cython=True, prior_log=False)
m.append(sim)
n_summary_ls = [7, 4, 1]
g_ls = []
for nsum in n_summary_ls:
stats = HodgkinHuxleyStatsMoments(t_on=t_on, t_off=t_off, n_xcorr=n_xcorr, n_mom=n_mom, n_summary=nsum)
g = dg.MPGenerator(models=m, prior=p, summary=stats)
g_ls.append(g)
density = 'maf' # 'mog' or 'maf'
for i, nsum in enumerate(n_summary_ls):
res = infer.APT(
g_ls[i],
obs=obs_stats[0, 0:nsum],
pilot_samples=pilot_samples,
n_hiddens=n_hiddens,
seed=seed,
n_mades=5,
prior_norm=True,
impute_missing=False,
density=density,
)
log, train_data, posterior = res.run(
n_train=n_sims,
n_rounds=n_rounds,
minibatch=500,
epochs=1000,
silent_fail=False,
proposal='mog',
val_frac=0.1,
monitor_every=1,
)
filename = './results/posterior_{nsum}_single_round_{density}_lfs.pkl'.format(density=density, nsum=nsum)
io.save_pkl((log, train_data, posterior), filename)
filename = './results/posterior_{nsum}_single_round_{density}_res_lfs.pkl'.format(density=density, nsum=nsum)
io.save(res, filename)
```
| github_jupyter |
# Odds of Winning the TOTO Prize
---
## Introduction:
This project aims to help TOTO lottery addicts better estimate their chances of winning.
The project will build functions that enable users to answer questions like:
- *What is the probability of winning the Jackpot prize with a single ticket?*
- *What is the probability of winning the Jackpot prize if we play 50 different tickets (or any other number)?*
- *What is the probability of having at least five (or four, or three) winning numbers on a single ticket?*
The scenario we're following throughout this project is fictional — the main purpose is to practice applying the concepts learned in a setting that simulates a real-world scenario. Throughout the project, we'll need to calculate repeatedly probabilities and combinations.
## Core Functions
We will build the core functions required to be used in our programs to calculate factorial and combinations.
Before that, let's recap on the following concepts.
#### Permutation
Permutation is referring to certain arrangement where the order of the individual elements are important.
For example, a 3-digit PIN code have 10x10x10=1000 permutations. This means we can have, let's say PIN code `377`, which is not the same as `773` or `737`.
If we do sampling without replacement (i.e. no repetition of elements), the number of permutations or different arrangements that we can get from a set of 5 items are 5x4x3x2x1=120. This is represented as `5!` (meaning 5 factorial).
However, if we were asked to choose 2 out of 5 items, then we will have 5x4=20 permutations.
This is represented as <sub>n</sub>P<sub>k</sub> in the formula below, where in this case: n=5, k=2.

#### Combination
Combination is referring to arrangements where the order doesn't matter.
This is represented as <sub>n</sub>C<sub>k</sub> in the formula below, which we’re reading as “n choose k”.

In this example, “5 choose 2”, or <sub>5</sub>C<sub>2</sub> will have 10 combinations.
#### Probability of Events
Take the example of rolling a die, where the set of all possible outcomes, or the sample space of a die roll, Ω = {1,2,3,4,5,6}.
In this example, let's consider the event E as "*getting an even number when rolling a die*". Thus an outcome for event E is considered as *successful outcome* if it is 2, 4, or 6.
The probability of event E, denoted by *P(E)*, is

```
### Function to calculate factorials (to find the total number of permutations for sample without replacement)
def factorial(n):
product = 1
for i in range(n, 0, -1):
product = product * i
return product
### Function to return the number of combinations when we're taking only k objects from a group of n objects.
def combinations(n, k):
numerator = factorial(n)
denominator = factorial(k) * factorial(n-k)
return numerator/denominator
```
## One-Ticket Probability of Winning the Jackpot Prize
We will write a function that calculates the probability of winning the TOTO Jackpot prize.
In the TOTO lottery, six Winning Numbers and one Additional Number are drawn from 49 numbers that range from 1 to 49. A player wins the Jackpot prize if the six numbers on their tickets match all the six Winning Numbers drawn. If a player has a ticket with the numbers {13, 22, 24, 27, 42, 44}, he only wins the Jackpot prize if the Winning Numbers drawn are {13, 22, 24, 27, 42, 44}.
We want players to be able to know the probability of winning the Jackpot prize with the various numbers they play on a single ticket (for each ticket a player chooses six numbers out of 49). So, we'll start by building a function that calculates the probability of winning the Jackpot prize for any given ticket.
```
### The function takes in a list of six unique numbers and prints the probability of winning.
def one_ticket_probability(list_of_6_numbers):
### Start by calculating the total number of possible outcomes — this is total number of combinations
### for a six-number lottery ticket.
### There are 49 possible numbers, and six numbers are sampled without replacement.
n_combinations = combinations(49, 6)
### Probability of one successful outcome (i.e. 1 ticket).
p_one_ticket = 1 / n_combinations
### Convert the probability to percentage.
percent = p_one_ticket * 100
### Print the result in a friendly way.
template = """Your chances to win the Jackpot prize with the numbers {input} are {num1:.7f}%.
In other words, you have a 1 in {num2:,} chances to win."""
output = template.format(input=list_of_6_numbers, num1=percent, num2=int(n_combinations))
print(output)
### Testing the function with sample input.
input_1 = [3, 49, 7, 2, 6, 9]
one_ticket_probability(input_1)
### Testing the function with another sample input.
input_2 = [3, 8, 7, 45, 6, 35]
one_ticket_probability(input_2)
```
## Historical Data Check for TOTO Lottery
We will also build a function to allow users to compare their ticket against the historical TOTO lottery data and determine whether they would have ever won by now.
Below we will be exploring the historical data coming from the TOTO lottery for over a thousand drawings (each row shows data for a single drawing), dating from 3 Jul 2008. For each drawing, we can find the six Winning Numbers drawn in the following six columns:
- Winning Number 1
- 2
- 3
- 4
- 5
- 6
The data set can be found on [Lottolyzer](https://en.lottolyzer.com/history/singapore/toto/) and it has the following structure as shown below.
```
import pandas as pd
pd.options.display.max_columns = 50 ### to avoid truncated output.
pd.options.display.max_rows = 20
url="https://en.lottolyzer.com/history-export-csv/singapore/toto/ToTo.csv"
data = pd.read_csv(url)
### Get the number of rows and columns.
data.shape
### Explore the first 3 rows of data.
data.head(3)
### Explore the last 3 rows of data.
data.tail(3)
```
## Function for Historical Data Check
Below we're writing the function that will enable users to compare their ticket against the historical TOTO lottery data and determine whether they would have ever won by now.
```
### Function to extract all the winning six numbers from the historical data set as Python sets.
def extract_numbers(row):
### Get data from column index 2 to 7 (i.e. columns for 'Winning Number 1', '2', ... to '6').
row = row[2:8]
### Convert the values to 'set' datatype, i.e. a collection of unique items which is unordered and unindexed.
### The major advantage of using a set, as opposed to a list, is that it has a highly optimized method
### for checking whether a specific element is contained in the set.
row = set(row.values)
return row
### Apply the function to every row of the dataset (axis=1) to extract all the Winning Numbers.
winning_numbers = data.apply(extract_numbers, axis=1)
### Preview of the first 5 rows of the Winning Numbers.
winning_numbers.head()
### Function that takes in two inputs:
### - a Python list containing the user numbers
### - and a pandas Series containing sets with the Winning Numbers
def check_historical_occurence(list_of_6_numbers, series_of_winning_numbers):
### Convert the user numbers list as a set.
input_numbers = set(list_of_6_numbers)
### Compare the set against the pandas Series that contains the sets with the Winning Numbers to find the number of matches.
### A Series of Boolean values will be returned as a result of the comparison.
matches = series_of_winning_numbers == input_numbers
### Sum the matches to get the number of times the matches has occurred.
total_matches = matches.sum()
### Print information about the number of times the combination inputted by the user occurred in the past.
template = "This combination of numbers {input} has occurred {num1} time(s) as Winning Numbers in the past."
output = template.format(input=list_of_6_numbers, num1=int(total_matches))
print(output)
if total_matches == 0:
print("This doesn't mean it's more likely to occur now.")
print('\nIn the next drawing:')
### Call the one_ticket_probability() function again to print the probability of winning the Jackpot prize
### in the next drawing with that combination.
one_ticket_probability(list_of_6_numbers)
### Test the check_historical_occurence() function.
check_historical_occurence([2, 41, 11, 12, 43, 14], winning_numbers)
### Test the check_historical_occurence() function again with a known Winning Number.
check_historical_occurence([6, 11, 14, 15, 28, 45], winning_numbers)
```
## Multi-Ticket Probability of Winning the Jackpot Prize
Lottery addicts usually play more than one ticket on a single drawing, thinking that this might increase their chances of winning significantly. Our purpose is to help them better estimate their chances of winning — here, we're going to write a function that will calculate the chances of winning for any number of different tickets.
```
### A function that prints the probability of winning the Jackpot prize depending on the number of different tickets played.
def multi_ticket_probability(n_tickets):
### Start by calculating the total number of possible outcomes — this is total number of combinations
### for a six-number lottery ticket.
### There are 49 possible numbers, and six numbers are sampled without replacement.
n_combinations = combinations(49, 6)
### Calculate the probability of winning the Jackpot prize based on the number of tickets.
p_n_tickets = n_tickets / n_combinations
### Convert the probability to percentage.
percent = p_n_tickets * 100
### Print the result in a friendly way.
if n_tickets == 1:
template = """Your chances to win the Jackpot prize with {input:,} ticket are {num1:.7f}%.
In other words, you have a 1 in {num2:,} chances to win."""
else:
template = """Your chances to win the Jackpot prize with {input:,} different tickets are {num1:.7f}%.
In other words, you have a 1 in {num2:,} chances to win."""
output = template.format(input=n_tickets, num1=percent, num2=round(n_combinations/n_tickets))
print(output)
### Test the above function using the following test inputs.
number_of_tickets = [1, 10, 100, 10000, 1000000, 6991908, 13983816]
for n in number_of_tickets:
multi_ticket_probability(n)
print('-----------------------------------------------------------------------------------------')
```
## Less Winning Numbers - Probability of Winning Smaller Prizes
For extra context, in [TOTO](https://online.singaporepools.com/en/lottery/toto-statistics-history) lottery there are smaller prizes if a player's ticket match three, four, or five of the six Winning Numbers drawn (or also match the Additional Number drawn). As a consequence, the users might be interested in knowing the probability of having three, four, or five Winning Numbers.
- Group 2 Prize: Matching 5 Winning Numbers + Additional Number
- Group 3 Prize: Matching 5 Winning Numbers
- Group 4 Prize: Matching 4 Winning Numbers + Additional Number
- Group 5 Prize: Matching 4 Winning Numbers
- Group 6 Prize: Matching 3 Winning Numbers + Additional Number
- Group 7 Prize: Matching 3 Winning Numbers
Below are functions to allow users to calculate probabilities for three, four, or five Winning Numbers (for Group 3, 5, and 7 Prizes), and also with matching the Additional Number (for Group 2, 4, and 6 Prizes).
```
### A function which takes in an integer n (value between 3 and 5) and prints information about the chances of winning
### the Group 3, Group 5, or Group 7 prize, depending on the value of that integer.
def probability_win_group357(n):
### Calculate the number of successful outcomes given the value of the input.
### Find the total number of n-number combinations from the set of 6 numbers (i.e. 6 choose n)
combinations_n = combinations(6, n)
### Find the remaining number of combinations (i.e. 42 choose 6-n).
### Note: 42 is used instead of 43 because there is one number drawn for Additional Number.
combinations_remaining = combinations(49-6-1, 6-n)
### Calculate the total number of successful outcomes.
### (Imagine if n=3, we need to find combination from the ticket [6 choose 3] and the remaining combination [42 choose 3]).
### (Imagine if n=4, we need to find combination from the ticket [6 choose 4] and the remaining combination [42 choose 2]).
### (Imagine if n=5, we need to find combination from the ticket [6 choose 5] and the remaining combination [42 choose 1]).
total_successful_outcome = (combinations_n * combinations_remaining)
### Get the total possible outcomes from [49 choose 6] for Winning Numbers.
total_possible_outcome = combinations(49, 6)
### Calculate the probability
probability = total_successful_outcome / total_possible_outcome
percent = probability * 100
template = """Your chances of having {input} Winning Numbers with this ticket are {num1:.7f}%.
In other words, you have a 1 in {num2:,} chances to win."""
output = template.format(input=n, num1=percent, num2=int(round(total_possible_outcome / total_successful_outcome)))
print(output)
### A function which takes in an integer n (value between 3 and 5) and prints information about the chances of winning
### the Group 2, Group 4, or Group 6 prize, depending on the value of that integer.
def probability_win_group246(n):
### Calculate the number of successful outcomes given the value of the input.
### Find the total number of n-number combinations from the set of 6 numbers (i.e. 6 choose n)
combinations_n = combinations(6, n)
### Find the remaining number of combinations (i.e. 42 choose 6-n-1).
### Note: 42 is used instead of 43 because there is one number drawn for Additional Number.
combinations_remaining1 = combinations(49-6-1, 6-n-1)
### Combination [1 choose 1] is referring to the Additonal Number.
combinations_remaining2 = combinations(1, 1)
### Calculate the total number of successful outcomes.
### (Imagine if n=3, find combination from the ticket [6 choose 3] and remaining combination [42 choose 2] and [1 choose 1]).
### (Imagine if n=4, find combination from the ticket [6 choose 4] and remaining combination [42 choose 1] and [1 choose 1]).
### (Imagine if n=5, find combination from the ticket [6 choose 5] and remaining combination [42 choose 0] and [1 choose 1]).
total_successful_outcome = (combinations_n * combinations_remaining1 * combinations_remaining2)
### Get the total possible outcomes from [49 choose 6] for Winning Numbers and [43 choose 1] for the Additional Number.
total_possible_outcome = combinations(49, 6) + combinations(43, 1)
### Calculate the probability
probability = total_successful_outcome / total_possible_outcome
percent = probability * 100
template = """Your chances of having {input} Winning Numbers + Additional Number with this ticket are {num1:.7f}%.
In other words, you have a 1 in {num2:,} chances to win."""
output = template.format(input=n, num1=percent, num2=int(round(total_possible_outcome / total_successful_outcome)))
print(output)
### Test the above functions using the following test inputs.
test_inputs = [3, 4, 5]
for n in test_inputs:
probability_win_group357(n)
print('------------------------------------------------------------------------------------------')
probability_win_group246(n)
print('------------------------------------------------------------------------------------------')
```
**Interested to view the frequencies of numbers drawn and the top 20 Jackpot prizes?**
**[Click here](https://public.tableau.com/profile/peggy.chang#!/vizhome/TOTOLottery/S1) to check out these visualizations created with Tableau Public.**

| github_jupyter |
# Get Lexicon
For the `20210515` run, we just used re-used the lexicon from `20200224`. Also, we didn't try filtering out non-human pathways this time, unlike the process we used for `20200224`, where we excluded figures from papers where PubTator had identified at least one species and none of those species were human or mouse.
For the next run, it would be good to finish this notebook to get an updated lexicon and get species information for the papers. [The notes from our old codebook](https://github.com/wikipathways/pathway-figure-ocr/blob/76ae219e65bcc723bbeaa3b82744b4aec78fc9d7/codebook.md#generating-files-and-initial-tables) may be useful for how to do this.
```
%load_ext sql
import csv
import hashlib
import io
import json
import os
import re
import subprocess
import sys
import warnings
from itertools import zip_longest
from pathlib import Path, PurePath
from pprint import pprint
import numpy as np
import pandas as pd
import requests
import requests_cache
import seaborn as sns
# from wand.image import Image
from IPython.display import Image
from nltk.metrics import edit_distance
target_date = "20210513"
images_dir = Path(f"../data/images/{target_date}")
```
## Old Lexicon
```
%sql postgresql:///pfocr20200224
%%sql lexicon2020 << SELECT symbol, xref as ncbigene_id, source
FROM lexicon
INNER JOIN xrefs ON lexicon.xref_id = xrefs.id
INNER JOIN symbols ON lexicon.symbol_id = symbols.id;
lexicon2020_df = lexicon2020.DataFrame()
lexicon2020_df
with open(images_dir.joinpath("lexicon2020.json"), "w") as f:
lexicon2020_df.to_json(f)
```
## Updated Lexicon
I'm trying to translate [these steps](https://github.com/wikipathways/pathway-figure-ocr/blob/7b34d23982c7812ec98256ab1caf8c6ca3abccbb/codebook.md#generating-files-and-initial-tables) into Python in order to build a list of gene symbols to look for in the OCR text, but I haven't finished this yet. Status of the three main sources:
- HGNC: done
- bioentities: in progress
- WikiPathways: not yet started
For the bioentities file, it appears there are inconsistencies in mapping bioentities to NCBI Gene IDs. See that section below for more details.
```
print(requests_cache.__file__)
requests_cache.install_cache("pfocr_cache")
%load_ext sql
sns.set_style("dark")
import Levenshtein
import Levenshtein_search
import polyleven
```
## HGNC
```
hgnc_data_url = "https://www.genenames.org/cgi-bin/download/custom?col=gd_hgnc_id&col=gd_app_sym&col=gd_app_name&col=gd_status&col=gd_prev_sym&col=gd_aliases&col=gd_pub_acc_ids&col=gd_locus_type&col=gd_date_mod&col=family.id&col=gd_locus_group&col=gd_name_aliases&col=gd_date_sym_change&col=gd_pub_eg_id&col=family.name&col=gd_date_name_change&col=gd_prev_name&col=gd_date2app_or_res&status=Approved&hgnc_dbtag=on&order_by=gd_app_sym_sort&format=text&submit=submit"
hgnc_data = []
r = requests.get(hgnc_data_url, stream=True)
for record in csv.DictReader(
(line.decode("utf-8") for line in r.iter_lines()), delimiter="\t"
):
hgnc_data.append(record)
print(len(hgnc_data))
hgnc_data[:2]
raw_hgnc_df = (
pd.DataFrame(hgnc_data)[
[
"HGNC ID",
"NCBI Gene ID",
# "Status",
"Approved symbol",
"Approved name",
"Alias symbols",
"Alias names",
"Previous symbols",
"Previous name",
]
]
.rename(
columns={
"HGNC ID": "hgnc_id",
"NCBI Gene ID": "ncbigene_id",
"Approved symbol": "approved_symbol",
"Approved name": "approved_name",
"Alias symbols": "alias_symbols",
"Alias names": "alias_names",
"Previous symbols": "previous_symbols",
"Previous name": "previous_name",
}
)
.replace("", np.nan)
)
print(len(raw_hgnc_df))
# raw_hgnc_df
```
"ambiguous symbols" are those that map to multiple ncbigene ids
- `94436` when keeping first approved ambiguous symbol
- `92535` when dropping all rows with ambiguous symbols
```
hgnc_df = raw_hgnc_df[raw_hgnc_df["ncbigene_id"].notnull()]
name_columns = ["approved_name", "previous_name", "alias_name"]
hgnc_df = (
hgnc_df.assign(
alias_symbol=hgnc_df["alias_symbols"].str.split(", "),
alias_name=hgnc_df["alias_names"].str.split(", "),
previous_symbol=hgnc_df["previous_symbols"].str.split(", "),
)
.explode("alias_symbol")
.explode("alias_name")
.explode("previous_symbol")
.drop(
columns=["alias_symbols", "alias_names", "previous_symbols"]
+ name_columns
)
.melt(
id_vars=["hgnc_id", "ncbigene_id"],
value_vars=["approved_symbol", "alias_symbol", "previous_symbol"],
var_name="source",
value_name="symbol",
)
.dropna()
# drop exact duplicates
.drop_duplicates()
)
hgnc_df = hgnc_df[
(hgnc_df["source"] == "approved_symbol")
| (hgnc_df["symbol"].str.len() >= 3)
]
variables_by_priority = {
"approved_symbol": 0,
"previous_symbol": 1,
"alias_symbol": 2,
}
hgnc_df["priority"] = hgnc_df["source"].apply(
lambda x: variables_by_priority[x]
)
# For rows with ambiguous symbols, keep the first for every symbol and drop the rest.
# Note the sorting is approved before previous before alias.
hgnc_df = (
hgnc_df.sort_values(by=["priority"])
.drop_duplicates(subset=["symbol"])
.drop(columns=["priority"])
)
# we don't want this
# drop all rows with ambiguous symbols
# hgnc_df = hgnc_df.drop_duplicates(subset=["value"], keep=False)
hgnc_df
```
## Bioentities
```
bioentities_data_url = "https://raw.githubusercontent.com/wikipathways/bioentities/master/relations.csv"
bioentities_data = []
r = requests.get(bioentities_data_url, stream=True)
for record in csv.DictReader(
(line.decode("utf-8") for line in r.iter_lines()),
fieldnames=["type", "symbol", "isa", "type2", "bioentity"],
):
bioentities_data.append(record)
bioentities_df = pd.DataFrame(bioentities_data)
# There are 9 entries from UP (UniProt). They are duplicates the HGNC entries, so we ignore them.
bioentities_df = (
bioentities_df[
bioentities_df["type"].isin(
{
"HGNC",
"BE",
}
)
]
).drop(columns=["isa", "type2"])
bioentities_df
```
There are no missing values:
```
print(bioentities_df.replace("", np.nan).isna().sum().sum())
bioentities_df.replace("", np.nan).isna().any()
joined_df = bioentities_df.merge(
hgnc_df[["ncbigene_id", "symbol"]], how="left", on="symbol"
)
joined_df
set(joined_df["type"].to_list())
joined_df[joined_df["ncbigene_id"].isnull()]
joined_df[joined_df["bioentity"] == "AMPK_alpha"]
joined_df[joined_df["symbol"] == "HSP90A"]
def get_hierarchy_levels(bioentity, hierarchy_levels=None):
# ******
# The bioentities appear to be at least sometimes in a hierarchical
# relationship. This function traces the path up the hierarchy for
# a bioentity in joined_df.
# ******
if not hierarchy_levels:
# make the trace include the lowest (first) item
hierarchy_levels = bioentity
# We're trying to go one level up the hierarchy.
# If this bioentity has a parent bioentity, then this bioentity will be
# listed as a symbol in a row where the parent bioentity is listed in the
# bioentity column. I don't know whether we should expect multiple results.
match_column = joined_df[joined_df["symbol"] == bioentity]["bioentity"]
if len(match_column) > 0:
ancestor = match_column.to_list()[0]
if ancestor in hierarchy_levels.split(","):
return hierarchy_levels
# TODO: when I use a list for hierarchy_levels, the column values in the df end
# up all being the same, but when I use a string, they each properly
# show the different trace for their specific row. Why?
# if ancestor in hierarchy_levels:
# return hierarchy_levels
# hierarchy_levels.insert(0, ancestor)
return get_hierarchy_levels(
ancestor, ",".join([ancestor, hierarchy_levels])
)
return hierarchy_levels
joined_df["hierarchy_levels"] = joined_df["bioentity"].apply(
# TODO: see comment in fn about str vs. list
lambda x: get_hierarchy_levels(x).split(",")
)
joined_df = joined_df.assign(
hierarchy_apex=joined_df["hierarchy_levels"].apply(lambda x: x[0]),
level_number=joined_df["hierarchy_levels"].apply(lambda x: len(x)),
)
joined_df
joined_df["level_number"].max()
joined_df[joined_df["level_number"] == 3]
```
I'm not sure how to interpret the following pattern in the bioentities, but it appears to be a mistake. As far as I can tell, `MAP2K`, `MAPKK` and `MEK` are synonyms, and every one of them each refers to the following collection of NCBI Gene IDs: `5604`, `5605`, `5606`, `5607`, `5608`, `5609`, `6416`. But `STAT` and `STAT5` are not synonyms. `STAT` refers to the NCBI Gene IDs `6772`, `6773`, `6774`, `6775`, `6776`, `6776`, `6777`, `6778`, but `STAT5` only refers to `6776` and `6777`.
In the df, we have the following `BE` relationships for rows with hierarchy apex `MAPKK`:
- `MAPKK` & `MAP2K`
- `MAP2K` & `MEK`
and for rows with hierarchy apex `STAT`:
- `STAT` & `STAT5`
If `BE` indicates synonyms, we get the correct results for `MAP2K`, `MAPKK` and `MEK` but the wrong results for `STAT` and `STAT5`.
```
joined_df[(joined_df["hierarchy_apex"] == "MAPKK")]
joined_df[
(joined_df["hierarchy_apex"] == "MAPKK") & (joined_df["type"] == "BE")
][["bioentity", "type", "symbol"]]
joined_df[(joined_df["hierarchy_apex"] == "MAPKK")][
"ncbigene_id"
].sort_values().dropna().to_list()
joined_df[(joined_df["hierarchy_apex"] == "STAT")]
joined_df[
(joined_df["hierarchy_apex"] == "STAT") & (joined_df["type"] == "BE")
][["bioentity", "type", "symbol"]]
joined_df[(joined_df["hierarchy_apex"] == "STAT")][
"ncbigene_id"
].sort_values().dropna().to_list()
```
## OLD
```
joined_df[(joined_df["bioentities"].str.startswith("STAT"))]
joined_df[(joined_df["bioentities"].str.startswith("STAT"))]
```
MAP2K == MEK == MAPKK
```
joined_df[
(joined_df["bioentities"] == "MAP2K")
| (joined_df["bioentities"] == "MAPKK")
| (joined_df["bioentities"] == "MEK")
| (joined_df["symbol"].str.startswith("MAP2K"))
| (joined_df["symbol"].str.startswith("MAPKK"))
| (joined_df["symbol"].str.startswith("MEK"))
]
joined_df[joined_df["bioentities"] == joined_df["top_ancestor"]]
joined_df[
(joined_df["genealogy"].str.contains(","))
& (joined_df["genealogy"].notnull())
]
i = 0
myd = dict()
for bioentities, df in joined_df[joined_df["type"] == "BE"].groupby(
"bioentities"
):
result = get_parents(bioentities)
if len(result) > 0:
print(result)
# print(bioentities)
# print(df)
# mysd = dict()
# myd["bioentities"] = mysd
# parent = joined_df[joined_df["symbol"] == bioentities]
# has_parent = len(parent) > 0
# print(has_parent)
# for s in df["symbol"].to_list():
# children = joined_df[joined_df["bioentities"] == s]
# mysd["children"] = children
# has_children = len(children) > 0
# print(has_children)
# # print(j)
# # print(s)
# # display(joined_df[joined_df["bioentities"] == s])
i += 1
if int(i) > 100:
break
multicol1 = pd.MultiIndex.from_tuples([("weight", "kg"), ("weight", "pounds")])
df_multi_level_cols1 = pd.DataFrame(
[[1, 2], [2, 4]], index=["cat", "dog"], columns=multicol1
)
df_multi_level_cols1
df_multi_level_cols1.stack()
multi_df = joined_df.copy().set_index(["bioentities", "symbol"])
multi_df
multi_df.loc["STAT"]
multi_df.columns
multi_df.index[0][0]
joined_df[joined_df["type"] == "BE"]
joined_df[(joined_df["ncbigene_id"].notnull()) & (joined_df["type"] == "BE")]
joined_df[joined_df["genealogy"].str.contains("Inhibin")]
joined_df[joined_df["genealogy"] == joined_df["bioentities"]]
joined_df[joined_df["genealogy"] == joined_df["bioentities"]]
joined_df[
(joined_df["bioentities"] == "Inhibin")
| (joined_df["bioentities"] == "inhibin")
| (joined_df["symbol"].str.startswith("Inhibin"))
| (joined_df["symbol"].str.startswith("INHBE"))
| (joined_df["symbol"].str.startswith("inhibin"))
]
joined_df[joined_df["symbol"].str.startswith("Activin")]
set(bioentities_df["type"].to_list())
bioentities_df[bioentities_df["type"] == "BE"]
bioentities_df[bioentities_df["bioentities"] == "CDKN"]
hgnc_df[hgnc_df["value"] == "CDKN1"]
ncbigene_ids_by_symbol = (
hgnc_df[["ncbigene_id", "value"]]
.set_index("value")
.to_dict()["ncbigene_id"]
)
hgnc_df[hgnc_df["hgnc"] == "HGNC:1784"]
bioentities_df[bioentities_df["symbol"] == "CDKN2"]
bioentities_df[bioentities_df["bioentities"] == "Activin"]
bioentities_df[bioentities_df["symbol"] == "Activin_A"]
bioentities_df[bioentities_df["type"] == "UP"]
bioentities_df[bioentities_df["type2"] == "UP"]
set(bioentities_df["type2"].to_list())
```
| github_jupyter |
<a href="https://colab.research.google.com/github/AuFeld/DS-Unit-4-Sprint-3-Deep-Learning/blob/master/module1-rnn-and-lstm/CG_DS_431_RNN_and_LSTM_Assignment.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
<img align="left" src="https://lever-client-logos.s3.amazonaws.com/864372b1-534c-480e-acd5-9711f850815c-1524247202159.png" width=200>
<br></br>
<br></br>
## *Data Science Unit 4 Sprint 3 Assignment 1*
# Recurrent Neural Networks and Long Short Term Memory (LSTM)

It is said that [infinite monkeys typing for an infinite amount of time](https://en.wikipedia.org/wiki/Infinite_monkey_theorem) will eventually type, among other things, the complete works of Wiliam Shakespeare. Let's see if we can get there a bit faster, with the power of Recurrent Neural Networks and LSTM.
This text file contains the complete works of Shakespeare: https://www.gutenberg.org/files/100/100-0.txt
Use it as training data for an RNN - you can keep it simple and train character level, and that is suggested as an initial approach.
Then, use that trained RNN to generate Shakespearean-ish text. Your goal - a function that can take, as an argument, the size of text (e.g. number of characters or lines) to generate, and returns generated text of that size.
Note - Shakespeare wrote an awful lot. It's OK, especially initially, to sample/use smaller data and parameters, so you can have a tighter feedback loop when you're trying to get things running. Then, once you've got a proof of concept - start pushing it more!
```
# installs
! pip install --upgrade tensorflow
# imports
import numpy as np
import random
import sys
import urllib.request
from tensorflow.keras.callbacks import LambdaCallback
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM
# read in data
full_text = []
url = "https://www.gutenberg.org/files/100/100-0.txt"
for line in urllib.request.urlopen(url):
full_text.append(line.decode('utf-8'))
# find last line of text
full_text[-435:-429]
# find first line of text
full_text[138:140]
# strip lines from remaining HTML characters
cleaned_full_text = []
for line in full_text[139:-430]:
cleaned_full_text.append(line.strip())
len(cleaned_full_text)
full_text[44:129:2]
# create titles data
titles = []
for line in full_text[44:129:2]:
titles.append(line.strip())
titles[0]
cleaned_full_text[2760:2770]
# seperate out sonnets
sonnets = []
for line in cleaned_full_text[:2767]:
sonnets.append(line)
sonnets[-1]
### use titles list to create first draft of model ###
# gather all text
text = " ".join(titles)
# create unique characters list
chars = list(set(text))
# create character lookup tables
char_int = {c:i for i, c in enumerate(chars)}
int_char = {i:c for i, c in enumerate(chars)}
len(chars)
# find average length of titles
lengths = []
sum_num = 0
for title in titles:
lengths.append(len(title))
for length in lengths:
sum_num += length
sum_num / len(lengths)
# create sequence data
maxlen = 25
step = 5
# create encoded data
encoded = [char_int[c] for c in text]
# create empty sequence and next character lists
sequences = []
next_char = []
# fill empty lists
for i in range(0, len(encoded) - maxlen, step):
sequences.append(encoded[i : i + maxlen])
next_char.append(encoded[i + maxlen])
print('Sequence Qty: ', len(sequences))
# one hot encode data to prepare for model
x = np.zeros((len(sequences), maxlen, len(chars)), dtype=np.bool)
y = np.zeros((len(sequences), len(chars)), dtype=np.bool)
for i, sequence in enumerate(sequences):
for t, char in enumerate(sequence):
x[i, t, char] = 1
y[i, next_char[i]] = 1
# build LSTM model
model = Sequential()
model.add(LSTM(128, input_shape=(maxlen, len(chars))))
model.add(Dense(len(chars), activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam')
model.summary()
# create functions to make use of model outputs
def indexer(preds):
# helper function to take highest probability and pull given index
preds = np.asarray(preds).astype('float64')
preds = np.log(preds) / 1
exp_preds = np.exp(preds)
preds = exp_preds / np.sum(exp_preds)
probas = np.random.multinomial(1, preds, 1)
return np.argmax(probas)
def on_epoch_end(epoch, _):
# function to generate predicted text at each epoch
print()
print('---- Generating text after Epoch: %d' % epoch)
start_index = random.randint(0, len(text) - maxlen - 1)
generated = ''
sentence = text[start_index: start_index + maxlen]
generated += sentence
print('---- Generating w/ seed: "' + sentence + '"')
# sys.stdout.write(generated)
for i in range(25):
x_pred = np.zeros((1, maxlen, len(chars)))
for t, char in enumerate(sentence):
x_pred[0, t, char_int[char]] = 1
preds = model.predict(x_pred, verbose=0)[0]
next_index = indexer(preds)
next_char = int_char[next_index]
sentence = sentence[1:] + next_char
sys.stdout.write(next_char)
sys.stdout.flush()
print()
print_callback = LambdaCallback(on_epoch_end=on_epoch_end)
# fit the model
model.fit(x, y,
batch_size=32,
epochs=100,
callbacks=[print_callback])
### try with sonnets ###
# gather all text
text = " ".join(sonnets)
# create unique character list
chars = list(set(text))
# create character lookup tables
char_int = {c:i for i, c in enumerate(chars)}
int_char = {i:c for i, c in enumerate(chars)}
len(chars)
# create sequence data
maxlen = 40
step = 5
# create encoded data
encoded = [char_int[c] for c in text]
# create empty sequence and next character lists
sequences = []
next_char = []
# fill empty lists
for i in range(0, len(encoded) - maxlen, step):
sequences.append(encoded[i : i + maxlen])
next_char.append(encoded[i + maxlen])
print('Sequence Qty: ', len(sequences))
# one hot encode data to prepare for model
x = np.zeros((len(sequences), maxlen, len(chars)), dtype=np.bool)
y = np.zeros((len(sequences), len(chars)), dtype=np.bool)
for i, sequence in enumerate(sequences):
for t, char in enumerate(sequence):
x[i, t, char] = 1
y[i, next_char[i]] = 1
# build LSTM model
model = Sequential()
model.add(LSTM(128, input_shape=(maxlen, len(chars))))
model.add(Dense(len(chars), activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam')
model.summary()
# create functions to make use of model outputs
def indexer(preds):
# helper function to take highest probability & pull given index
preds = np.asarray(preds).astype('float64')
preds = np.log(preds) / 1
exp_preds = np.exp(preds)
preds = exp_preds / np.sum(exp_preds)
probas = np.random.multinomial(1, preds, 1)
return np.argmax(probas)
def on_epoch_end(epoch, _):
# function to generate predicted text at each epoch
print()
print('---- Generating text after Epoch: %d' % epoch)
start_index = random.randint(0, len(text) - maxlen - 1)
generated = ''
sentence = text[start_index: start_index + maxlen]
generated += sentence
print('---- Generating with seed: "' + sentence + '"')
sys.stdout.write("\n")
print(' %d' % epoch)
sys.stdout.write(generated)
sys.stdout.write("\n")
for i in range(13):
for i in range(maxlen):
x_pred = np.zeros((1, maxlen, len(chars)))
for t, char in enumerate(sentence):
x_pred[0, t, char_int[char]] = 1
preds = model.predict(x_pred, verbose=0)[0]
next_index = indexer(preds)
next_char = int_char[next_index]
sentence = sentence[1:] + next_char
sys.stdout.write(next_char)
sys.stdout.flush()
sys.stdout.write("\n")
print()
print_callback = LambdaCallback(on_epoch_end=on_epoch_end)
# fit model
model.fit(x, y,
batch_size=32,
epochs=100,
callbacks=[print_callback])
```
# Resources and Stretch Goals
## Stretch goals:
- Refine the training and generation of text to be able to ask for different genres/styles of Shakespearean text (e.g. plays versus sonnets)
- Train a classification model that takes text and returns which work of Shakespeare it is most likely to be from
- Make it more performant! Many possible routes here - lean on Keras, optimize the code, and/or use more resources (AWS, etc.)
- Revisit the news example from class, and improve it - use categories or tags to refine the model/generation, or train a news classifier
- Run on bigger, better data
## Resources:
- [The Unreasonable Effectiveness of Recurrent Neural Networks](https://karpathy.github.io/2015/05/21/rnn-effectiveness/) - a seminal writeup demonstrating a simple but effective character-level NLP RNN
- [Simple NumPy implementation of RNN](https://github.com/JY-Yoon/RNN-Implementation-using-NumPy/blob/master/RNN%20Implementation%20using%20NumPy.ipynb) - Python 3 version of the code from "Unreasonable Effectiveness"
- [TensorFlow RNN Tutorial](https://github.com/tensorflow/models/tree/master/tutorials/rnn) - code for training a RNN on the Penn Tree Bank language dataset
- [4 part tutorial on RNN](http://www.wildml.com/2015/09/recurrent-neural-networks-tutorial-part-1-introduction-to-rnns/) - relates RNN to the vanishing gradient problem, and provides example implementation
- [RNN training tips and tricks](https://github.com/karpathy/char-rnn#tips-and-tricks) - some rules of thumb for parameterizing and training your RNN
| github_jupyter |
```
import sys
import os
sys.path.append(os.path.expanduser('~/workspace/tacotron/'))
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib import cm
from matplotlib.colors import ListedColormap
import numpy as np
import tensorflow as tf
FIGSIZE = (10, 6)
def get_losses(checkpoint, key='model/stats/loss'):
losses = []
# This example supposes that the events file contains summaries with a
# summary value tag 'loss'. These could have been added by calling
# `add_summary()`, passing the output of a scalar summary op created with
# with: `tf.scalar_summary(['loss'], loss_tensor)`.
summ_iter = tf.train.summary_iterator(checkpoint)
# infinite loop
while True:
try:
# get the next item
element = next(summ_iter)
# do something with element
for v in element.summary.value:
if v.tag == key:
losses.append(v.simple_value)
except tf.errors.DataLossError:
pass
except StopIteration:
# if StopIteration is raised, break from loop
break
return losses
tacotron_lj_loss = []
tacotron_lj_loss += get_losses('/media/josh/Store/remote-logs/tacotron-lj-500k/events.out.tfevents.1549319851.air208')
tacotron_lj_loss += get_losses('/media/josh/Store/remote-logs/tacotron-lj-500k/events.out.tfevents.1549531199.air208')
tacotron_lj_loss = np.array(tacotron_lj_loss)
tacotron_lj_loss.shape
tacotron_lj_pml_loss = []
tacotron_lj_pml_loss += get_losses('/media/josh/Store/remote-logs/tacotron-lj-pml-500k/events.out.tfevents.1547724814.air209')
tacotron_lj_pml_loss = np.array(tacotron_lj_pml_loss)
tacotron_lj_pmlx_loss = []
tacotron_lj_pmlx_loss += get_losses('/media/josh/Store/remote-logs/pmlx-lj-500k/events.out.tfevents.1551261505.air208', key='model/stats/loss_pml')
tacotron_lj_pmlx_loss += get_losses('/media/josh/Store/remote-logs/pmlx-lj-500k/events.out.tfevents.1551471596.air208', key='model/stats/loss_pml')
tacotron_lj_pmlx_loss += get_losses('/media/josh/Store/remote-logs/pmlx-lj-500k/events.out.tfevents.1551904223.air208', key='model/stats/loss_pml')
# tacotron_lj_pmlx_loss += get_losses('/media/josh/Store/remote-logs/pmlx-lj-500k/events.out.tfevents.1551977987.air208')
# tacotron_lj_pmlx_loss += get_losses('/media/josh/Store/remote-logs/pmlx-lj-500k/events.out.tfevents.1557985364.air208')
# tacotron_lj_pmlx_loss += get_losses('/media/josh/Store/remote-logs/pmlx-lj-500k/events.out.tfevents.1557999848.air208')
tacotron_lj_pmlx_loss = np.array(tacotron_lj_pmlx_loss)
tacotron_lj_pmlx_loss.shape
postnet_lj_loss = []
postnet_lj_loss += get_losses('/media/josh/Store/remote-logs/postnet-lj-500k/events.out.tfevents.1551261505.air208', key='model/stats/loss_pml')
postnet_lj_loss += get_losses('/media/josh/Store/remote-logs/postnet-lj-500k/events.out.tfevents.1551391258.air208', key='model/stats/loss_pml')
postnet_lj_loss = np.array(postnet_lj_loss)
postnet_lj_loss.shape
iter_counts = np.arange(0, tacotron_lj_loss.size) * 100
plt.figure(figsize=FIGSIZE)
plt.plot(iter_counts, tacotron_lj_loss)
plt.ylabel('Loss')
plt.xlabel('Iteration Count')
plt.title('Standard Tacotron Loss Curve')
plt.ylim(0.04, 0.20)
plt.show()
iter_counts = np.arange(0, tacotron_lj_pml_loss.size) * 100
plt.figure(figsize=FIGSIZE)
plt.plot(iter_counts, tacotron_lj_pml_loss)
plt.ylabel('Loss')
plt.xlabel('Iteration Count')
plt.title('Standard Tacotron Loss Curve')
plt.ylim(0.04, 0.20)
plt.show()
iter_counts = np.arange(0, tacotron_lj_pml_loss.size) * 100
pmlx_iter_counts = np.arange(0, tacotron_lj_pmlx_loss.size) * 100
postnet_iter_counts = np.arange(0, postnet_lj_loss.size) * 100
plt.figure(figsize=FIGSIZE)
plt.plot(iter_counts, tacotron_lj_pml_loss)
plt.plot(postnet_iter_counts, postnet_lj_loss)
plt.plot(pmlx_iter_counts, tacotron_lj_pmlx_loss)
plt.ylabel('Loss')
plt.xlabel('Iteration Count')
plt.title('Tacotron Conditioned on Vocoder Trajectories Loss Curve')
plt.legend(['Tacotron PML Loss Curve', 'PML Prediction Network with Residual Prediction Loss Curve', 'PML Prediction Network with CBHG Correction Loss Curve'])
plt.ylim(0.04, 0.15)
plt.xlim(-5000, 150000)
plt.savefig('./ErrorCorrection/ErrorCorrectLoss.png', dpi=600)
plt.show()
iter_counts = np.arange(0, tacotron_lj_pml_loss.size) * 100
pmlx_iter_counts = np.arange(0, tacotron_lj_pmlx_loss.size) * 100
postnet_iter_counts = np.arange(0, postnet_lj_loss.size) * 100
plt.figure(figsize=FIGSIZE)
# plt.plot(iter_counts, tacotron_lj_pml_loss)
plt.plot(postnet_iter_counts, postnet_lj_loss)
plt.plot(pmlx_iter_counts, tacotron_lj_pmlx_loss)
plt.ylabel('Loss')
plt.xlabel('Iteration Count')
plt.title('Tacotron Conditioned on Vocoder Trajectories Loss Curve')
plt.legend(['Tacotron PML with Postnet Loss Curve', 'Tacotron PML with Bidirectional Correction Loss Curve'])
plt.ylim(0.04, 0.07)
plt.savefig('./ErrorCorrection/loss_curve_closeup.png', dpi=600)
plt.show()
```
| github_jupyter |
#Performing Maximum Likelihood Estimates (MLEs) in IPython
By Delaney Granizo-Mackenzie
Notebook released under the Creative Commons Attribution 4.0 License.
---
In this tutorial notebook we'll do the following things:
1. Compute the MLE for a normal distribution.
2. Compute the MLE for an exponential distribution.
3. Fit a normal distribution to asset returns using MLE.
First we need to import some libraries
```
import math
import matplotlib.pyplot as plt
import numpy as np
import scipy
import scipy.stats
```
##Normal Distribution
We'll start by sampling some data from a normal distribution.
```
TRUE_MEAN = 40
TRUE_STD = 10
X = numpy.random.normal(TRUE_MEAN, TRUE_STD, 1000)
```
Now we'll define functions that given our data, will compute the MLE for the $\mu$ and $\sigma$ parameters of the normal distribution.
Recall that
$$\hat\mu = \frac{1}{T}\sum_{t=1}^{T} x_t$$
$$\hat\sigma = \sqrt{\frac{1}{T}\sum_{t=1}^{T}{(x_t - \hat\mu)^2}}$$
```
def normal_mu_MLE(X):
# Get the number of observations
T = len(data)
# Sum the observations
s = sum(X)
return 1.0/T * s
def normal_sigma_MLE(X):
T = len(X)
# Get the mu MLE
mu = normal_mu_mle(X)
# Sum the square of the differences
s = sum( math.pow((X - mu), 2) )
# Compute sigma^2
sigma_squared = 1.0/T * s
return math.sqrt(sigma_squared)
```
Now let's try our functions out on our sample data and see how they compare to the built-in `np.mean` and `np.std`
```
print "Mean Estimation"
print normal_mu_mle(X)
print np.mean(X)
print "Standard Deviation Estimation"
print normal_sigma_mle(X)
print np.std(X)
```
Now let's estimate both parameters at once with scipy's built in `fit()` function.
```
mu, std = scipy.stats.norm.fit(X)
print "mu estimate: " + str(mu)
print "std estimate: " + str(std)
```
Now let's plot the distribution PDF along with the data to see how well it fits. We can do that by accessing the pdf provided in `scipy.stats.norm.pdf`.
```
pdf = scipy.stats.norm.pdf
# We would like to plot our data along an x-axis ranging from 0-80 with 80 intervals
# (increments of 1)
x = np.linspace(0, 80, 80)
h = plt.hist(X, bins=x, normed='true')
l = plt.plot(pdf(x, loc=mu, scale=std))
```
##Exponential Distribution
Let's do the same thing, but for the exponential distribution. We'll start by sampling some data.
```
TRUE_LAMBDA = 5
X = np.random.exponential(TRUE_LAMBDA, 1000)
```
`numpy` defines the exponential distribution as
$$\frac{1}{\lambda}e^{-\frac{x}{\lambda}}$$
So we need to invert the MLE from the lecture notes. There it is
$$\hat\lambda = \frac{T}{\sum_{t=1}^{T} x_t}$$
Here it's just the reciprocal, so
$$\hat\lambda = \frac{\sum_{t=1}^{T} x_t}{T}$$
```
def exp_lamda_MLE(X):
T = len(X)
s = sum(X)
return s/T
print "lambda estimate: " + str(exp_lamda_MLE(X))
# The scipy version of the exponential distribution has a location parameter
# that can skew the distribution. We ignore this by fixing the location
# parameter to 0 with floc=0
_, l = scipy.stats.expon.fit(X, floc=0)
pdf = scipy.stats.expon.pdf
x = range(0, 80)
h = plt.hist(X, bins=x, normed='true')
l = plt.plot(pdf(x, scale=l))
```
##MLE for Asset Returns
Now we'll fetch some real returns and try to fit a normal distribution to them using MLE.
```
prices = get_pricing('TSLA', fields='price', start_date='2014-01-01', end_date='2015-01-01')
# This will give us the number of dollars returned each day
absolute_returns = np.diff(prices)
# This will give us the percentage return over the last day's value
# the [:-1] notation gives us all but the last item in the array
# We do this because there are no returns on the final price in the array.
returns = absolute_returns/prices[:-1]
```
Let's use `scipy`'s fit function to get the $\mu$ and $\sigma$ MLEs.
```
mu, std = scipy.stats.norm.fit(returns)
pdf = scipy.stats.norm.pdf
x = np.linspace(-1,1, num=100)
h = plt.hist(returns, bins=x, normed='true')
l = plt.plot(x, pdf(x, loc=mu, scale=std))
```
| github_jupyter |
# Writing out a USGSCSM ISD from a PDS3 Mex HRSC image
```
import os
# Update with where your metakernels are located
os.environ['ALESPICEROOT'] = '/scratch/spice/'
from ale.drivers.mex_drivers import MexHrscPds3NaifSpiceDriver
from ale.drivers.mex_drivers import MexHrscIsisLabelNaifSpiceDriver
from ale.formatters.isis_formatter import to_isis
import json
import ale
import os
from glob import glob
import numpy as np
import pvl
import struct
import spiceypy as spice
import warnings
from ale.base.data_isis import read_table_data
from ale.base.data_isis import parse_table
from ale.base import Driver
from ale.base.data_naif import NaifSpice
from ale.base.label_pds3 import Pds3Label
from ale.base.label_isis import IsisLabel
from ale.base.type_sensor import LineScanner
from ale.base.type_distortion import RadialDistortion
from ale.util import find_latest_metakernel
```
## Instantiating an ALE driver
ALE drivers are objects that define how to acquire common ISD keys from an input image format, in this case we are reading in a PDS3 image using NAIF SPICE kernels for exterior orientation data. If the driver utilizes NAIF SPICE kernels, it is implemented as a [context manager](https://docs.python.org/3/reference/datamodel.html#context-managers) and will furnish metakernels when entering the context (i.e. when entering the `with` block) and free the metakernels on exit. This maintains the integrity of spicelib's internal data structures. These driver objects are short-lived and are input to a formatter function that consumes the API to create a serializable file format. `ale.formatters` contains available formatter functions.
The ALESPICEROOT environment variable is used to find metakernels for different missions. You can update the path in the notebook to point to your metakernels directory. The directory is required to follow the NAIF direcrtory setup.
ALE has a two step process for writing out an ISD: 1. Instantiate your driver (in this case `LroLrocPds3LabelNaifSpiceDriver`) within a context and 2. pass the driver object into a formatter (in this case, `to_usgscsm`).
Requirements:
* A PDS3 Mex HRSC image
* NAIF metakernels installed
* A conda environment with ALE installed into it usisng the `conda install` command or created using the environment.yml file at the base of ALE.
```
fileName = '/home/tthatcher/Desktop/data/h5270_0000_ir2.cub'
isis_lbl = pvl.load(fileName)
kerns = pvl.dumps(isis_lbl["IsisCube"])
isis_lbl["IsisCube"]["Kernels"]
isis_bytes = read_table_data(isis_lbl['Table'], fileName)
print(isis_bytes)
parse_table(isis_lbl['Table'], isis_bytes)
isis_lbl
from ale import util
util.get_kernels_from_isis_pvl(isis_lbl["IsisCube"])
os.environ["ISIS3DATA"] = "/usgs/cpkgs/isis3/data/"
# change to desired PDS3 image path
# fileName = '/home/kdlee/h5270_0000_ir2.img'
fileName = '/home/tthatcher/Desktop/data/h5270_0000_ir2.cub'
# metakernels are furnsh-ed when entering the context (with block) with a driver instance
# most driver constructors simply accept an image path
with MexHrscIsisLabelNaifSpiceDriver(fileName, props={'kernels' : isis_lbl["IsisCube"]}) as driver:
# pass driver instance into formatter function
usgscsm_dict = to_isis(driver)
print(usgscsm_dict)
MexHrscIsisLabelNaifSpiceDriver.__mro__
```
### Write ISD to disk
ALE's USGSCSM formatter function returns a JSON.
USGSCSM requires the ISD to be colocated with the image file with a `.json` extension in place of the image extension.
```
usgscsm_dict.keys()
```
| github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.