markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Read name frequencies | # TODO rewrite this using pandas too
def load_name_freqs(path, is_surname):
name_freqs = defaultdict(int)
with fopen(path, mode="r", encoding="utf-8") as f:
for line in f:
fields = line.rstrip().split("\t")
for name_piece in normalize(fields[0], is_surname):
name_... | _____no_output_____ | MIT | reports/80_cluster_anc_triplet-initial.ipynb | rootsdev/nama |
Load model | model = torch.load(model_filename) | _____no_output_____ | MIT | reports/80_cluster_anc_triplet-initial.ipynb | rootsdev/nama |
Encode names | MAX_NAME_LENGTH=30
char_to_idx_map, idx_to_char_map = build_token_idx_maps() | _____no_output_____ | MIT | reports/80_cluster_anc_triplet-initial.ipynb | rootsdev/nama |
Take a sample because encoded names require a lot of memory | if sample_size <= 0 or sample_size >= len(all_names):
names_sample = np.array(list(all_names))
else:
names_sample = np.array(random.sample(all_names, sample_size))
print(names_sample.shape) | _____no_output_____ | MIT | reports/80_cluster_anc_triplet-initial.ipynb | rootsdev/nama |
Compute encodings | # Get embeddings
names_tensor, _ = convert_names_to_model_inputs(names_sample,
char_to_idx_map,
MAX_NAME_LENGTH)
# Get encodings for the names from the encoder
# TODO why do I need to encode in chunks?
chunk_size = 10000
nps... | _____no_output_____ | MIT | reports/80_cluster_anc_triplet-initial.ipynb | rootsdev/nama |
Compute distances | name_candidates = get_best_matches(names_encoded,
names_encoded,
names_sample,
num_candidates=num_candidates,
metric='euclidean')
# what's going on here?
distances = np.hstack((np.... | _____no_output_____ | MIT | reports/80_cluster_anc_triplet-initial.ipynb | rootsdev/nama |
Compute closures | # iterate over all distances, create closures and save scores
next_closure = 0
closure_ids = {}
id_closure = {}
row_ixs = []
col_ixs = []
dists = []
max_size = 0
for row in tqdm(distances):
name1 = row[0]
name2 = row[1]
id1 = name_ids[name1]
id2 = name_ids[name2]
# each distance is in distances twi... | _____no_output_____ | MIT | reports/80_cluster_anc_triplet-initial.ipynb | rootsdev/nama |
Compute clusters | def compute_clusters(closure_ids, id_names, dist_matrix, linkage, distance_threshold, eps, max_dist):
cluster_names = defaultdict(set)
name_cluster = {}
for closure, ids in tqdm(closure_ids.items()):
clusterer = AgglomerativeClustering(n_clusters=None, affinity='precomputed', linkage=linkage, distan... | _____no_output_____ | MIT | reports/80_cluster_anc_triplet-initial.ipynb | rootsdev/nama |
Add unclustered names as singleton clusters | def add_singleton_names(cluster_names, name_cluster, names_sample):
for ix, name in enumerate(names_sample):
if name not in name_cluster:
cluster = f'{ix}'
cluster_names[cluster].add(name)
name_cluster[name] = cluster
return cluster_names, name_cluster
cluster_names, ... | _____no_output_____ | MIT | reports/80_cluster_anc_triplet-initial.ipynb | rootsdev/nama |
Eval cluster P/R over Ancestry test data | train, test = load_train_test("../data/raw/records25k_data_train.csv", "../data/raw/records25k_data_test.csv")
_, _, candidates_train = train
input_names_test, weighted_relevant_names_test, candidates_test = test
all_candidates = np.concatenate((candidates_train, candidates_test))
def get_precision_recall(names_sampl... | _____no_output_____ | MIT | reports/80_cluster_anc_triplet-initial.ipynb | rootsdev/nama |
Write clusters | def write_clusters(path, cluster_names, name_freqs, name_nicks):
cluster_id_name_map = {}
with fopen(path, mode="w", encoding="utf-8") as f:
for cluster_id, names in cluster_names.items():
# get most-frequent name
cluster_name = max(names, key=(lambda name: name_freqs.get(name, 0... | _____no_output_____ | MIT | reports/80_cluster_anc_triplet-initial.ipynb | rootsdev/nama |
Create super-clusters | super_cluster_names, name_super_cluster = compute_clusters(closure_ids, id_names, dist_matrix, cluster_linkage,
super_cluster_distance_threshold, eps, max_dist)
print(len(super_cluster_names))
super_cluster_names, name_super_cluster = add_singleton_names(super... | _____no_output_____ | MIT | reports/80_cluster_anc_triplet-initial.ipynb | rootsdev/nama |
Write super-clusters | _ = write_clusters(super_clusters_filename, super_cluster_clusters, name_freqs, None) | _____no_output_____ | MIT | reports/80_cluster_anc_triplet-initial.ipynb | rootsdev/nama |
This notebook gives a 30 second introduction to the Vortexa SDK First let's import our requirements | from datetime import datetime
import vortexasdk as v | _____no_output_____ | Apache-2.0 | docs/examples/try_me_out/voyages_congestion_breakdown.ipynb | V0RT3X4/python-sdk |
Now let's load a dataframe of a sum of vessels in congestion. You'll need to enter your Vortexa API key when prompted. | df = v.VoyagesCongestionBreakdown()\
.search(
time_min=datetime(2021, 8, 1, 0),
time_max=datetime(2021, 8, 1, 23))\
.to_df()
df.head() | _____no_output_____ | Apache-2.0 | docs/examples/try_me_out/voyages_congestion_breakdown.ipynb | V0RT3X4/python-sdk |
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... | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Load images with tf.data View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook This tutorial provides a simple example of how to load an image dataset using `tf.data`.The dataset used in this example is distributed as directories of images, with one class of im... | from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tensorflow==2.0.0-beta1
import tensorflow as tf
AUTOTUNE = tf.data.experimental.AUTOTUNE | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Download and inspect the dataset Retrieve the imagesBefore you start any training, you will need a set of images to teach the network about the new classes you want to recognize. You have already created an archive of creative-commons licensed flower photos to use initially: | import pathlib
data_root_orig = tf.keras.utils.get_file(origin='https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz',
fname='flower_photos', untar=True)
data_root = pathlib.Path(data_root_orig)
print(data_root) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
After downloading 218MB, you should now have a copy of the flower photos available: | for item in data_root.iterdir():
print(item)
import random
all_image_paths = list(data_root.glob('*/*'))
all_image_paths = [str(path) for path in all_image_paths]
random.shuffle(all_image_paths)
image_count = len(all_image_paths)
image_count
all_image_paths[:10] | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Inspect the imagesNow let's have a quick look at a couple of the images, so you know what you are dealing with: | import os
attributions = (data_root/"LICENSE.txt").open(encoding='utf-8').readlines()[4:]
attributions = [line.split(' CC-BY') for line in attributions]
attributions = dict(attributions)
import IPython.display as display
def caption_image(image_path):
image_rel = pathlib.Path(image_path).relative_to(data_root)
... | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Determine the label for each image List the available labels: | label_names = sorted(item.name for item in data_root.glob('*/') if item.is_dir())
label_names | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Assign an index to each label: | label_to_index = dict((name, index) for index, name in enumerate(label_names))
label_to_index | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Create a list of every file, and its label index: | all_image_labels = [label_to_index[pathlib.Path(path).parent.name]
for path in all_image_paths]
print("First 10 labels indices: ", all_image_labels[:10]) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Load and format the images TensorFlow includes all the tools you need to load and process images: | img_path = all_image_paths[0]
img_path | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Here is the raw data: | img_raw = tf.io.read_file(img_path)
print(repr(img_raw)[:100]+"...") | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Decode it into an image tensor: | img_tensor = tf.image.decode_image(img_raw)
print(img_tensor.shape)
print(img_tensor.dtype) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Resize it for your model: | img_final = tf.image.resize(img_tensor, [192, 192])
img_final = img_final/255.0
print(img_final.shape)
print(img_final.numpy().min())
print(img_final.numpy().max())
| _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Wrap up these up in simple functions for later. | def preprocess_image(image):
image = tf.image.decode_jpeg(image, channels=3)
image = tf.image.resize(image, [192, 192])
image /= 255.0 # normalize to [0,1] range
return image
def load_and_preprocess_image(path):
image = tf.io.read_file(path)
return preprocess_image(image)
import matplotlib.pyplot as plt
... | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Build a `tf.data.Dataset` A dataset of images The easiest way to build a `tf.data.Dataset` is using the `from_tensor_slices` method.Slicing the array of strings, results in a dataset of strings: | path_ds = tf.data.Dataset.from_tensor_slices(all_image_paths) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
The `shapes` and `types` describe the content of each item in the dataset. In this case it is a set of scalar binary-strings | print(path_ds) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Now create a new dataset that loads and formats images on the fly by mapping `preprocess_image` over the dataset of paths. | image_ds = path_ds.map(load_and_preprocess_image, num_parallel_calls=AUTOTUNE)
import matplotlib.pyplot as plt
plt.figure(figsize=(8,8))
for n, image in enumerate(image_ds.take(4)):
plt.subplot(2,2,n+1)
plt.imshow(image)
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.xlabel(caption_image(all_image_paths... | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
A dataset of `(image, label)` pairs Using the same `from_tensor_slices` method you can build a dataset of labels: | label_ds = tf.data.Dataset.from_tensor_slices(tf.cast(all_image_labels, tf.int64))
for label in label_ds.take(10):
print(label_names[label.numpy()]) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Since the datasets are in the same order you can just zip them together to get a dataset of `(image, label)` pairs: | image_label_ds = tf.data.Dataset.zip((image_ds, label_ds)) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
The new dataset's `shapes` and `types` are tuples of shapes and types as well, describing each field: | print(image_label_ds) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Note: When you have arrays like `all_image_labels` and `all_image_paths` an alternative to `tf.data.dataset.Dataset.zip` is to slice the pair of arrays. | ds = tf.data.Dataset.from_tensor_slices((all_image_paths, all_image_labels))
# The tuples are unpacked into the positional arguments of the mapped function
def load_and_preprocess_from_path_label(path, label):
return load_and_preprocess_image(path), label
image_label_ds = ds.map(load_and_preprocess_from_path_label)... | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Basic methods for training To train a model with this dataset you will want the data:* To be well shuffled.* To be batched.* To repeat forever.* Batches to be available as soon as possible.These features can be easily added using the `tf.data` api. | BATCH_SIZE = 32
# Setting a shuffle buffer size as large as the dataset ensures that the data is
# completely shuffled.
ds = image_label_ds.shuffle(buffer_size=image_count)
ds = ds.repeat()
ds = ds.batch(BATCH_SIZE)
# `prefetch` lets the dataset fetch batches in the background while the model is training.
ds = ds.pref... | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
There are a few things to note here:1. The order is important. * A `.shuffle` after a `.repeat` would shuffle items across epoch boundaries (some items will be seen twice before others are seen at all). * A `.shuffle` after a `.batch` would shuffle the order of the batches, but not shuffle the items across batches.1.... | ds = image_label_ds.apply(
tf.data.experimental.shuffle_and_repeat(buffer_size=image_count))
ds = ds.batch(BATCH_SIZE)
ds = ds.prefetch(buffer_size=AUTOTUNE)
ds | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Pipe the dataset to a modelFetch a copy of MobileNet v2 from `tf.keras.applications`.This will be used for a simple transfer learning example.Set the MobileNet weights to be non-trainable: | mobile_net = tf.keras.applications.MobileNetV2(input_shape=(192, 192, 3), include_top=False)
mobile_net.trainable=False | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
This model expects its input to be normalized to the `[-1,1]` range:```help(keras_applications.mobilenet_v2.preprocess_input)```...This function applies the "Inception" preprocessing which convertsthe RGB values from [0, 255] to [-1, 1]... Before you pass the input to the MobilNet model, you need to convert it from a r... | def change_range(image,label):
return 2*image-1, label
keras_ds = ds.map(change_range) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
The MobileNet returns a `6x6` spatial grid of features for each image.Pass it a batch of images to see: | # The dataset may take a few seconds to start, as it fills its shuffle buffer.
image_batch, label_batch = next(iter(keras_ds))
feature_map_batch = mobile_net(image_batch)
print(feature_map_batch.shape) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Build a model wrapped around MobileNet and use `tf.keras.layers.GlobalAveragePooling2D` to average over those space dimensions before the output `tf.keras.layers.Dense` layer: | model = tf.keras.Sequential([
mobile_net,
tf.keras.layers.GlobalAveragePooling2D(),
tf.keras.layers.Dense(len(label_names))]) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Now it produces outputs of the expected shape: | logit_batch = model(image_batch).numpy()
print("min logit:", logit_batch.min())
print("max logit:", logit_batch.max())
print()
print("Shape:", logit_batch.shape) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Compile the model to describe the training procedure: | model.compile(optimizer=tf.keras.optimizers.Adam(),
loss='sparse_categorical_crossentropy',
metrics=["accuracy"]) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
There are 2 trainable variables - the Dense `weights` and `bias`: | len(model.trainable_variables)
model.summary() | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
You are ready to train the model.Note that for demonstration purposes you will only run 3 steps per epoch, but normally you would specify the real number of steps, as defined below, before passing it to `model.fit()`: | steps_per_epoch=tf.math.ceil(len(all_image_paths)/BATCH_SIZE).numpy()
steps_per_epoch
model.fit(ds, epochs=1, steps_per_epoch=3) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
PerformanceNote: This section just shows a couple of easy tricks that may help performance. For an in depth guide see [Input Pipeline Performance](https://www.tensorflow.org/guide/performance/datasets).The simple pipeline used above reads each file individually, on each epoch. This is fine for local training on CPU, b... | import time
default_timeit_steps = 2*steps_per_epoch+1
def timeit(ds, steps=default_timeit_steps):
overall_start = time.time()
# Fetch a single batch to prime the pipeline (fill the shuffle buffer),
# before starting the timer
it = iter(ds.take(steps+1))
next(it)
start = time.time()
for i,(images,labels... | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
The performance of the current dataset is: | ds = image_label_ds.apply(
tf.data.experimental.shuffle_and_repeat(buffer_size=image_count))
ds = ds.batch(BATCH_SIZE).prefetch(buffer_size=AUTOTUNE)
ds
timeit(ds) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Cache Use `tf.data.Dataset.cache` to easily cache calculations across epochs. This is very efficient, especially when the data fits in memory.Here the images are cached, after being pre-precessed (decoded and resized): | ds = image_label_ds.cache()
ds = ds.apply(
tf.data.experimental.shuffle_and_repeat(buffer_size=image_count))
ds = ds.batch(BATCH_SIZE).prefetch(buffer_size=AUTOTUNE)
ds
timeit(ds) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
One disadvantage to using an in memory cache is that the cache must be rebuilt on each run, giving the same startup delay each time the dataset is started: | timeit(ds) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
If the data doesn't fit in memory, use a cache file: | ds = image_label_ds.cache(filename='./cache.tf-data')
ds = ds.apply(
tf.data.experimental.shuffle_and_repeat(buffer_size=image_count))
ds = ds.batch(BATCH_SIZE).prefetch(1)
ds
timeit(ds) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
The cache file also has the advantage that it can be used to quickly restart the dataset without rebuilding the cache. Note how much faster it is the second time: | timeit(ds) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
TFRecord File Raw image dataTFRecord files are a simple format to store a sequence of binary blobs. By packing multiple examples into the same file, TensorFlow is able to read multiple examples at once, which is especially important for performance when using a remote storage service such as GCS.First, build a TFReco... | image_ds = tf.data.Dataset.from_tensor_slices(all_image_paths).map(tf.io.read_file)
tfrec = tf.data.experimental.TFRecordWriter('images.tfrec')
tfrec.write(image_ds) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Next, build a dataset that reads from the TFRecord file and decodes/reformats the images using the `preprocess_image` function you defined earlier: | image_ds = tf.data.TFRecordDataset('images.tfrec').map(preprocess_image) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Zip that dataset with the labels dataset you defined earlier to get the expected `(image,label)` pairs: | ds = tf.data.Dataset.zip((image_ds, label_ds))
ds = ds.apply(
tf.data.experimental.shuffle_and_repeat(buffer_size=image_count))
ds=ds.batch(BATCH_SIZE).prefetch(AUTOTUNE)
ds
timeit(ds) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
This is slower than the `cache` version because you have not cached the preprocessing. Serialized Tensors To save some preprocessing to the TFRecord file, first make a dataset of the processed images, as before: | paths_ds = tf.data.Dataset.from_tensor_slices(all_image_paths)
image_ds = paths_ds.map(load_and_preprocess_image)
image_ds | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Now instead of a dataset of `.jpeg` strings, you have a dataset of tensors.To serialize this to a TFRecord file you first convert the dataset of tensors to a dataset of strings: | ds = image_ds.map(tf.io.serialize_tensor)
ds
tfrec = tf.data.experimental.TFRecordWriter('images.tfrec')
tfrec.write(ds) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
With the preprocessing cached, data can be loaded from the TFrecord file quite efficiently - just remember to de-serialize tensor before using it: | ds = tf.data.TFRecordDataset('images.tfrec')
def parse(x):
result = tf.io.parse_tensor(x, out_type=tf.float32)
result = tf.reshape(result, [192, 192, 3])
return result
ds = ds.map(parse, num_parallel_calls=AUTOTUNE)
ds | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Now, add the labels and apply the same standard operations, as before: | ds = tf.data.Dataset.zip((ds, label_ds))
ds = ds.apply(
tf.data.experimental.shuffle_and_repeat(buffer_size=image_count))
ds=ds.batch(BATCH_SIZE).prefetch(AUTOTUNE)
ds
timeit(ds) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/load_data/images.ipynb | Terahezi/docs |
Loss Functions> Custom fastai loss functions | F.binary_cross_entropy_with_logits(torch.randn(4,5), torch.randint(0, 2, (4,5)).float(), reduction='none')
funcs_kwargs
# export
@log_args
class BaseLoss():
"Same as `loss_cls`, but flattens input and target."
activation=decodes=noops
def __init__(self, loss_cls, *args, axis=-1, flatten=True, floatify=False... | _____no_output_____ | Apache-2.0 | nbs/01a_losses.ipynb | aaminggo/fastai |
Wrapping a general loss function inside of `BaseLoss` provides extra functionalities to your loss functions:- flattens the tensors before trying to take the losses since it's more convenient (with a potential tranpose to put `axis` at the end)- a potential `activation` method that tells the library if there is an activ... | # export
@log_args
@delegates()
class CrossEntropyLossFlat(BaseLoss):
"Same as `nn.CrossEntropyLoss`, but flattens input and target."
y_int = True
@use_kwargs_dict(keep=True, weight=None, ignore_index=-100, reduction='mean')
def __init__(self, *args, axis=-1, **kwargs): super().__init__(nn.CrossEntropyL... | _____no_output_____ | Apache-2.0 | nbs/01a_losses.ipynb | aaminggo/fastai |
On top of the formula we define:- a `reduction` attribute, that will be used when we call `Learner.get_preds`- an `activation` function that represents the activation fused in the loss (since we use cross entropy behind the scenes). It will be applied to the output of the model when calling `Learner.get_preds` or `Lear... | #export
@log_args
@delegates()
class LabelSmoothingCrossEntropyFlat(BaseLoss):
"Same as `LabelSmoothingCrossEntropy`, but flattens input and target."
y_int = True
@use_kwargs_dict(keep=True, eps=0.1, reduction='mean')
def __init__(self, *args, axis=-1, **kwargs): super().__init__(LabelSmoothingCrossEntr... | _____no_output_____ | Apache-2.0 | nbs/01a_losses.ipynb | aaminggo/fastai |
Export - | #hide
from nbdev.export import *
notebook2script() | Converted 00_torch_core.ipynb.
Converted 01_layers.ipynb.
Converted 02_data.load.ipynb.
Converted 03_data.core.ipynb.
Converted 04_data.external.ipynb.
Converted 05_data.transforms.ipynb.
Converted 06_data.block.ipynb.
Converted 07_vision.core.ipynb.
Converted 08_vision.data.ipynb.
Converted 09_vision.augment.ipynb.
Co... | Apache-2.0 | nbs/01a_losses.ipynb | aaminggo/fastai |
Trusted Notebook" width="500 px" align="left"> Qiskit Tutorials***Welcome Qiskitters.The easiest way to get started is to use [the Binder image](https://mybinder.org/v2/gh/qiskit/qiskit-tutorials/master?filepath=index.ipynb), which lets you use the notebooks via the web. This means that you don't need to download or ... | from IPython.display import display, Markdown
with open('index.md', 'r') as readme: content = readme.read(); display(Markdown(content)) | _____no_output_____ | Apache-2.0 | index.ipynb | Chibikuri/qiskit-tutorials |
The Central Limit Theorem Very few of the data histograms that we have seen in this course have been bell shaped. When we have come across a bell shaped distribution, it has almost invariably been an empirical histogram of a statistic based on a random sample. **The Central Limit Theorem says that the probability dist... | colors = make_array('Purple', 'Purple', 'Purple', 'White')
model = Table().with_column('Color', colors)
model
props = make_array()
num_plants = 200
repetitions = 1000
for i in np.arange(repetitions):
sample = model.sample(num_plants)
new_prop = np.count_nonzero(sample.column('Color') == 'Purple')/num_plants... | _____no_output_____ | BSD-3-Clause | packages/nbinteract-core/example-notebooks/examples_central_limit_theorem.ipynb | samlaf/nbinteract |
There's that normal curve again, as predicted by the Central Limit Theorem, centered at around 0.75 just as you would expect.How would this distribution change if we increased the sample size? We can copy our sampling code into a function and then use interaction to see how the distribution changes as the sample size i... | def empirical_props(num_plants):
props = make_array()
for i in np.arange(repetitions):
sample = model.sample(num_plants)
new_prop = np.count_nonzero(sample.column('Color') == 'Purple')/num_plants
props = np.append(props, new_prop)
return props
nbi.hist(empirical_props, options=opts,
... | _____no_output_____ | BSD-3-Clause | packages/nbinteract-core/example-notebooks/examples_central_limit_theorem.ipynb | samlaf/nbinteract |
Plotting aggregate variablesPyam offers many great visualisation and analysis tools. In this notebook we highlight the `aggregate` and `stack_plot` methods of an `IamDataFrame`. | import numpy as np
import pandas as pd
import pyam
%matplotlib inline
import matplotlib.pyplot as plt | _____no_output_____ | Apache-2.0 | doc/source/tutorials/aggregating_variables_and_plotting_with_negative_values.ipynb | peterkolp/pyam |
Here we provide some sample data for this tutorial. This data is for a single model-scenario-region combination but provides multiple subsectors of CO$_2$ emissions. The emissions in the subsectors are both positive and negative and so provide a good test of the flexibility of our aggregation and plotting routines. | df = pyam.IamDataFrame(pd.DataFrame([
['IMG', 'a_scen', 'World', 'Emissions|CO2|Energy|Oil', 'Mt CO2/yr', 2, 3.2, 2.0, 1.8],
['IMG', 'a_scen', 'World', 'Emissions|CO2|Energy|Gas', 'Mt CO2/yr', 1.3, 1.6, 1.0, 0.7],
['IMG', 'a_scen', 'World', 'Emissions|CO2|Energy|BECCS', 'Mt CO2/yr', 0.0, 0.4, -0.4, 0.3],
... | _____no_output_____ | Apache-2.0 | doc/source/tutorials/aggregating_variables_and_plotting_with_negative_values.ipynb | peterkolp/pyam |
Pyam's `stack_plot` method plots the stacks in the clearest way possible, even when some emissions are negative. The optional `total` keyword arguments also allows the user to include a total line on their plot. | df.stack_plot();
df.stack_plot(total=True); | _____no_output_____ | Apache-2.0 | doc/source/tutorials/aggregating_variables_and_plotting_with_negative_values.ipynb | peterkolp/pyam |
The appearance of the stackplot can be simply controlled via ``kwargs``. The appearance of the total line is controlled by passing a dictionary to the `total_kwargs` keyword argument. | df.stack_plot(alpha=0.5, total={"color": "grey", "ls": "--", "lw": 2.0}); | _____no_output_____ | Apache-2.0 | doc/source/tutorials/aggregating_variables_and_plotting_with_negative_values.ipynb | peterkolp/pyam |
If the user wishes, they can firstly filter their data before plotting. | df.filter(variable="Emissions|CO2|Energy*").stack_plot(total=True); | _____no_output_____ | Apache-2.0 | doc/source/tutorials/aggregating_variables_and_plotting_with_negative_values.ipynb | peterkolp/pyam |
Using `aggregate`, it is possible to create arbitrary sums of sub-sectors before plotting. | pdf = df.copy()
afoluluc_vars = ["Emissions|CO2|LUC", "Emissions|CO2|Agg"]
fossil_vars = list(set(pdf.variables()) - set(afoluluc_vars))
pdf.aggregate(
"Emissions|CO2|AFOLULUC",
components=afoluluc_vars,
append=True
)
pdf.aggregate(
"Emissions|CO2|Fossil",
components=fossil_vars,
append=True... | _____no_output_____ | Apache-2.0 | doc/source/tutorials/aggregating_variables_and_plotting_with_negative_values.ipynb | peterkolp/pyam |
Author: Saeed Amen (@thalesians) - Managing Director & Co-founder of [the Thalesians](http://www.thalesians.com) Introduction With the UK general election in early May 2015, we thought it would be a fun exercise to demonstrate how you can investigate market price action over historial elections. We shall be using Pyth... | # for time series manipulation
import pandas
class DataDownloader:
def download_time_series(self, vendor_ticker, pretty_ticker, start_date, source, csv_file = None):
if source == 'Quandl':
import Quandl
# Quandl requires API key for large number of daily downloads
# htt... | _____no_output_____ | CC-BY-3.0 | _posts/ipython-notebooks/ukelectionbbg.ipynb | jacolind/documentation |
Generic functions for event study and Plotly plotting We now focus our efforts on the EventPlot class. Here we shall do our basic analysis. We shall aslo create functions for creating plotly traces and layouts that we shall reuse a number of times. The analysis we shall conduct is fairly simple. Given a time series of... | # for dates
import datetime
# time series manipulation
import pandas
# for plotting data
import plotly
from plotly.graph_objs import *
class EventPlot:
def event_study(self, spot, dates, pre, post, mean_label = 'Mean'):
# event_study - calculates the asset price moves over windows around event days
... | _____no_output_____ | CC-BY-3.0 | _posts/ipython-notebooks/ukelectionbbg.ipynb | jacolind/documentation |
We write a function to convert dates represented in a string format to Python format. | def parse_dates(self, str_dates):
# parse_dates - parses string dates into Python format
#
# str_dates = dates to be parsed in the format of day/month/year
#
dates = []
for d in str_dates:
dates.append(datetime.datetime.strptime(d, '%d/%m/%Y'))
... | _____no_output_____ | CC-BY-3.0 | _posts/ipython-notebooks/ukelectionbbg.ipynb | jacolind/documentation |
Our next focus is on the Plotly functions which create a layout. This enables us to specify axes labels, the width and height of the final plot and so on. We could of course add further properties into it. | def create_layout(self, title, xaxis, yaxis, width = -1, height = -1):
# create_layout - populates a layout object
# title = title of the plot
# xaxis = xaxis label
# yaxis = yaxis label
# width (optional) = width of plot
# height (optional) = height of plot
#... | _____no_output_____ | CC-BY-3.0 | _posts/ipython-notebooks/ukelectionbbg.ipynb | jacolind/documentation |
Earlier, in the DataDownloader class, our output was Pandas based dataframes. Our convert_df_plotly function will convert these each series from Pandas dataframe into plotly traces. Along the way, we shall add various properties such as markers with varying levels of opacity, graduated coloring of lines (which uses col... | def convert_df_plotly(self, dataframe, axis_no = 1, color_def = ['default'],
special_line = 'Mean', showlegend = True, addmarker = False, gradcolor = None):
# convert_df_plotly - converts a Pandas data frame to Plotly format for line plots
# dataframe = data frame due to be... | _____no_output_____ | CC-BY-3.0 | _posts/ipython-notebooks/ukelectionbbg.ipynb | jacolind/documentation |
UK election analysis We've now created several generic functions for downloading data, doing an event study and also for helping us out with plotting via Plotly. We now start work on the ukelection.py script, for pulling it all together. As a very first step we need to provide credentials for Plotly (you can get your ... | # for time series/maths
import pandas
# for plotting data
import plotly
import plotly.plotly as py
from plotly.graph_objs import *
def ukelection():
# Learn about API authentication here: https://plot.ly/python/getting-started
# Find your api_key here: https://plot.ly/settings/api
plotly_username = "t... | _____no_output_____ | CC-BY-3.0 | _posts/ipython-notebooks/ukelectionbbg.ipynb | jacolind/documentation |
Let's download our market data that we need (GBP/USD spot data) using the DataDownloader class. As a default, I've opted to use Bloomberg data. You can try other currency pairs or markets (for example FTSE), to compare results for the event study. Note that obviously each data vendor will have a different ticker in the... | ticker = 'GBPUSD' # will use in plot titles later (and for creating Plotly URL)
##### download market GBP/USD data from Quandl, Bloomberg or CSV file
source = "Bloomberg"
# source = "Quandl"
# source = "CSV"
csv_file = None
event_plot = EventPlot()
data_downloader = DataDownload... | _____no_output_____ | CC-BY-3.0 | _posts/ipython-notebooks/ukelectionbbg.ipynb | jacolind/documentation |
The most important part of the study is getting the historical UK election dates! We can obtain these from Wikipedia. We then convert into Python format. We need to make sure we filter the UK election dates, for where we have spot data available. | labour_wins = ['28/02/1974', '10/10/1974', '01/05/1997', '07/06/2001', '05/05/2005']
conservative_wins = ['03/05/1979', '09/06/1983', '11/06/1987', '09/04/1992', '06/05/2010']
# convert to more easily readable format
labour_wins_d = event_plot.parse_dates(labour_wins)
conservative_wins_d = event_pl... | _____no_output_____ | CC-BY-3.0 | _posts/ipython-notebooks/ukelectionbbg.ipynb | jacolind/documentation |
We then call our event study function in EventPlot on our spot data, which compromises of the 20 days before up till the 20 days after the UK general election. We shall plot these lines later. | # number of days before and after for our event study
pre = -20
post = 20
# calculate spot path during Labour wins
labour_wins_spot = event_plot.event_study(spot, labour_wins_d, pre, post, mean_label = 'Labour Mean')
# calculate spot path during Conservative wins
conservative_wins_spot = e... | _____no_output_____ | CC-BY-3.0 | _posts/ipython-notebooks/ukelectionbbg.ipynb | jacolind/documentation |
Define our xaxis and yaxis labels, as well as our source, which we shall later include in the title. | ##### Create separate plots of price action during Labour and Conservative wins
xaxis = 'Days'
yaxis = 'Index'
source_label = "Source: @thalesians/BBG/Wikipedia" | _____no_output_____ | CC-BY-3.0 | _posts/ipython-notebooks/ukelectionbbg.ipynb | jacolind/documentation |
We're finally ready for our first plot! We shall plot GBP/USD moves over Labour election wins, using the default palette and then we shall embed it into the sheet, using the URL given to us from the Plotly website. | ###### Plot market reaction during Labour UK election wins
###### Using default color scheme
title = ticker + ' during UK gen elect - Lab wins' + '<BR>' + source_label
fig = Figure(data=event_plot.convert_df_plotly(labour_wins_spot),
layout=event_plot.create_layout(title, xaxis, yaxis... | _____no_output_____ | CC-BY-3.0 | _posts/ipython-notebooks/ukelectionbbg.ipynb | jacolind/documentation |
The "iplot" function will send it to Plotly's server (provided we have all the dependencies installed). Alternatively, we could embed the HTML as an image, which we have taken from the Plotly website. Note this approach will yield a static image which is fetched from Plotly's servers. It also possible to write the imag... | ###### Plot market reaction during Conservative UK election wins
###### Using varying shades of blue for each line (helped by colorlover library)
title = ticker + ' during UK gen elect - Con wins ' + '<BR>' + source_label
# also apply graduated color scheme of blues (from light to dark)
# see http... | _____no_output_____ | CC-BY-3.0 | _posts/ipython-notebooks/ukelectionbbg.ipynb | jacolind/documentation |
Embed the chart into the document using "embed". This essentially embeds the Javascript code, necessary to make it interactive. | import plotly.tools as tls
tls.embed("https://plot.ly/~thalesians/245") | _____no_output_____ | CC-BY-3.0 | _posts/ipython-notebooks/ukelectionbbg.ipynb | jacolind/documentation |
Our final plot, will consist of three subplots, Labour wins, Conservative wins, and average moves for both. We also add a grid and a grey background for each plot. | ##### Plot market reaction during Conservative UK election wins
##### create a plot consisting of 3 subplots (from left to right)
##### 1. Labour wins, 2. Conservative wins, 3. Conservative/Labour mean move
# create a dataframe which grabs the mean from the respective Lab & Con election wins
mean_w... | This is the format of your plot grid:
[ (1,1) x1,y1 ] [ (1,2) x2,y2 ] [ (1,3) x3,y3 ]
| CC-BY-3.0 | _posts/ipython-notebooks/ukelectionbbg.ipynb | jacolind/documentation |
This time we use "embed", which grab the plot from Plotly's server, we did earlier (given we have already uploaded it). | import plotly.tools as tls
tls.embed("https://plot.ly/~thalesians/246") | _____no_output_____ | CC-BY-3.0 | _posts/ipython-notebooks/ukelectionbbg.ipynb | jacolind/documentation |
That's about it! I hope the code I've written proves fruitful for creating some very cool Plotly plots and also for doing some very timely analysis ahead of the UK general election! Hoping this will be first of many blogs on using Plotly data. The analysis in this blog is based on a report I wrote for Thalesians, a qua... | from IPython.display import display, HTML
display(HTML('<link href="//fonts.googleapis.com/css?family=Open+Sans:600,400,300,200|Inconsolata|Ubuntu+Mono:400,700" rel="stylesheet" type="text/css" />'))
display(HTML('<link rel="stylesheet" type="text/css" href="http://help.plot.ly/documentation/all_static/css/ipython-not... | Requirement already up-to-date: publisher in /Users/chriddyp/Repos/venvpy27/lib/python2.7/site-packages/publisher-0.4-py2.7.egg
| CC-BY-3.0 | _posts/ipython-notebooks/ukelectionbbg.ipynb | jacolind/documentation |
Introduction to Bayesian Optimization with GPyOpt Written by Javier Gonzalez, Amazon Research Cambridge*Last updated Monday, 22 May 2017.*=====================================================================================================1. **How to use GPyOpt?**2. **The Basics of Bayesian Optimization** 1. Gauss... | %pylab inline
import GPy
import GPyOpt
from numpy.random import seed
import matplotlib | Populating the interactive namespace from numpy and matplotlib
warning in stationary: failed to import cython module: falling back to numpy
| BSD-3-Clause | manual/GPyOpt_reference_manual.ipynb | komorihi/GPyOpt |
GPyOpt is easy to use as a black-box functions optimizer. To start you only need: * Your favorite function $f$ to minimize. We use $f(x)=2x^2$ in this toy example, whose global minimum is at x=0. | def myf(x):
return (2*x)**2 | _____no_output_____ | BSD-3-Clause | manual/GPyOpt_reference_manual.ipynb | komorihi/GPyOpt |
* A set of box constrains, the interval [-1,1] in our case. You can define a list of dictionaries where each element defines the name, type and domain of the variables. | bounds = [{'name': 'var_1', 'type': 'continuous', 'domain': (-1,1)}] | _____no_output_____ | BSD-3-Clause | manual/GPyOpt_reference_manual.ipynb | komorihi/GPyOpt |
* A budget, or number of allowed evaluations of $f$. | max_iter = 15 | _____no_output_____ | BSD-3-Clause | manual/GPyOpt_reference_manual.ipynb | komorihi/GPyOpt |
With this three pieces of information GPyOpt has enough to find the minimum of $f$ in the selected region. GPyOpt solves the problem in two steps. First, you need to create a GPyOpt object that stores the problem (f and and box-constrains). You can do it as follows. | myProblem = GPyOpt.methods.BayesianOptimization(myf,bounds) | _____no_output_____ | BSD-3-Clause | manual/GPyOpt_reference_manual.ipynb | komorihi/GPyOpt |
Next you need to run the optimization for the given budget of iterations. This bit it is a bit slow because many default options are used. In the next notebooks of this manual you can learn how to change other parameters to optimize the optimization performance. | myProblem.run_optimization(max_iter) | _____no_output_____ | BSD-3-Clause | manual/GPyOpt_reference_manual.ipynb | komorihi/GPyOpt |
Now you can check the best found location $x^*$ by | myProblem.x_opt | _____no_output_____ | BSD-3-Clause | manual/GPyOpt_reference_manual.ipynb | komorihi/GPyOpt |
and the predicted value value of $f$ at $x^*$ optimum by | myProblem.fx_opt | _____no_output_____ | BSD-3-Clause | manual/GPyOpt_reference_manual.ipynb | komorihi/GPyOpt |
And that's it! Keep reading to learn how GPyOpt uses Bayesian Optimization to solve this an other optimization problem. You will also learn all the features and options that you can use to solve your problems efficiently. ==================================================================================================... | from IPython.display import YouTubeVideo
YouTubeVideo('ualnbKfkc3Q') | _____no_output_____ | BSD-3-Clause | manual/GPyOpt_reference_manual.ipynb | komorihi/GPyOpt |
3. One dimensional exampleIn this example we show how GPyOpt works in a one-dimensional example a bit more difficult that the one we analyzed in Section 3. Let's consider here the Forrester function $$f(x) =(6x-2)^2 \sin(12x-4)$$ defined on the interval $[0, 1]$. The minimum of this function is located at $x_{min}=0.7... | %pylab inline
import GPy
import GPyOpt
# Create the true and perturbed Forrester function and the boundaries of the problem
f_true= GPyOpt.objective_examples.experiments1d.forrester() # noisy version
bounds = [{'name': 'var_1', 'type': 'continuous', 'domain': (0,1)}] # problem constrains | Populating the interactive namespace from numpy and matplotlib
| BSD-3-Clause | manual/GPyOpt_reference_manual.ipynb | komorihi/GPyOpt |
We plot the true Forrester function. | f_true.plot() | _____no_output_____ | BSD-3-Clause | manual/GPyOpt_reference_manual.ipynb | komorihi/GPyOpt |
As we did in Section 3, we need to create the GPyOpt object that will run the optimization. We specify the function, the boundaries and we add the type of acquisition function to use. | # Creates GPyOpt object with the model and anquisition fucntion
seed(123)
myBopt = GPyOpt.methods.BayesianOptimization(f=f_true.f, # function to optimize
domain=bounds, # box-constrains of the problem
acqu... | _____no_output_____ | BSD-3-Clause | manual/GPyOpt_reference_manual.ipynb | komorihi/GPyOpt |
Now we want to run the optimization. Apart from the number of iterations you can select how do you want to optimize the acquisition function. You can run a number of local optimizers (acqu_optimize_restart) at random or in grid (acqu_optimize_method). | # Run the optimization
max_iter = 15 # evaluation budget
max_time = 60 # time budget
eps = 10e-6 # Minimum allows distance between the las two observations
myBopt.run_optimization(max_iter, max_time, eps) | _____no_output_____ | BSD-3-Clause | manual/GPyOpt_reference_manual.ipynb | komorihi/GPyOpt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.