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
Export the data and model configuration**Note:** Before exporting data ensure that Neptune Export has been configured as described here: [Neptune Export Service](https://docs.aws.amazon.com/neptune/latest/userguide/machine-learning-data-export-service.htmlmachine-learning-data-export-service-run-export) With our produ...
export_params={ "command": "export-pg", "params": { "endpoint": neptune_ml.get_host(), "profile": "neptune_ml", "cloneCluster": False }, "outputS3Path": f'{s3_bucket_uri}/neptune-export', "additionalParams": { "neptune_ml": { "version": "v2.0", "features...
_____no_output_____
ISC
src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb
zacharyrs/graph-notebook
ML data processing, model training, and endpoint creationOnce the export job is completed we are now ready to train our machine learning model and create the inference endpoint. Training our Neptune ML model requires three steps. Note: The cells below only configure a minimal set of parameters required to run a mod...
# The training_job_name can be set to a unique value below, otherwise one will be auto generated training_job_name=neptune_ml.get_training_job_name('link-prediction') processing_params = f""" --config-file-name training-data-configuration.json --job-id {training_job_name} --s3-input-uri {export_results['outputS3Uri']...
_____no_output_____
ISC
src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb
zacharyrs/graph-notebook
Model trainingThe second step (model training) trains the ML model that will be used for predictions. The model training is done in two stages. The first stage uses a SageMaker Processing job to generate a model training strategy. A model training strategy is a configuration set that specifies what type of model and m...
training_params=f""" --job-id {training_job_name} --data-processing-id {training_job_name} --instance-type ml.p3.2xlarge --s3-output-uri {str(s3_bucket_uri)}/training --max-hpo-number 2 --max-hpo-parallel 2 """ %neptune_ml training start --wait --store-to training_results {training_params}
_____no_output_____
ISC
src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb
zacharyrs/graph-notebook
Endpoint creationThe final step is to create the inference endpoint which is an Amazon SageMaker endpoint instance that is launched with the model artifacts produced by the best training job. This endpoint will be used by our graph queries to return the model predictions for the inputs in the request. The endpoint on...
endpoint_params=f""" --id {training_job_name} --model-training-job-id {training_job_name}""" %neptune_ml endpoint create --wait --store-to endpoint_results {endpoint_params}
_____no_output_____
ISC
src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb
zacharyrs/graph-notebook
Once this has completed we get the endpoint name for our newly created inference endpoint. The cell below will set the endpoint name which will be used in the Gremlin queries below.
endpoint=endpoint_results['endpoint']['name']
_____no_output_____
ISC
src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb
zacharyrs/graph-notebook
Querying using GremlinNow that we have our inference endpoint setup let's query our product knowledge graph to show how to predict how likely it is that a user will rate a movie. The need to predict the likelyhood of connections in a product knowledge graph is commonly used to provide recommendations for products tha...
%%gremlin g.V('user_1').out('rated').hasLabel('movie').valueMap()
_____no_output_____
ISC
src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb
zacharyrs/graph-notebook
As expected, their are not any `rated` edges for `user_1`. Maybe `user_1` is a new user in our system and we want to provide them some product recommendations. Let's modify the query to predict what movies `user_1` is most likely to rate. First, we add the `with()` step to specify the inference endpoint we want to us...
%%gremlin g.with("Neptune#ml.endpoint","${endpoint}"). V('user_1').out('rated').with("Neptune#ml.prediction").hasLabel('movie').valueMap('title')
_____no_output_____
ISC
src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb
zacharyrs/graph-notebook
Great, we can now see that we are predicted edges showing that `Sleepers` is the movie that `user_1` is most likely to rate. In the example above we predicted the target node but we can also use the same mechanism to predict the source node. Let's turn that question around and say that we had a product and we wanted ...
%%gremlin g.with("Neptune#ml.endpoint","${endpoint}"). with("Neptune#ml.limit",10). V().has('title', 'Apollo 13 (1995)'). in('rated').with("Neptune#ml.prediction").hasLabel('user').id()
_____no_output_____
ISC
src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb
zacharyrs/graph-notebook
With that we have sucessfully been able to show how you can use link prediction to predict edges starting at either end. From the examples we have shown here you can begin to see how the ability to infer unknown connections within a graph starts to enable many interesting and unique use cases within Amazon Neptune. ...
neptune_ml.delete_endpoint(training_job_name)
_____no_output_____
ISC
src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb
zacharyrs/graph-notebook
Desafio01: Encontrar os valores relativos para as idades dos incritosDesafio02: Descobrir de quais estados são os inscritos com 13 anos. Desafio03: Colocar título no gráfico
# Mostrando histograma das idades dos participantes dados[ "NU_IDADE"].hist(bins = 50, figsize = (16, 7)) # Fazendo query no bando de dados para pegar somente observacoes de treineiros, depois mostrando o total das idades em ordem crescente dados.query("IN_TREINEIRO == 1")["NU_IDADE"].value_counts().sort_index().head(5...
_____no_output_____
MIT
Alura/imersaoDados02/aula 2/ImersaoDados02Aula02.ipynb
W8jonas/estudos
Desafio04: Plotar os histogramas das idades dos treineiros e não treineiros
# Plotando histograma das notas da redacao dados["NU_NOTA_REDACAO"].hist(bins = 50, figsize=(19, 7)) # Plotando histograma das notas da prova de Ciências Humanas dados["NU_NOTA_CH"].hist(bins = 50, figsize=(19, 7)) # Fazendo query no bando de dados para pegar somente observacoes do Estado de Minas # Depois separando so...
_____no_output_____
MIT
Alura/imersaoDados02/aula 2/ImersaoDados02Aula02.ipynb
W8jonas/estudos
Desafio05: Comparar as distribuições das provas em inglês e espanhol nas provas de LC
#Resolvendo desafio 01 dados.query("NU_IDADE <= 14")["SG_UF_RESIDENCIA"].value_counts(normalize=True) renda_ordenada = dados["Q006"].unique() renda_ordenada.sort() print(renda_ordenada) import seaborn as sns import matplotlib.pyplot as plt plt.figure(figsize=(18, 8)) sns.boxplot(x="Q006", y = "NU_NOTA_REDACAO", dat...
_____no_output_____
MIT
Alura/imersaoDados02/aula 2/ImersaoDados02Aula02.ipynb
W8jonas/estudos
Nessie Iceberg/Flink SQL Demo with NBA Dataset============================This demo showcases how to use Nessie Python API along with Flink from IcebergInitialize PyFlink----------------------------------------------To get started, we will first have to do a few setup steps that give us everything we needto get started...
import os from pyflink.datastream import StreamExecutionEnvironment from pyflink.table import StreamTableEnvironment from pyflink.table.expressions import lit from pynessie import init # where we will store our data warehouse = os.path.join(os.getcwd(), "flink-warehouse") # this was downloaded when Binder started, its...
_____no_output_____
Apache-2.0
notebooks/nessie-iceberg-flink-demo-nba.ipynb
sandhyasun/nessie-demos
Solving Data Engineering problems with Nessie============================In this Demo we are a data engineer working at a fictional sports analytics blog. In order for the authors to write articles they have to have access to the relevant data. They need to be able to retrieve data quickly and be able to create charts ...
create_ref_catalog("dev")
_____no_output_____
Apache-2.0
notebooks/nessie-iceberg-flink-demo-nba.ipynb
sandhyasun/nessie-demos
We have created the branch `dev` and we can see the branch with the Nessie `hash` its currently pointing to.Below we list all branches. Note that the auto created `main` branch already exists and both branches point at the same `hash`
!nessie --verbose branch
_____no_output_____
Apache-2.0
notebooks/nessie-iceberg-flink-demo-nba.ipynb
sandhyasun/nessie-demos
Create tables under dev branch-------------------------------------Once we created the `dev` branch and verified that it exists, we can create some tables and add some data.We create two tables under the `dev` branch:- `salaries`- `totals_stats`These tables list the salaries per player per year and their stats per year...
# Load the dataset from pyflink.table import DataTypes from pyflink.table.descriptors import Schema, OldCsv, FileSystem # Creating `salaries` table (table_env.connect(FileSystem().path('../datasets/nba/salaries.csv')) .with_format(OldCsv() .field('Season', DataTypes.STRING()).field("Team", DataTypes.S...
_____no_output_____
Apache-2.0
notebooks/nessie-iceberg-flink-demo-nba.ipynb
sandhyasun/nessie-demos
Now we count the rows in our tables to ensure they are the same number as the csv files. Note we use the `table@branch` notation which overrides the context set by the catalog.
table_count = table_env.from_path('dev_catalog.nba.`salaries@dev`').select('Season.count').to_pandas().values[0][0] csv_count = table_env.from_path('dev_catalog.nba.salaries_temp').select('Season.count').to_pandas().values[0][0] assert table_count == csv_count print(table_count) table_count = table_env.from_path('dev_...
_____no_output_____
Apache-2.0
notebooks/nessie-iceberg-flink-demo-nba.ipynb
sandhyasun/nessie-demos
Check generated tables----------------------------Since we have been working solely on the `dev` branch, where we created 2 tables and added some data,let's verify that the `main` branch was not altered by our changes.
!nessie contents --list
_____no_output_____
Apache-2.0
notebooks/nessie-iceberg-flink-demo-nba.ipynb
sandhyasun/nessie-demos
And on the `dev` branch we expect to see two tables
!nessie contents --list --ref dev
_____no_output_____
Apache-2.0
notebooks/nessie-iceberg-flink-demo-nba.ipynb
sandhyasun/nessie-demos
We can also verify that the `dev` and `main` branches point to different commits
!nessie --verbose branch
_____no_output_____
Apache-2.0
notebooks/nessie-iceberg-flink-demo-nba.ipynb
sandhyasun/nessie-demos
Dev promotion into main-----------------------Once we are done with our changes on the `dev` branch, we would like to merge those changes into `main`.We merge `dev` into `main` via the command line `merge` command.Both branches should be at the same revision after merging/promotion.
!nessie merge dev -b main --force
_____no_output_____
Apache-2.0
notebooks/nessie-iceberg-flink-demo-nba.ipynb
sandhyasun/nessie-demos
We can verify the branches are at the same hash and that the `main` branch now contains the expected tables and row counts.The tables are now on `main` and ready for consumtion by our blog authors and analysts!
!nessie --verbose branch !nessie contents --list table_count = table_env.from_path('main_catalog.nba.salaries').select('Season.count').to_pandas().values[0][0] csv_count = table_env.from_path('dev_catalog.nba.salaries_temp').select('Season.count').to_pandas().values[0][0] assert table_count == csv_count table_count = ...
_____no_output_____
Apache-2.0
notebooks/nessie-iceberg-flink-demo-nba.ipynb
sandhyasun/nessie-demos
Perform regular ETL on the new tables-------------------Our analysts are happy with the data and we want to now regularly ingest data to keep things up to date. Our first ETL job consists of the following:1. Update the salaries table to add new data2. We have decided the `Age` column isn't required in the `total_stats`...
create_ref_catalog("etl") # add some salaries for Kevin Durant table_env.execute_sql("""INSERT INTO etl_catalog.nba.salaries VALUES ('2017-18', 'Golden State Warriors', '$25000000', 'Kevin Durant'), ('2018-19', 'Golden State Warriors', '$30000000', 'Kevin Durant'), ...
_____no_output_____
Apache-2.0
notebooks/nessie-iceberg-flink-demo-nba.ipynb
sandhyasun/nessie-demos
We can verify that the new table isn't on the `main` branch but is present on the etl branch
# Since we have been working on the `etl` branch, the `allstar_games_stats` table is not on the `main` branch !nessie contents --list # We should see `allstar_games_stats` and the `new_total_stats` on the `etl` branch !nessie contents --list --ref etl
_____no_output_____
Apache-2.0
notebooks/nessie-iceberg-flink-demo-nba.ipynb
sandhyasun/nessie-demos
Now that we are happy with the data we can again merge it into `main`
!nessie merge etl -b main --force
_____no_output_____
Apache-2.0
notebooks/nessie-iceberg-flink-demo-nba.ipynb
sandhyasun/nessie-demos
Now lets verify that the changes exist on the `main` branch and that the `main` and `etl` branches have the same `hash`
!nessie contents --list !nessie --verbose branch table_count = table_env.from_path('main_catalog.nba.allstar_games_stats').select('Season.count').to_pandas().values[0][0] csv_count = table_env.from_path('etl_catalog.nba.allstar_games_stats_temp').select('Season.count').to_pandas().values[0][0] assert table_count == csv...
_____no_output_____
Apache-2.0
notebooks/nessie-iceberg-flink-demo-nba.ipynb
sandhyasun/nessie-demos
Create `experiment` branch--------------------------------As a data analyst we might want to carry out some experiments with some data, without affecting `main` in any way.As in the previous examples, we can just get started by creating an `experiment` branch off of `main`and carry out our experiment, which could consi...
create_ref_catalog("experiment") # Drop the `totals_stats` table on the `experiment` branch table_env.execute_sql("DROP TABLE IF EXISTS experiment_catalog.nba.new_total_stats") # add some salaries for Dirk Nowitzki table_env.execute_sql("""INSERT INTO experiment_catalog.nba.salaries VALUES ('2015-16', 'Dallas Maver...
_____no_output_____
Apache-2.0
notebooks/nessie-iceberg-flink-demo-nba.ipynb
sandhyasun/nessie-demos
Let's take a look at the contents of the `salaries` table on the `experiment` branch.Notice the use of the `nessie` catalog and the use of `@experiment` to view data on the `experiment` branch
table_env.from_path('main_catalog.nba.`salaries@experiment`').select(lit(1).count).to_pandas()
_____no_output_____
Apache-2.0
notebooks/nessie-iceberg-flink-demo-nba.ipynb
sandhyasun/nessie-demos
and compare to the contents of the `salaries` table on the `main` branch. Notice that we didn't have to specify `@branchName` as it defaultedto the `main` branch
table_env.from_path('main_catalog.nba.`salaries@main`').select(lit(1).count).to_pandas()
_____no_output_____
Apache-2.0
notebooks/nessie-iceberg-flink-demo-nba.ipynb
sandhyasun/nessie-demos
Make model
model = tf.keras.models.Sequential() model.add(tf.keras.layers.Embedding(input_length=500, input_dim=10000, output_dim=24)) # input layer model.add(tf.keras.layers.LSTM(24, return_sequences=True, activation='tanh')) # LSTM을 하나 더 쓸 때 model.add(tf.keras.layers.LSTM(12, activation='tanh')) # model.add(tf.keras.layers.Fl...
Epoch 1/100 25/25 [==============================] - 20s 658ms/step - loss: 3.7195 - acc: 0.2704 - val_loss: 3.4674 - val_acc: 0.0479 Epoch 2/100 25/25 [==============================] - 16s 627ms/step - loss: 3.2134 - acc: 0.2591 - val_loss: 2.9466 - val_acc: 0.3532 Epoch 3/100 25/25 [==============================] -...
Apache-2.0
reuter_LSTM.ipynb
tecktonik08/test_deeplearning
Evaluation
# 학습시켰던 데이터 model.evaluate(pad_x_train, y_train)
281/281 [==============================] - 16s 56ms/step - loss: 1.3192 - acc: 0.6544
Apache-2.0
reuter_LSTM.ipynb
tecktonik08/test_deeplearning
x_test 데이터 전처리
pad_x_test = tf.keras.preprocessing.sequence.pad_sequences(x_test, maxlen=500) def pad_make(x_data): pad_x = tf.keras.preprocessing.sequence.pad_sequences(x_data, maxlen=500) return pad_x pad_make_x = pad_make(x_test) model.evaluate(pad_make_x, y_test) model.evaluate(pad_x_test, y_test)
71/71 [==============================] - 4s 57ms/step - loss: 1.9766 - acc: 0.5419
Apache-2.0
reuter_LSTM.ipynb
tecktonik08/test_deeplearning
train과 test의 acc 유사하기 때문에 학습이 잘 됨을 볼 수 있음
import matplotlib.pyplot as plt plt.plot(hist.history['loss']) plt.plot(hist.history['val_loss']) plt.show() plt.plot(hist.history['acc']) plt.plot(hist.history['val_acc']) plt.show() from sklearn.metrics import classification_report y_train_pred = model.predict(pad_x_train) y_train_pred[0] y_pred = np.argmax(y_train_p...
precision recall f1-score support 0 0.00 0.00 0.00 12 1 0.17 0.53 0.26 105 2 0.00 0.00 0.00 20 3 0.93 0.89 0.91 813 4 0.70 0.72 0.71 ...
Apache-2.0
reuter_LSTM.ipynb
tecktonik08/test_deeplearning
비슷한 부분끼리 0임을 확인 -> words=10000 제한 때문에 0이 발생
_____no_output_____
Apache-2.0
reuter_LSTM.ipynb
tecktonik08/test_deeplearning
''' install 3dparty sheit ''' from IPython.display import clear_output as cle from pprint import pprint as print from PIL import Image import os import sys import json import IPython ''' default sample data delete ''' os.system('rm -r sample_data') ''' set root paths ''' root = '/content' gdrive_root = '/content/driv...
_____no_output_____
BSD-2-Clause
latestv1.ipynb
bxck75/Python_Helpers
parser = argparse.ArgumentParser(add_help=False)parser.add_argument('--zoo', default=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'models.yml'), help='An optional path to file with preprocessing parameters.')parser.add_argument('--input', help='Path to input image or video file. Skip this...
# !wget https://drive.google.com/open?id=1KNfN-ktxbPJMtmdiL-I1WW0IO1B_2EG2 # landmarks_file=['1KNfN-ktxbPJMtmdiL-I1WW0IO1B_2EG2','/content/shape_predictor_68_face_landmarks.dat'] # fromGdrive.GdriveD(landmarks_file[0],landmarks_file[1]) import cv2 import numpy import dlib import matplotlib.pyplot as plt # cap = cv2.Vi...
_____no_output_____
BSD-2-Clause
latestv1.ipynb
bxck75/Python_Helpers
Dieser Block erzeugt eine Darstellung, die die ganze Breite des Fensters ausnutzt.
%%HTML <style>.container{width:100%;}</style>
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Dieser Block schaltet die Überprüfung auf Schönheitsfehler ein. Wir ignorieren die Konvention, dass zwischen Definitionen zwei Leerzeilen stehen sollen, um die Lesbarkeit zu erhöhen. Wir erlauben auch mehrere Leerzeichen vor einem Operator, um sequenzielle Zuweisungen am `=` ausrichten zu können.
%load_ext pycodestyle_magic %flake8_on --ignore E302,E305,E221
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Wir benötigen außerdem *Graphviz* zur Visualisierung.
import graphviz
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Splay TreesIn diesem Notebook wird eine bestimmte Art von selbstbalancierenden Bäumen gezeigt, die *Splay Trees*. Diese Datenstruktur wurde [1985 von Sleator und Tarjan eingeführt](http://www.cs.cmu.edu/~sleator/papers/self-adjusting.pdf "D. D. Sleator, R. E. Tarjan (1985): Self-Adjusting Binary Search Trees. Journal ...
class Node: def __init__(self, payload, left, right): self.payload = payload self.left = left self.right = right
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Wir verlangen dabei:- Für alle Nutzlasten aus dem linken Teilbaum $l$ gilt, dass sie kleiner als die Nutzlast $p$ sind.- Für alle Nutzlasten aus dem rechten Teilbaum $r$ gilt, dass sie größer als die Nutzlast $p$ sind.Diese Aussagen können auch als $l < p < r$ formuliert werden. VisualisierungWir wollen, um die Splay T...
def _graph(self, dot, used, key): used.add(id(self)) dot.node(str(id(self)), label=str(self.payload)) if not (self.left is None and self.right is None): for node in self.left, self.right: if node is not None: dot.edge(str(id(self)), str(id(node))) key = no...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Die nach außen offenstehende Methode `graph` (ohne Unterstrich) der Klasse `Node` leistet nur die Vorarbeit für `_graph` und ruft diese Methode dann auf. `graph` unterstützt allerdings beliebig viele `additionals`, also `Node`s, die in dieser Reihenfolge ebenfalls in den Graphen eingefügt werden. So können wir mehrere ...
def graph(self, *additionals): dot = graphviz.Digraph() used = set() key = self._graph(dot, used, 0) for el in additionals: key = el._graph(dot, used, key) return dot Node.graph = graph del graph
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Um bei solchen Schritten anmerken zu können, was geschieht, definieren wir die Klasse `Method`, die sich auch mit `_graph` visualisieren lassen kann. Solche Knoten werden dann als Rechtecke angezeigt.
class Method: def __init__(self, name): self.name = name def _graph(self, dot, used, key): used.add(id(self)) dot.node(str(id(self)), label=str(self.name) + " ⇒", shape="rectangle", style="dotted") return key
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Zuletzt definieren wir `TempTree`, dessen Verbindung zu seinem einzigen (links oder rechts sitzenden) Kind an der Seite statt unten sitzt und gestrichelt gezeichnet wird. Der Baum selbst wird als Dreieck gezeichnet. Wir werden damit später Bäume visualisieren, bei denen wir nur die äußersten Knoten zeichnen und dazwisc...
class TempTree: def __init__(self, name, child, left): self.name = name self.child = child self.left = left def _graph(self, dot, used, key): used.add(id(self)) dot.node(str(id(self)), label=str(self.name), shape="triangle") if self.child is not None: ...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
SplayingDie Besonderheit von Splay Trees ist, dass mit allen Baumoperationen, die ein Element im Baum lokalisieren, eine besondere Operation, der *Splay*, durchgeführt wird. Mit Baumoperationen, die ein Element im Baum lokalisieren, sind alle Operationen auf den Baum gemeint, die den Baum auf der Suche nach einem Elem...
# flake8: noqa # blocks solely for drawing are exempt because I consider # semicolons and longer lines more beneficial to the reading flow there x1 = Node("x", None, None); y1 = Node("y", None, None); z1 = Node("z", None, None) a1 = Node("a", x1, y1); b1 = Node("b", a1, z1) l1 = TempTree("L", None, False); r1 = TempTre...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Wir bewegen den Knoten $a$ an die Wurzel, wobei $b$ gemeinsam mit seinem rechten Teilbaum $z$ links unten an $R$ angefügt wird. Die Ordnung bleibt erhalten, da $b > a$ ist, und da alle Elemente, die zuvor schon in $R$ waren, auch größer als $b$ sind.Formal definieren wir$$\langle L, \mathrm{Node}(b, \mathrm{Node}(a, x,...
def _zig(self, max_less, min_greater): # self = Node(b, Node(a, x, y), z) min_greater.left = self new_min_greater = self # new_min_greater = Node(b, Node(a, x, y), z) new_self = self.left # new_self = Node(a, x, y) new_min_greater.left = None # new_min_greater = Node(b, Nil, z) retu...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Bei *Zag* ist der zu splayende Knoten das rechte Kind der Wurzel:
# flake8: noqa x1 = Node("x", None, None); y1 = Node("y", None, None); z1 = Node("z", None, None) a1 = Node("a", y1, z1); b1 = Node("b", x1, a1) l1 = TempTree("L", None, False); r1 = TempTree("R", None, True) x2 = Node("x", None, None); y2 = Node("y", None, None); z2 = Node("z", None, None) a2 = Node("a", y2, z2); b2 ...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Formale Definition und Implementierung sind ähnlich.$$\langle L, \mathrm{Node}(b, x, \mathrm{Node}(a, y, z)), R\rangle.\mathrm{splay\_step}(a) = \langle L.\mathrm{insert\_right}(\mathrm{Node}(b, x, \mathrm{Nil})), \mathrm{Node}(a, y, z), R\rangle.\mathrm{splay\_step}(a)$$
def _zag(self, max_less, min_greater): # self = Node(b, x, Node(a, y, z)) max_less.right = self new_max_less = self # new_min_greater = Node(b, x, Node(a, y, z)) new_self = self.right # new_self = Node(a, y, z) new_max_less.right = None # new_min_greater = Node(b, x, Nil) return ne...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Zig-Zig und Zag-ZagAls nächstes behandeln wir den Fall, dass der Knoten wenigstens zwei Ebenen von der Wurzel entfernt ist, und sowohl der Knoten als auch sein Elternknoten ein linkes Kind sind. Die Operation, die auf diese Ausgangssituation anzuwenden ist, bezeichnen wir als *Zig-Zig*. Diese Operation sieht so aus:
# flake8: noqa w1 = Node("w", None, None); x1 = Node("x", None, None); y1 = Node("y", None, None); z1 = Node("z", None, None) a1 = Node("a", w1, x1); b1 = Node("b", a1, y1); c1 = Node("c", b1, z1) l1 = TempTree("L", None, False); r1 = TempTree("R", None, True) w2 = Node("w", None, None); x2 = Node("x", None, None); y2...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Wir bewegen den Knoten $a$ an die Wurzel. $b$ wird mit $c$ als rechtes Kind an $R$ angefügt, wobei $c$ als seinen linken Teilbaum $y$ hat. Die Ordnungsbedingung bleibt erhalten, da $c > b > a$ und $y > c > b$ ist.Wir definieren$$k < b \Rightarrow \langle L, \mathrm{Node}(c, \mathrm{Node}(b, \mathrm{Node}(a, w, x), y), ...
def _zig_zig(self, max_less, min_greater): # self = Node(c, Node(b, Node(a, w, x), y), z) min_greater.left = self.left new_min_greater = self.left # new min_greater = Node(b, Node(a, w, x), y) new_self = new_min_greater.left # new_self = Node(a, w, x) self.left = new_min_greater.right #...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Wir bezeichnen die gleiche Situation mit rechtem Kind und rechtem Enkel als *Zag-Zag*:
# flake8: noqa w1 = Node("w", None, None); x1 = Node("x", None, None); y1 = Node("y", None, None); z1 = Node("z", None, None) a1 = Node("a", y1, z1); b1 = Node("b", x1, a1); c1 = Node("c", w1, b1) l1 = TempTree("L", None, False); r1 = TempTree("R", None, True) w2 = Node("w", None, None); x2 = Node("x", None, None); y2...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Der Splay-Schritt ist ähnlich definiert und implementiert.$$k > b \Rightarrow \langle L, \mathrm{Node}(c, w, \mathrm{Node}(b, x, \mathrm{Node}(a, y, z))), R\rangle.\mathrm{splay\_step}(k) = $$$$= \langle L.\mathrm{insert\_right}(\mathrm{Node}(b, \mathrm{Node}(c, w, x), \mathrm{Nil})), \mathrm{Node}(a, y, z), R\rangle.\...
def _zag_zag(self, max_less, min_greater): # self = Node(c, w, Node(b, x, Node(a, y, z))) max_less.right = self.right new_max_less = self.right # new_max_less = Node(b, x, Node(a, y, z)) new_self = new_max_less.right # new_self = Node(a, y, z) self.right = new_max_less.left # self = Nod...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Zig-Zag und Zag-ZigZuletzt behandeln wir den Fall, dass der Elternknoten ein linkes Kind, der Knoten selbst aber ein rechtes Kind ist. Die Operation auf diese Situation nennen wir *Zig-Zag*. Für diese Operation brauchen wir erstmalig sowohl $L$ als auch $R$:
# flake8: noqa w1 = Node("w", None, None); x1 = Node("x", None, None) y1 = Node("y", None, None); z1 = Node("z", None, None) a1 = Node("a", x1, y1); b1 = Node("b", w1, a1); c1 = Node("c", b1, z1) l1 = TempTree("L", None, False); r1 = TempTree("R", None, True) w2 = Node("w", None, None); x2 = Node("x", None, None) y2 =...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Wir bewegen den Knoten $a$ an die Stelle von $c$, dabei werden $b$ und $c$ respektive an $L$ und $R$ angefügt, die ja jeweils kleiner bzw. größer als $a$ sind.Wir definieren$$b < k < c \Rightarrow \langle L, \mathrm{Node}(c, \mathrm{Node}(b, w, \mathrm{Node}(a, x, y)), z), R\rangle.\mathrm{splay\_step}(k) =$$$$= \langl...
def _zig_zag(self, max_less, min_greater): # self = Node(c, Node(b, w, Node(a, x, y)), z) max_less.right = self.left new_max_less = self.left # new_max_less = Node(b, w, Node(a, x, y)) min_greater.left = self new_min_greater = self # new_min_greater = Node(c, Node(b, w, Node(a, x, y)), z) ...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
In umgekehrter Reihenfolge, d.h. der Elternknoten ist das rechte Kind, der Knoten das linke Kind, haben wir die Operation *Zag-Zig* mit
# flake8: noqa w1 = Node("w", None, None); x1 = Node("x", None, None) y1 = Node("y", None, None); z1 = Node("z", None, None) a1 = Node("a", x1, y1); b1 = Node("b", a1, z1); c1 = Node("c", w1, b1) l1 = TempTree("L", None, False); r1 = TempTree("R", None, True) w2 = Node("w", None, None); x2 = Node("x", None, None) y2 =...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Formal schreiben wir$$c < k < b \Rightarrow \langle L, \mathrm{Node}(c, w, \mathrm{Node}(b, \mathrm{Node}(a, x, y), z)), R\rangle.\mathrm{splay\_step}(k) =$$$$= \langle L.\mathrm{insert\_right}(\mathrm{Node}(c, w, \mathrm{Nil})), \mathrm{Node}(a, x, y), R.\mathrm{insert\_left}(\mathrm{Node}(b, \mathrm{Nil}, z))\rangle....
def _zag_zig(self, max_less, min_greater): # self = Node(c, w, Node(b, Node(a, x, y), z)) max_less.right = self new_max_less = self # new_max_less = Node(c, w, Node(b, Node(a, x, y), z)) min_greater.left = self.right new_min_greater = self.right # new_min_greater = Node(b, Node(a, x, y), z...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Vergleich beliebiger NutzlastenWir müssen, um später Mengen, die Elemente unterschiedlicher Typen enthalten, zu unterstützen, dazu in der Lage sein, beliebige Nutzlasten zu vergleichen. Dazu versuchen wir den direkten Vergleich, und vergleichen, wenn das nicht funktioniert, am Klassennamen. So kommen wertgleiche Fließ...
def _arb_gt(self, x, y): try: return y < x except TypeError: return type(x).__name__ > type(y).__name__ Node._arb_gt = _arb_gt del _arb_gt
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
`_arb_lt(x, y)` überprüft `x` $<$ `y`…
def _arb_lt(self, x, y): try: return x < y except TypeError: return type(x).__name__ < type(y).__name__ Node._arb_lt = _arb_lt del _arb_lt
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
…und `_arb_eq(x, y)` überprüft `x == y`.
def _arb_eq(self, x, y): try: return x == y except TypeError: return False Node._arb_eq = _arb_eq del _arb_eq
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Verkettung der SchritteDer formalen Definition fehlt noch der Basisfall, wenn die Wurzel die zu splayende Nutzlast enthält. Wir fügen dann $L$ und $R$ an die neue Wurzel an – die Knoten in $L$ und $R$ waren ja gerade eben kleiner bzw. größer als die Wurzel. Wir fügen dabei die Teilbäume, die die Wurzel jetzt noch hat,...
# flake8: noqa x1 = Node("x", None, None); y1 = Node("y", None, None); a1 = Node("a", x1, y1) l1 = TempTree("L", None, False); r1 = TempTree("R", None, True) x2 = Node("x", None, None); y2 = Node("y", None, None) l2 = TempTree("L", x2, False); r2 = TempTree("R", y2, True) a2 = Node("a", l2, r2) dot = l1.graph(a1, r1,...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Wir definieren:$$\langle L, \mathrm{Node}(a, x, y), R\rangle.\mathrm{splay\_step}(a) = \langle\mathrm{Nil}, \mathrm{Node}(a, L.\mathrm{insert\_right}(x), R.\mathrm{insert\_left}(y)), \mathrm{Nil}\rangle$$Wir müssen allerdings auch den Basisfall betrachten, dass wir feststellen, dass der Knoten nicht vorhanden ist, weil...
def _splay_step(self, max_less, min_greater, payload): if self._arb_lt(payload, self.payload): if self.left is None: return max_less, self, min_greater if self._arb_lt(payload, self.left.payload) \ and self.left.left is not None: new_max_less, new_self, new_mi...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
In der Zusammensetzung `_splay` fügen wir noch die Teilbäume von der neuen Wurzel an $L, R$ an und setzen $L, R$ als Teilbäume dieser neuen Wurzel. Wir benutzen statt $L, R$ nur einen Baum `set_aside`, bei dem wir auf der entsprechenden Seite anfügen.
def _splay(self, payload): set_aside = Node(None, None, None) max_less, new_self, min_greater = \ self._splay_step(set_aside, set_aside, payload) max_less.right = new_self.left min_greater.left = new_self.right new_self.left = set_aside.right new_self.right = set_aside.left re...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Das nächste Beispiel zeigt, wie ein Splay aus einem schlechtestmöglich balancierten Baum einen deutlich besser balancierten Baum machen kann:
# flake8: noqa a1 = Node("a", None, None); c1 = Node("c", None, None); e1 = Node("e", None, None); g1 = Node("g", None, None) j1 = Node("j", None, None); l1 = Node("l", None, None); n1 = Node("n", None, None); p1 = Node("p", None, None) b1 = Node("b", a1, c1); d1 = Node("d", b1, e1); f1 = Node("f", d1, g1); h1 = Node("...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Ein anderes Beispiel enthält alle Schritte außer Zag:
# flake8: noqa j1 = Node("j", None, None); l1 = Node("l", None, None); n1 = Node("n", None, None); p1 = Node("p", None, None) g1 = Node("g", None, None); e1 = Node("e", None, None); r1 = Node("r", None, None); c1 = Node("c", None, None) a1 = Node("a", None, None); t1 = Node("t", None, None); v1 = Node("v", None, None) ...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Wir betrachten zuletzt das folgende Beispiel, um Zag abgedeckt zu haben:
# flake8: noqa a1 = Node("a", None, None); c1 = Node("c", None, None); e1 = Node("e", None, None) d1 = Node("d", c1, e1); b1 = Node("b", a1, d1) a2 = Node("a", None, None); c2 = Node("c", None, None); e2 = Node("e", None, None) d2 = Node("d", c2, e2); b2 = Node("b", a2, d2) dot = b1.graph(Method("splay()"), b2._splay...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
StandardoperationenWir definieren für den Splay Tree als nächstes die grundlegenden Operationen auf Bäume: Einfügen, Löschen, auf das Vorhandensein eines Elements überprüfen, und auf das Leersein überprüfen. EinfügenWir definieren das Einfügen eines Elementes, bei dem in einen bestehenden Baum eine neue Nutzlast einge...
# flake8: noqa B = Node("B", None, None); k1 = Node("k", None, None) y2 = Node("y", None, None); z2 = Node("z", None, None); x2 = Node("x", y2, z2); k2 = Node("k", None, None) y3 = Node("y", None, None); z3 = Node("z", None, None); x3 = Node("x", None, z3); k3 = Node("k", y3, x3) dot = k1.graph(B, Method("B.splay(k)")...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Im Fall, dass $k$ größer als die Wurzel $x$ des gesplayten Baums $B' = \mathrm{Node}(x, y, z)$ ist, sind umgekehrt alle Elemente in dessen rechten Teilbaum $z$ größer als $k$, und wir setzen die Wurzel dieses Baumes $x$ als linken Teilbaum des neuen Elements $k$, wobei dieser Knoten dann als linken Teilbaum $y$ hat, al...
# flake8: noqa B = Node("B", None, None); k1 = Node("k", None, None) y2 = Node("y", None, None); z2 = Node("z", None, None); x2 = Node("x", y2, z2); k2 = Node("k", None, None) y3 = Node("y", None, None); z3 = Node("z", None, None); x3 = Node("x", y3, None); k3 = Node("k", x3, z3) dot = B.graph(k1, Method("B.splay(k)")...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Für den leeren Baum brauchen wir nur das Element in einen neuen Knoten setzen. Wir definieren – unter anderem zur Betrachtung des Falls des leeren Baumes – die Klasse `SplayTree`, die das Management des leeren Baums wie auch der Tatsache, dass sich bei einem Splay die Wurzel ändert, nach außen vereinfacht.
class SplayTree: def __init__(self): self.tree = None def insert(self, payload): if self.tree is None: self.tree = Node(payload, None, None) else: self.tree = self.tree.insert(payload)
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Für den `SplayTree` definieren wir außerdem `graph`, um `Node.graph` zu exponieren.
def graph(self): if self.tree is None: return graphviz.Digraph() return self.tree.graph() SplayTree.graph = graph del graph
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Einige Beispiele zeigen das Einsetzen von Knoten in Splay Trees:
my_splay = SplayTree() my_splay.insert("a") my_splay.graph() my_splay.insert("c") my_splay.graph() my_splay.insert("b") my_splay.graph()
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
EntfernenWir definieren als nächstes das Entfernen eines Elementes, bei dem ebenfalls eine Nutzlast aus einem bestehenden Baum entfernt wird, wobei sich der Baum i.A. verändert.$$\mathrm{Node}.\mathrm{remove}: \mathrm{Payload} \to \mathrm{Node}$$Wir splayen wieder am zu entfernenden Element und haben dann einen Baum, ...
# flake8: noqa B = Node("B", None, None) v1 = Node("v", None, None); w1 = Node("w", None, None); y1 = Node("y", None, None); x1 = Node("x", w1, y1); k1 = Node("k", v1, x1) v2 = Node("v", None, None); y2 = Node("y'", None, None); x2 = Node("x'", None, y2); k2 = Node("k", v2, x2) v3 = Node("v", None, None); y3 = Node("y'...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Wir machen aus dem Baum $\mathrm{Node}(x, w, y)$ den Baum $\mathrm{Node}(x', \mathrm{Nil}, y')$, indem wir an $k$ splayen. Da das Minimum aus $\mathrm{Node}(x, w, y)$ größer $k$ ist, muss dann gerade dieses Minimum die Wurzel ($x'$) werden und kann keinen linken Teilbaum mehr haben.$$B.\mathrm{splay}(k) = \mathrm{Node}...
def remove(self, payload): self = self._splay(payload) if not self._arb_eq(payload, self.payload): return False, self if self.left is None: return True, self.right if self.right is None: return True, self.left tmp = self.left self = self.right._splay(payload) ...
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Wir werfen in der Implementierung erst auf Ebene von `SplayTree` den `KeyError`, um im Baum noch aufräumen zu können. Der Nutzer könnte ja im Falle eines `KeyError`s diesen auffangen wollen und die Menge trotzdem noch benutzen wollen.
def remove(self, payload): if self.tree is None: raise KeyError(payload) rc, self.tree = self.tree.remove(payload) if not rc: raise KeyError(payload) SplayTree.remove = remove del remove
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Einige Beispiele zeigen das Entfernen von Elementen.
my_splay = SplayTree() for letter in ["a", "c", "b"]: my_splay.insert(letter) my_splay.graph() my_splay.remove("b") my_splay.graph() my_splay.remove("a") my_splay.graph()
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
FindenWir definieren als nächstes das Überprüfen eines Baumes auf ein Element. In unserer Definition wird ein Tupel aus dem Vorhandensein und der neuen Wurzel zurückgegeben.$$\mathrm{Node}.\mathrm{contains}: \mathrm{Payload} \to \langle\mathbb{B}, \mathrm{Node}\rangle$$Wir splayen am gesuchten Element und können schon...
def contains(self, payload): self = self._splay(payload) return self._arb_eq(payload, self.payload), self Node.contains = contains del contains
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
und für den `SplayTree`
def contains(self, payload): if self.tree is None: return False contains, self.tree = self.tree.contains(payload) return contains SplayTree.contains = contains del contains
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Beispiele zeigen uns:
my_splay = SplayTree() for letter in ["a", "c", "b"]: my_splay.insert(letter) my_splay.graph() my_splay.contains("a") my_splay.graph() my_splay.contains("d") my_splay.graph()
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
LeerüberprüfungWir definieren zuletzt, wie wir überprüfen, ob der Baum leer ist.$$\mathrm{Node}.\mathrm{is\_empty}: \langle\rangle \to \mathbb{B}$$$$\mathrm{Node}.\mathrm{is\_empty}() = (\mathrm{Node} = \mathrm{Nil})$$Die Implementierung findet von `SplayTree` aus statt.
def is_empty(self): return self.tree is None SplayTree.is_empty = is_empty del is_empty my_splay = SplayTree() my_splay.is_empty() my_splay.insert("a") my_splay.is_empty()
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
DemonstrationAls kleine Demonstration von `SplayTree` implementieren wir damit die Ermittlung aller Primzahlen bis zu einer Zahl `n` mit dem *Sieb des Eratosthenes*:
def primes(n): primes = SplayTree() for i in range(2, n + 1): primes.insert(i) for i in range(2, n + 1): for j in range(2 * i, n + 1, i): try: primes.remove(j) except KeyError: pass return primes
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Da die Zahlen sequenziell betrachtet wurden, ist der Baum zunächst maximal unbalanciert:
tree = primes(25) tree.graph()
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Wir sehen aber zum Beispiel, dass schon durch einen Splay ein deutlich besser balancierter Baum entsteht:
tree.tree = tree.tree._splay(7) tree.graph()
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Da wir dieses Notebook noch wiederverwenden, entfernen wir irrelevante Namen aus dem Namespace.
del B, a1, a2, b1, b2, c1, c2, d1, d2, dot, e1, e2, f1, f2, g1, g2, h1, h2, \ j1, j2, k1, k2, k3, l1, l2, letter, m1, m2, my_splay, n1, n2, o1, o2, p1, \ p2, primes, q1, q2, r1, r2, s1, s2, subtree, t1, t2, tree, v1, v2, v3, \ w1, w2, x1, x2, x3, y1, y2, y3, z1, z2, z3
_____no_output_____
MIT
1-Splay-Trees.ipynb
jakobn-ai/SplayPy-Paper
Notebook to play with some graph forms...
### Standard Magic and startup initializers. import math import csv import numpy as np import random import itertools import matplotlib import matplotlib.pyplot as plt import pandas as pd %matplotlib inline matplotlib.style.use('seaborn-whitegrid') font = {'family' :'serif', 'size' : 22} matplotlib.rc('f...
2 5 10 5 0.006819 0.016678 0.033212 10 0.063348 0.178242 0.377655 30 2.620236 9.073796 23.524422 50 25.765830 89.238418 222.992741 70 107.386757 379.349311 787.160301 2 5 10 5 0.005216 0.010583 0.020155 10 ...
BSD-3-Clause
Graphing.ipynb
nmattei/InterdependentSchedulingGames
# Gives us a well defined version of tensorflow try: # %tensorflow_version only exists in Colab. %tensorflow_version 2.x except Exception: pass # will also work, but nightly build might contain surprises # !pip install -q tf-nightly-gpu-2.0-preview import tensorflow as tf print(tf.__version__) import matplotli...
_____no_output_____
MIT
notebooks/tf2/tf-dense-insurance-reg.ipynb
kmunve/ml-workshop
An experimental approach:- keep adding regularization to make validation and train scores come closer to each other- this will come at the cost of train scores going down- if both values start going down you have gone too far- each experiment takes some time- for larger datasets and more complex models some people sta...
from tensorflow.keras.layers import Input, Dense, Dropout, \ BatchNormalization, Activation num_features = 3 num_categories = 3 dropout = 0.6 model = keras.Sequential() model.add(Input(name='input', shape=(num_features,))) # reduce capacity by decreasing number of neurons model.a...
_____no_output_____
MIT
notebooks/tf2/tf-dense-insurance-reg.ipynb
kmunve/ml-workshop
Notebook TemplateThis Notebook is stubbed out with some project paths, loading of enviroment variables, and common package imports to speed up the process of starting a new project.It is highly recommended you copy and rename this notebook following the naming convention outlined in the readme of naming notebooks with...
import importlib import os from pathlib import Path import sys from arcgis.features import GeoAccessor, GeoSeriesAccessor from arcgis.gis import GIS from dotenv import load_dotenv, find_dotenv import pandas as pd # import arcpy if available if importlib.util.find_spec("arcpy") is not None: import arcpy # paths to...
_____no_output_____
Apache-2.0
notebooks/notebook-template.ipynb
knu2xs/white-pass-feature-selection
Benchmarking Annotation StorageClick to open in: [[GitHub](https://github.com/TissueImageAnalytics/tiatoolbox/tree/master/benchmarks/annotation_store.ipynb)][[Colab](https://colab.research.google.com/github/TissueImageAnalytics/tiatoolbox/blob/master/benchmarks/annotation_store.ipynb)][[Kaggle](https://kaggle.com/kern...
import sys sys.path.append("..") # If running locally without pypi installed tiatoolbox import copy import pickle import tempfile import timeit import uuid from numbers import Number from pathlib import Path from typing import Generator, List, Optional, Tuple import numpy as np from IPython.display import display f...
_____no_output_____
BSD-3-Clause
benchmarks/annotation_store.ipynb
adamshephard/tiatoolbox
Data Generation & Utility FunctionsHere we define some useful functions to generate some artificial dataand visualise results.
def cell_polygon( xy: Tuple[Number, Number], n_points: int = 20, radius: Number = 8, noise: Number = 0.01, eccentricity: Tuple[Number, Number] = (1, 3), repeat_first: bool = True, direction: str = "CCW", seed:int = 0, ) -> Polygon: """Generate a fake cell boundary polygon. Borro...
_____no_output_____
BSD-3-Clause
benchmarks/annotation_store.ipynb
adamshephard/tiatoolbox
Display Some Generated Data
for n in range(4): display(cell_polygon(xy=(0, 0), n_points=20, repeat_first=False, seed=n))
_____no_output_____
BSD-3-Clause
benchmarks/annotation_store.ipynb
adamshephard/tiatoolbox
Randomised Cell BoundariesHere we create a function to generate grid of cells for testing. It uses a fixed seed for reproducibility. A Sample 5×5 Grid
from shapely.geometry import MultiPolygon MultiPolygon(polygons=list(cell_grid(size=(5, 5), spacing=35)))
_____no_output_____
BSD-3-Clause
benchmarks/annotation_store.ipynb
adamshephard/tiatoolbox
Part 1: Small Scale Benchmarking of Annotation StorageUsing the already defined data generation functions (`cell_polygon` and`cell_grid`), we create some simple artificial cell boundaries bycreating a circle of points, adding some noise, scaling to introduceeccentricity, and then rotating. We use 20 points per cell, ...
# Convert to annotations (a dataclass pairing a geometry and (optional) # key-value properties) # Run time: ~2s annotations = [ Annotation(polygon) for polygon in cell_grid(size=(100, 100), spacing=35) ]
_____no_output_____
BSD-3-Clause
benchmarks/annotation_store.ipynb
adamshephard/tiatoolbox
1.1.1) In Memory Append
# Run time: ~5s # Time dictionary store dict_runs = timeit.repeat( "dict_store.append_many(annotations)", setup="dict_store = DictionaryStore()", globals={"DictionaryStore": DictionaryStore, "annotations": annotations}, number=1, repeat=3, ) # Time SQLite store sqlite_runs = timeit.repeat( "sq...
_____no_output_____
BSD-3-Clause
benchmarks/annotation_store.ipynb
adamshephard/tiatoolbox
Note that inserting into the `SQLiteStore` is much slower than the`DictionaryStore`. Appending to a `Dictionary` store simply requiresadding a memory reference to a dictionary. Therefore, this is a veryfast operation. On the other hand, for the `SQLiteStore`, the insertionis slower because the data must be serialised f...
# Run time: ~10s setup = "fp.truncate(0)\n" "store = Store(fp)" # Clear the file # Time dictionary store with tempfile.NamedTemporaryFile("w+") as fp: dict_runs = timeit.repeat( ("store.append_many(annotations)\n" "store.commit()"), setup=setup, globals={"Store": DictionaryStore, "annotat...
_____no_output_____
BSD-3-Clause
benchmarks/annotation_store.ipynb
adamshephard/tiatoolbox
Here we can see that when we include the serialisation to disk in thebenchmark, the time to insert is much more similar. 1.2) Box Query
# Run time: ~20s # One time Setup dict_store = DictionaryStore() sql_store = SQLiteStore() dict_store.append_many(annotations) sql_store.append_many(annotations) np.random.seed(123) boxes = [ Polygon.from_bounds(x, y, 128, 128) for x, y in np.random.randint(0, 1000, size=(100, 2)) ] stmt = "for box in boxes:\...
_____no_output_____
BSD-3-Clause
benchmarks/annotation_store.ipynb
adamshephard/tiatoolbox
Here we can see that the `SQLiteStore` is a bit faster. Addtionally,difference in performance is more pronounced when there are moreannotations (as we will see later in this notebook) in the store or whenjust returning keys:
# Run time: ~15s # One time Setup dict_store = DictionaryStore() sql_store = SQLiteStore() dict_store.append_many(annotations) sql_store.append_many(annotations) np.random.seed(123) boxes = [ Polygon.from_bounds(x, y, 128, 128) for x, y in np.random.randint(0, 1000, size=(100, 2)) ] stmt = "for box in boxes:\...
_____no_output_____
BSD-3-Clause
benchmarks/annotation_store.ipynb
adamshephard/tiatoolbox
1.3) Polygon Query
# Run time: ~15s # One time Setup dict_store = DictionaryStore() sql_store = SQLiteStore() dict_store.append_many(annotations) sql_store.append_many(annotations) np.random.seed(123) query_polygons = [ Polygon( [ (x, y), (x + 128, y), (x + 128, y + 128), (x, ...
_____no_output_____
BSD-3-Clause
benchmarks/annotation_store.ipynb
adamshephard/tiatoolbox
Here we can see that performing queries within a polygon region is about10x faster with the `SQLiteStore` than with the `DictionaryStore`. 1.4) Predicate QueryHere we query the whole annotation region but with a predicate toselect only annotations with the class label of 0. We also,demonstrate how creating a database ...
# Run time: ~2m # Setup labelled_annotations = copy.deepcopy(annotations) for n, annotation in enumerate(labelled_annotations): annotation.properties["class"] = n % 10 annotation.properties["vector"] = np.random.randint(1, 4, 10).tolist() predicate = "(props['class'] == ?) & (3 in props['vector'])" classes = ...
_____no_output_____
BSD-3-Clause
benchmarks/annotation_store.ipynb
adamshephard/tiatoolbox
Polygon & Predicate Query
# Run time: ~10s # Setup labelled_annotations = copy.deepcopy(annotations) for n, annotation in enumerate(labelled_annotations): annotation.properties["class"] = n % 10 predicate = "props['class'] == " classes = np.random.randint(0, 10, size=50) query_polygons = [ Polygon( [ (x, y), ...
_____no_output_____
BSD-3-Clause
benchmarks/annotation_store.ipynb
adamshephard/tiatoolbox
Complex Predicate QueryHere we slightly increase the complexity of the predicate to show howthe complexity of a predicate can dramatically affect the performancewhen handling many annotations.
# Run time: ~1m # Setup box = Polygon.from_bounds(0, 0, 1024, 1024) labelled_annotations = copy.deepcopy(annotations) for n, annotation in enumerate(labelled_annotations): annotation.properties["class"] = n % 4 annotation.properties["n"] = n predicate = "(props['n'] > 1000) & (props['n'] % 4 == 0) & (props['c...
_____no_output_____
BSD-3-Clause
benchmarks/annotation_store.ipynb
adamshephard/tiatoolbox
Part 2: Large Scale Dataset BenchmarkingHere we generate some sets of anntations with five million items each(in a 2237 x 2237 grid). One is a set of points, the other a set ofgenerated cell boundaries.The code to generate and write out the annotations to various formats isincluded in the following cells. However, som...
# Generate some points with a little noise # Run time: ~5s points = np.array( [[x, y] for x in np.linspace(0, 75_000, 2237) for y in np.linspace(0, 75_000, 2237)] ) # Add some noise between -1 and 1 np.random.seed(42) points += np.random.uniform(-1, 1, size=(2237**2, 2))
_____no_output_____
BSD-3-Clause
benchmarks/annotation_store.ipynb
adamshephard/tiatoolbox