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 |
|---|---|---|---|---|---|
We get the top 100 keywords and store the counts toegether with the keywords in a new DF | top_100_zh = yake_df.explode('keywords_classes').keywords_classes.value_counts()[0:100]
top_100_zh = pd.DataFrame(top_100_zh)
# Create new DF from the counts
top_100_zh['zh'] = top_100_zh.index
top_100_zh.reset_index(inplace=True)
top_100_zh
| _____no_output_____ | Apache-2.0 | examples/webinars_conferences_etc/multi_lingual_webinar/4_Unsupervise_Chinese_Keyword_Extraction_NER_and_Translation_from_Chinese_News.ipynb | UPbook-innovations/nlu |
Now we can just translate each predicted keyword with `zh.translate_to.en` in 1 line of code and see what is actually going on in the dataset | top_100_en = nlu.load('zh.translate_to.en').predict(top_100_zh.zh)
top_100_en | translate_zh_en download started this may take some time.
Approx size to download 396.8 MB
[OK!]
| Apache-2.0 | examples/webinars_conferences_etc/multi_lingual_webinar/4_Unsupervise_Chinese_Keyword_Extraction_NER_and_Translation_from_Chinese_News.ipynb | UPbook-innovations/nlu |
Write the translations into the df with the Keyword counts so we can plot them together in the next step | # Write translation back to the keyword df with the counts
top_100_zh['en']= top_100_en.translation
top_100_zh | _____no_output_____ | Apache-2.0 | examples/webinars_conferences_etc/multi_lingual_webinar/4_Unsupervise_Chinese_Keyword_Extraction_NER_and_Translation_from_Chinese_News.ipynb | UPbook-innovations/nlu |
Now we can simply look at every keyword as a bar chart with the actual translation of it and understand what keywordsa ppeared in chinese news! | top_100_zh.index = top_100_zh.en
top_100_zh.keywords_classes.plot.barh(figsize=(20,20), title='Distribution of top 100 translated chinese News Articles generated by YAKE alogirthm applied to RAW data') | _____no_output_____ | Apache-2.0 | examples/webinars_conferences_etc/multi_lingual_webinar/4_Unsupervise_Chinese_Keyword_Extraction_NER_and_Translation_from_Chinese_News.ipynb | UPbook-innovations/nlu |
Apply Yake to Segmented/Tokenized dataWe gave the YAKE algorithm full heatlines which where not segmented. To better understand the Chinese text ,we can segment it into token and analyze their occurcence instead YAKE + Word Segmentation | # Segment words into tokenz with the word segmenter
# This will output 1 row per token
seg_df = nlu.load('zh.segment_words').predict(df.headline)
seg_df | wordseg_weibo download started this may take some time.
Approximate size to download 1.2 MB
[OK!]
| Apache-2.0 | examples/webinars_conferences_etc/multi_lingual_webinar/4_Unsupervise_Chinese_Keyword_Extraction_NER_and_Translation_from_Chinese_News.ipynb | UPbook-innovations/nlu |
Join the tokens back as white space seperated strings for the Yake Keyword extraction in the next step | # Join the tokens back as white space seperated strings
joined_segs = seg_df.token.groupby(seg_df.index).transform(lambda x : ' '.join(x)).drop_duplicates()
joined_segs | _____no_output_____ | Apache-2.0 | examples/webinars_conferences_etc/multi_lingual_webinar/4_Unsupervise_Chinese_Keyword_Extraction_NER_and_Translation_from_Chinese_News.ipynb | UPbook-innovations/nlu |
Now we can extract keywords with yake on the whitespace seperated tokens | seg_yake_df = nlu.load('yake').predict(joined_segs)
seg_yake_df
# Get top 100 occoring Keywords from the joined segmented tokens
top_100_seg_zh = seg_yake_df.explode('keywords_classes').keywords_classes.value_counts()[0:100]#.plot.bar(title='Top 100 in Chinese News Articles Segmented', figsize=(20,8))
top_100_seg_zh = ... | _____no_output_____ | Apache-2.0 | examples/webinars_conferences_etc/multi_lingual_webinar/4_Unsupervise_Chinese_Keyword_Extraction_NER_and_Translation_from_Chinese_News.ipynb | UPbook-innovations/nlu |
Get top 100 keywords and Translate them like we did for the raw Data as data preperation for the visualization of the keyword distribution | # Create new DF from the counts
top_100_seg_zh['zh'] = top_100_seg_zh.index
top_100_seg_zh.reset_index(inplace=True)
# Write Translations back to df with keyword counts
top_100_seg_zh['en'] = nlu.load('zh.translate_to.en').predict(top_100_seg_zh.zh).translation | translate_zh_en download started this may take some time.
Approx size to download 396.8 MB
[OK!]
| Apache-2.0 | examples/webinars_conferences_etc/multi_lingual_webinar/4_Unsupervise_Chinese_Keyword_Extraction_NER_and_Translation_from_Chinese_News.ipynb | UPbook-innovations/nlu |
Visualize the distirbution of the Keywords extracted from the segmented tokensWe can observe that we now have a very different distribution than originally | top_100_seg_zh.index = top_100_seg_zh.en
top_100_seg_zh.keywords_classes.plot.barh(figsize=(20,20), title = 'Segmented Keywords YAKE Distribution') | _____no_output_____ | Apache-2.0 | examples/webinars_conferences_etc/multi_lingual_webinar/4_Unsupervise_Chinese_Keyword_Extraction_NER_and_Translation_from_Chinese_News.ipynb | UPbook-innovations/nlu |
Apply Yake to Segmented and Lemmatized data | # Automated Word Segmentation Included!
zh_lem_df = nlu.load('zh.lemma').predict(df.headline)
zh_lem_df | lemma download started this may take some time.
Approximate size to download 149.5 KB
[OK!]
wordseg_weibo download started this may take some time.
Approximate size to download 1.2 MB
[OK!]
| Apache-2.0 | examples/webinars_conferences_etc/multi_lingual_webinar/4_Unsupervise_Chinese_Keyword_Extraction_NER_and_Translation_from_Chinese_News.ipynb | UPbook-innovations/nlu |
Join tokens into whitespace seperated string like we did previosuly for Word Segmentation | zh_lem_df['lem_str'] = zh_lem_df.lemma.str.join(' ')
zh_lem_df | _____no_output_____ | Apache-2.0 | examples/webinars_conferences_etc/multi_lingual_webinar/4_Unsupervise_Chinese_Keyword_Extraction_NER_and_Translation_from_Chinese_News.ipynb | UPbook-innovations/nlu |
Extract Keywords on Stemmed + Word Segmented Chinese text | yake_lem_df = nlu.load('yake').predict(zh_lem_df.lem_str)
yake_lem_df
top_100_stem = yake_lem_df.explode('keywords_classes').keywords_classes.value_counts()[:100]
top_100_stem = pd.DataFrame(top_100_stem)
# Create new DF from the counts
top_100_stem['zh'] = top_100_stem.index
top_100_stem.reset_index(inplace=True)
# Wr... | translate_zh_en download started this may take some time.
Approx size to download 396.8 MB
[OK!]
| Apache-2.0 | examples/webinars_conferences_etc/multi_lingual_webinar/4_Unsupervise_Chinese_Keyword_Extraction_NER_and_Translation_from_Chinese_News.ipynb | UPbook-innovations/nlu |
Plot the Segmented and Lemmatized Distribution of extracted keywords | top_100_stem.index = top_100_stem.en
top_100_stem.keywords_classes.plot.barh(figsize=(20,20), title='Distribution of top 100 translated chinese News Artzzzicles generated by YAKE alogirthm applied to Lemmatized and Segmented Chinese Text') | _____no_output_____ | Apache-2.0 | examples/webinars_conferences_etc/multi_lingual_webinar/4_Unsupervise_Chinese_Keyword_Extraction_NER_and_Translation_from_Chinese_News.ipynb | UPbook-innovations/nlu |
Extract Chinese Named entities | zh_ner_df = nlu.load('zh.ner').predict(df.iloc[:1000].headline, output_level='document')
zh_ner_df
# Translate Detected Chinese Entities to English
en_entities = nlu.load('zh.translate_to.en').predict(zh_ner_df.explode('entities').entities)
en_entities
en_entities.translation.value_counts()[0:100].plot.barh(figsize=(20... | _____no_output_____ | Apache-2.0 | examples/webinars_conferences_etc/multi_lingual_webinar/4_Unsupervise_Chinese_Keyword_Extraction_NER_and_Translation_from_Chinese_News.ipynb | UPbook-innovations/nlu |
Simple Scatter Plots Another commonly used plot type is the simple scatter plot, a close cousin of the line plot.Instead of points being joined by line segments, here the points are represented individually with a dot, circle, or other shape.We’ll start by setting up the notebook for plotting and importing the functio... | %matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np | _____no_output_____ | MIT | 3.2_Simple-Scatter-Plots.ipynb | anilkumarpanda/python-training-2021 |
Scatter Plots with ``plt.plot``In the previous section we looked at ``plt.plot``/``ax.plot`` to produce line plots.It turns out that this same function can produce scatter plots as well: | x = np.linspace(0, 10, 30)
y = np.sin(x)
plt.plot(x, y, 'o', color='black'); | _____no_output_____ | MIT | 3.2_Simple-Scatter-Plots.ipynb | anilkumarpanda/python-training-2021 |
The third argument in the function call is a character that represents the type of symbol used for the plotting. Just as you can specify options such as ``'-'``, ``'--'`` to control the line style, the marker style has its own set of short string codes. The full list of available symbols can be seen in the documentatio... | rng = np.random.RandomState(0)
for marker in ['o', '.', ',', 'x', '+', 'v', '^', '<', '>', 's', 'd']:
plt.plot(rng.rand(5), rng.rand(5), marker,
label="marker='{0}'".format(marker))
plt.legend(numpoints=1)
plt.xlim(0, 1.8); | _____no_output_____ | MIT | 3.2_Simple-Scatter-Plots.ipynb | anilkumarpanda/python-training-2021 |
For even more possibilities, these character codes can be used together with line and color codes to plot points along with a line connecting them: | plt.plot(x, y, '-ok'); | _____no_output_____ | MIT | 3.2_Simple-Scatter-Plots.ipynb | anilkumarpanda/python-training-2021 |
Additional keyword arguments to ``plt.plot`` specify a wide range of properties of the lines and markers: | plt.plot(x, y, '-p', color='gray',
markersize=15, linewidth=4,
markerfacecolor='white',
markeredgecolor='gray',
markeredgewidth=2)
plt.ylim(-1.2, 1.2); | _____no_output_____ | MIT | 3.2_Simple-Scatter-Plots.ipynb | anilkumarpanda/python-training-2021 |
This type of flexibility in the ``plt.plot`` function allows for a wide variety of possible visualization options.For a full description of the options available, refer to the ``plt.plot`` documentation. Scatter Plots with ``plt.scatter``A second, more powerful method of creating scatter plots is the ``plt.scatter`` f... | plt.scatter(x, y, marker='o'); | _____no_output_____ | MIT | 3.2_Simple-Scatter-Plots.ipynb | anilkumarpanda/python-training-2021 |
The primary difference of ``plt.scatter`` from ``plt.plot`` is that it can be used to create scatter plots where the properties of each individual point (size, face color, edge color, etc.) can be individually controlled or mapped to data.Let's show this by creating a random scatter plot with points of many colors and ... | rng = np.random.RandomState(0)
x = rng.randn(100)
y = rng.randn(100)
colors = rng.rand(100)
sizes = 1000 * rng.rand(100)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.3,
cmap='viridis')
plt.colorbar(); # show color scale | _____no_output_____ | MIT | 3.2_Simple-Scatter-Plots.ipynb | anilkumarpanda/python-training-2021 |
Notice that the color argument is automatically mapped to a color scale (shown here by the ``colorbar()`` command), and that the size argument is given in pixels.In this way, the color and size of points can be used to convey information in the visualization, in order to visualize multidimensional data.For example, we ... | from sklearn.datasets import load_iris
iris = load_iris()
features = iris.data.T
plt.scatter(features[0], features[1], alpha=0.2,
s=100*features[3], c=iris.target, cmap='viridis')
plt.xlabel(iris.feature_names[0])
plt.ylabel(iris.feature_names[1]); | _____no_output_____ | MIT | 3.2_Simple-Scatter-Plots.ipynb | anilkumarpanda/python-training-2021 |
Define Loss and Optimizer | model.parameters
loss_function=nn.MSELoss()
optimizer=torch.optim.Adam(model.parameters(),lr=0.01)
df.shape
cont_values.shape
batch_size=1200
test_size=int(batch_size*0.15)
train_categorical=cat_features[:batch_size-test_size]
test_categorical=cat_features[batch_size-test_size:batch_size]
train_cont=cont_values[:batch_... | _____no_output_____ | MIT | HousePricePrediction.ipynb | pallabi-sahoo/Pytorch |
Working with ````asammdf.MDF```` | from asammdf import MDF, Signal
print(MDF.__doc__) | Unified access to MDF v3 and v4 files. Underlying _mdf's attributes and
methods are linked to the `MDF` object via *setattr*. This is done to expose
them to the user code and for performance considerations.
Parameters
----------
name : string | fsspec.core.OpenFile,
mdf file name (if provid... | MIT | 02_Working_With_MDF_Class.ipynb | SimulinkDevOps/Jupyter_MDF_Analysis |
Create 3 Signal objects | import numpy as np
timestamps = np.array([0.1, 0.2, 0.3, 0.4, 0.5], dtype=np.float32) | _____no_output_____ | MIT | 02_Working_With_MDF_Class.ipynb | SimulinkDevOps/Jupyter_MDF_Analysis |
unit8 | s_uint8 = Signal(samples=np.array([0, 1, 2, 3, 4], dtype=np.uint8),
timestamps=timestamps,
name='Uint8_Signal',
unit='u1') | _____no_output_____ | MIT | 02_Working_With_MDF_Class.ipynb | SimulinkDevOps/Jupyter_MDF_Analysis |
int32 | s_int32 = Signal(samples=np.array([-20, -10, 0, 10, 20], dtype=np.int32),
timestamps=timestamps,
name='Int32_Signal',
unit='i4') | _____no_output_____ | MIT | 02_Working_With_MDF_Class.ipynb | SimulinkDevOps/Jupyter_MDF_Analysis |
float64 | s_float64 = Signal(samples=np.array([-20, -10, 0, 10, 20], dtype=np.float64),
timestamps=timestamps,
name='Float64_Signal',
unit='f8') | _____no_output_____ | MIT | 02_Working_With_MDF_Class.ipynb | SimulinkDevOps/Jupyter_MDF_Analysis |
Create empty MDF version 4.00 file: | with MDF(version="4.10") as mdf4:
# append the 3 signals to the new file
signals = [s_uint8, s_int32, s_float64]
mdf4.append(signals, "Created by Python")
# save new file
mdf4.save("my_new_file.mf4", overwrite=True)
# convert new file to mdf version 3.10
mdf3 = mdf4.convert(version="3.10"... | WARNING:root:Signal plotting requires pyqtgraph or matplotlib
| MIT | 02_Working_With_MDF_Class.ipynb | SimulinkDevOps/Jupyter_MDF_Analysis |
📃 Solution for Exercise M1.04The goal of this exercise is to evaluate the impact of using an arbitraryinteger encoding for categorical variables along with a linearclassification model such as Logistic Regression.To do so, let's try to use `OrdinalEncoder` to preprocess the categoricalvariables. This preprocessor is ... | import pandas as pd
adult_census = pd.read_csv("../datasets/adult-census.csv")
target_name = "class"
target = adult_census[target_name]
data = adult_census.drop(columns=[target_name, "education-num"]) | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline_sol_01.ipynb | odotreppe/scikit-learn-mooc |
In the previous notebook, we used `sklearn.compose.make_column_selector` toautomatically select columns with a specific data type (also called `dtype`).Here, we will use this selector to get only the columns containing strings(column with `object` dtype) that correspond to categorical features in ourdataset. | from sklearn.compose import make_column_selector as selector
categorical_columns_selector = selector(dtype_include=object)
categorical_columns = categorical_columns_selector(data)
data_categorical = data[categorical_columns] | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline_sol_01.ipynb | odotreppe/scikit-learn-mooc |
We filter our dataset that it contains only categorical features.Define a scikit-learn pipeline comBecause `OrdinalEncoder` can raise errors if it sees an unknown category atprediction time, you can set the `handle_unknown="use_encoded_value"` and`unknown_value` parameters. You can refer to the[scikit-learn documentati... |
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OrdinalEncoder
from sklearn.linear_model import LogisticRegression
model = make_pipeline(
OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=-1),
LogisticRegression(max_iter=500)) | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline_sol_01.ipynb | odotreppe/scikit-learn-mooc |
Your model is now defined. Evaluate it using a cross-validation using`sklearn.model_selection.cross_validate`. | from sklearn.model_selection import cross_validate
cv_results = cross_validate(model, data_categorical, target)
scores = cv_results["test_score"]
print("The mean cross-validation accuracy is: "
f"{scores.mean():.3f} +/- {scores.std():.3f}") | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline_sol_01.ipynb | odotreppe/scikit-learn-mooc |
Using an arbitrary mapping from string labels to integers as done here causesthe linear model to make bad assumptions on the relative ordering ofcategories.This prevents the model from learning anything predictive enough and thecross-validated score is even lower than the baseline we obtained by ignoringthe input data ... | from sklearn.dummy import DummyClassifier
cv_results = cross_validate(DummyClassifier(strategy="most_frequent"),
data_categorical, target)
scores = cv_results["test_score"]
print("The mean cross-validation accuracy is: "
f"{scores.mean():.3f} +/- {scores.std():.3f}") | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline_sol_01.ipynb | odotreppe/scikit-learn-mooc |
Now, we would like to compare the generalization performance of our previousmodel with a new model where instead of using an `OrdinalEncoder`, we willuse a `OneHotEncoder`. Repeat the model evaluation using cross-validation.Compare the score of both models and conclude on the impact of choosing aspecific encoding strat... | from sklearn.preprocessing import OneHotEncoder
model = make_pipeline(
OneHotEncoder(handle_unknown="ignore"),
LogisticRegression(max_iter=500))
cv_results = cross_validate(model, data_categorical, target)
scores = cv_results["test_score"]
print("The mean cross-validation accuracy is: "
f"{scores.mean():... | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline_sol_01.ipynb | odotreppe/scikit-learn-mooc |
Copyright 2018 The TensorFlow Authors. | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | MIT | model_tflite/TFLite_FashionMnist.ipynb | alessiot/Flask-Tutorial-TFLite |
Train Your Own Model and Convert It to TFLite Run in Google Colab View source on GitHub This notebook uses the [Fashion MNIST](https://github.com/zalandoresearch/fashion-mnist) dataset which contains 70,000 grayscale images in 10 categories. The images show individual articles of clothin... | try:
%tensorflow_version 2.x
except:
pass
import pathlib
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_datasets as tfds
tfds.disable_progress_bar()
print('\u2022 Using TensorFlow Version:', tf.__version__)
print('\u2022 GPU Device Found.' if tf.test.is_gpu_avail... | • Using TensorFlow Version: 2.4.1
WARNING:tensorflow:From <ipython-input-3-adb891da5723>:11: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.config.list_physical_devices('GPU')` instead.
• GPU Device Not Found. Runni... | MIT | model_tflite/TFLite_FashionMnist.ipynb | alessiot/Flask-Tutorial-TFLite |
Download Fashion MNIST DatasetWe will use TensorFlow Datasets to load the Fashion MNIST dataset. | whole_ds,info_ds = tfds.load("fashion_mnist", with_info = True, split='train+test', as_supervised=True) #60,000+10,000
n = tf.data.experimental.cardinality(whole_ds).numpy() # 70,000
train_num = int(n*0.8) #56,000
val_num = int(n*0.1) #7000
train_examples = whole_ds.take(train_num)
validation_examples = whole_ds.skip... | [1mDownloading and preparing dataset 29.45 MiB (download: 29.45 MiB, generated: 36.42 MiB, total: 65.87 MiB) to /Users/atambu/tensorflow_datasets/fashion_mnist/3.0.1...[0m
[1mDataset fashion_mnist downloaded and prepared to /Users/atambu/tensorflow_datasets/fashion_mnist/3.0.1. Subsequent calls will reuse this data.... | MIT | model_tflite/TFLite_FashionMnist.ipynb | alessiot/Flask-Tutorial-TFLite |
The class names are not included with the dataset, so we will specify them here. | class_names = ['T-shirt_top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# Create a labels.txt file with the class names
with open('labels.txt', 'w') as f:
f.write('\n'.join(class_names))
# The images in the dataset are 28 by 28 pixels.
IMG_SIZE = 28 | _____no_output_____ | MIT | model_tflite/TFLite_FashionMnist.ipynb | alessiot/Flask-Tutorial-TFLite |
Preprocessing data Preprocess | def format_example(image, label):
# Cast image to float32
image = tf.image.convert_image_dtype(image, dtype=tf.float32)
# Normalize the image in the range [0, 1]
image = image/255.0
return image, tf.one_hot(label, num_classes)
# Specify the batch size
BATCH_SIZE = 256 | _____no_output_____ | MIT | model_tflite/TFLite_FashionMnist.ipynb | alessiot/Flask-Tutorial-TFLite |
Create Datasets From Images and Labels | # Create Datasets
train_batches = train_examples.cache().shuffle(num_examples//4).batch(BATCH_SIZE).map(format_example).prefetch(1)
validation_batches = validation_examples.cache().batch(BATCH_SIZE).map(format_example)
test_batches = test_examples.batch(1).map(format_example) | _____no_output_____ | MIT | model_tflite/TFLite_FashionMnist.ipynb | alessiot/Flask-Tutorial-TFLite |
Building the Model ```Model: "sequential"_________________________________________________________________Layer (type) Output Shape Param =================================================================conv2d (Conv2D) (None, 26, 26, 16) 160 ___________________... | model = tf.keras.Sequential([
# Set the input shape to (28, 28, 1), kernel size=3, filters=16 and use ReLU activation,
tf.keras.layers.Conv2D(input_shape=(28,28,1), kernel_size=3, filters=16, activation='relu'),
tf.keras.layers.MaxPooling2D(),
# Set the number of filters to 32, kernel size... | Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 26, 26, 16) 160
____________________________________... | MIT | model_tflite/TFLite_FashionMnist.ipynb | alessiot/Flask-Tutorial-TFLite |
Train | model.fit(train_batches,
epochs=10,
validation_data=validation_batches) | Epoch 1/10
219/219 [==============================] - 10s 43ms/step - loss: 1.8871 - accuracy: 0.3617 - val_loss: 0.7890 - val_accuracy: 0.7144
Epoch 2/10
219/219 [==============================] - 8s 37ms/step - loss: 0.7622 - accuracy: 0.7165 - val_loss: 0.6610 - val_accuracy: 0.7543
Epoch 3/10
219/219 [=============... | MIT | model_tflite/TFLite_FashionMnist.ipynb | alessiot/Flask-Tutorial-TFLite |
Exporting to TFLiteYou will now save the model to TFLite. We should note, that you will probably see some warning messages when running the code below. These warnings have to do with software updates and should not cause any errors or prevent your code from running. | # EXERCISE: Use the tf.saved_model API to save your model in the SavedModel format.
export_dir = 'saved_model/1'
tf.saved_model.save(model, export_dir)
#@title Select mode of optimization
mode = "Speed" #@param ["Default", "Storage", "Speed"]
if mode == 'Storage':
optimization = tf.lite.Optimize.OPTIMIZE_FOR_SIZ... | _____no_output_____ | MIT | model_tflite/TFLite_FashionMnist.ipynb | alessiot/Flask-Tutorial-TFLite |
Test the Model with TFLite Interpreter | # Load TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_content=tflite_model)
interpreter.allocate_tensors()
input_index = interpreter.get_input_details()[0]["index"]
output_index = interpreter.get_output_details()[0]["index"]
# Gather results for the randomly sampled test images
predictions ... | 0 0
| MIT | model_tflite/TFLite_FashionMnist.ipynb | alessiot/Flask-Tutorial-TFLite |
Download the TFLite Model and AssetsIf you are running this notebook in a Colab, you can run the cell below to download the tflite model and labels to your local disk.**Note**: If the files do not download when you run the cell, try running the cell a second time. Your browser might prompt you to allow multiple files ... | try:
from google.colab import files
files.download(tflite_model_file)
files.download('labels.txt')
except:
pass | _____no_output_____ | MIT | model_tflite/TFLite_FashionMnist.ipynb | alessiot/Flask-Tutorial-TFLite |
Prepare the Test Images for Download (Optional) | !mkdir -p test_images
tf.argmax(label, 1).numpy()[0]
def format_example(image, label):
return image, tf.one_hot(label, num_classes)
test_batches = test_examples.batch(1).map(format_example)
from PIL import Image
for index, (image, label) in enumerate(test_batches.take(50)):
#print(image)
#image = tf.... | _____no_output_____ | MIT | model_tflite/TFLite_FashionMnist.ipynb | alessiot/Flask-Tutorial-TFLite |
If you are running this notebook in a Colab, you can run the cell below to download the Zip file with the images to your local disk. **Note**: If the Zip file does not download when you run the cell, try running the cell a second time. | try:
files.download('fmnist_test_images.zip')
except:
pass | _____no_output_____ | MIT | model_tflite/TFLite_FashionMnist.ipynb | alessiot/Flask-Tutorial-TFLite |
Clean and Analyze Employee Exit SurveysIn this project, we'll clean and analyze exit surveys from employees of the Department of Education, Training and Employment (DETE)}) and the Technical and Further Education (TAFE) body of the Queensland government in Australia. The TAFE exit survey can be found here and the surv... | #Read in the data
import pandas as pd
import numpy as np
dete_survey = pd.read_csv('dete_survey.csv')
#Quick exploration of the data
pd.options.display.max_columns = 150 # to avoid truncated output
dete_survey.head()
dete_survey.info()
#Read in the data
tafe_survey = pd.read_csv("tafe_survey.csv")
#Quick exploration ... | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 702 entries, 0 to 701
Data columns (total 72 columns):
Record ID 702 non-null float64
Institute ... | MIT | Data Analysis/Clean and Analyze Employee Exit Surveys/Clean and Analyze Employee Exit Surveys.ipynb | linnforsman/data-science-portfolio |
We can make the following observations based on the work above:* The dete_survey dataframe contains 'Not Stated' values that indicate values are missing, but they aren't represented as NaN.* Both the dete_survey and tafe_survey contain many columns that we don't need to complete our analysis.* Each dataframe contains m... | # Read in the data again, but this time read 'Not Stated' values as 'NaN'
dete_survey = pd.read_csv('dete_survey.csv', na_values='Not Stated')
#Quick exploration of the data
dete_survey.head()
# Remove columns we don't need for our analysis
dete_survey_updated = dete_survey.drop(dete_survey.columns[28:49], axis=1)
taf... | Index(['ID', 'SeparationType', 'Cease Date', 'DETE Start Date',
'Role Start Date', 'Position', 'Classification', 'Region',
'Business Unit', 'Employment Status', 'Career move to public sector',
'Career move to private sector', 'Interpersonal conflicts',
'Job dissatisfaction', 'Dissatisfaction... | MIT | Data Analysis/Clean and Analyze Employee Exit Surveys/Clean and Analyze Employee Exit Surveys.ipynb | linnforsman/data-science-portfolio |
Rename ColumnsNext, we'll standardize the names of the columns we want to work with, because we eventually want to combine the dataframes. | # Clean the column names
dete_survey_updated.columns = dete_survey_updated.columns.str.lower().str.strip().str.replace(' ', '_')
# Check that the column names were updated correctly
dete_survey_updated.columns
# Update column names to match the names in dete_survey_updated
mapping = {'Record ID': 'id', 'CESSATION YEAR... | _____no_output_____ | MIT | Data Analysis/Clean and Analyze Employee Exit Surveys/Clean and Analyze Employee Exit Surveys.ipynb | linnforsman/data-science-portfolio |
Filter the DataFor this project, we'll only analyze survey respondents who resigned, so we'll only select separation types containing the string 'Resignation'. | # Check the unique values for the separationtype column
tafe_survey_updated['separationtype'].value_counts()
# Check the unique values for the separationtype column
dete_survey_updated['separationtype'].value_counts()
# Check the unique values for the separationtype column
dete_survey_updated['separationtype'].value_co... | _____no_output_____ | MIT | Data Analysis/Clean and Analyze Employee Exit Surveys/Clean and Analyze Employee Exit Surveys.ipynb | linnforsman/data-science-portfolio |
Verify the DataBelow, we clean and explore the cease_date and dete_start_date columns to make sure all of the years make sense. We'll use the following criteria:* Since the cease_date is the last year of the person's employment and the dete_start_date is the person's first year of employment, it wouldn't make sense to... | # Check the unique values
dete_resignations['cease_date'].value_counts()
# Extract the years and convert them to a float type
dete_resignations['cease_date'] = dete_resignations['cease_date'].str.split('/').str[-1]
dete_resignations['cease_date'] = dete_resignations['cease_date'].astype("float")
# Check the values aga... | _____no_output_____ | MIT | Data Analysis/Clean and Analyze Employee Exit Surveys/Clean and Analyze Employee Exit Surveys.ipynb | linnforsman/data-science-portfolio |
Below are our findings:* The years in both dataframes don't completely align. The tafe_survey_updated dataframe contains some cease dates in 2009, but the dete_survey_updated dataframe does not. The tafe_survey_updated dataframe also contains many more cease dates in 2010 than the dete_survey_updaed dataframe. Since we... | # Calculate the length of time an employee spent in their respective workplace and create a new column
dete_resignations['institute_service'] = dete_resignations['cease_date'] - dete_resignations['dete_start_date']
# Quick check of the result
dete_resignations['institute_service'].head() | _____no_output_____ | MIT | Data Analysis/Clean and Analyze Employee Exit Surveys/Clean and Analyze Employee Exit Surveys.ipynb | linnforsman/data-science-portfolio |
Identify Dissatisfied Employees¶Next, we'll identify any employees who resigned because they were dissatisfied. Below are the columns we'll use to categorize employees as "dissatisfied" from each dataframe:1. tafe_survey_updated:* Contributing Factors. Dissatisfaction* Contributing Factors. Job Dissatisfaction2. dafe_... | # Check the unique values
tafe_resignations['Contributing Factors. Dissatisfaction'].value_counts()
# Check the unique values
tafe_resignations['Contributing Factors. Job Dissatisfaction'].value_counts()
# Update the values in the contributing factors columns to be either True, False, or NaN
def update_vals(x):
if ... | _____no_output_____ | MIT | Data Analysis/Clean and Analyze Employee Exit Surveys/Clean and Analyze Employee Exit Surveys.ipynb | linnforsman/data-science-portfolio |
Combining the Data¶Below, we'll add an institute column so that we can differentiate the data from each survey after we combine them. Then, we'll combine the dataframes and drop any remaining columns we don't need. | # Add an institute column
dete_resignations_up['institute'] = 'DETE'
tafe_resignations_up['institute'] = 'TAFE'
# Combine the dataframes
combined = pd.concat([dete_resignations_up, tafe_resignations_up], ignore_index=True)
# Verify the number of non null values in each column
combined.notnull().sum().sort_values()
# D... | _____no_output_____ | MIT | Data Analysis/Clean and Analyze Employee Exit Surveys/Clean and Analyze Employee Exit Surveys.ipynb | linnforsman/data-science-portfolio |
Clean the Service Column¶Next, we'll clean the institute_service column and categorize employees according to the following definitions:* New: Less than 3 years in the workplace* Experienced: 3-6 years in the workplace* Established: 7-10 years in the workplace* Veteran: 11 or more years in the workplaceOur analysis is... | # Check the unique values
combined_updated['institute_service'].value_counts(dropna=False)
# Extract the years of service and convert the type to float
combined_updated['institute_service_up'] = combined_updated['institute_service'].astype('str').str.extract(r'(\d+)')
combined_updated['institute_service_up'] = combined... | _____no_output_____ | MIT | Data Analysis/Clean and Analyze Employee Exit Surveys/Clean and Analyze Employee Exit Surveys.ipynb | linnforsman/data-science-portfolio |
Perform Some Initial Analysis¶Finally, we'll replace the missing values in the dissatisfied column with the most frequent value, False. Then, we'll calculate the percentage of employees who resigned due to dissatisfaction in each service_cat group and plot the results.Note that since we still have additional missing v... | # Verify the unique values
combined_updated['dissatisfied'].value_counts(dropna=False)
# Replace missing values with the most frequent value, False
combined_updated['dissatisfied'] = combined_updated['dissatisfied'].fillna(False)
# Calculate the percentage of employees who resigned due to dissatisfaction in each catego... | _____no_output_____ | MIT | Data Analysis/Clean and Analyze Employee Exit Surveys/Clean and Analyze Employee Exit Surveys.ipynb | linnforsman/data-science-portfolio |
Lec 11. Simple CNN : 한글 자모 | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.init as init
import torch.utils.data as Data
import torchvision.utils as utils
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import numpy as np
import os
from PIL import Image
import matplotlib.pyplot as ... | _____no_output_____ | MIT | F_Camp/c11_Simple_CNN_hangul.ipynb | woosa7/pytorch |
Load Custom Data * transforms에 대해서는 다음 참조https://pytorch.org/docs/stable/torchvision/transforms.html | img_dir = "data/hangul/"
img_data = dsets.ImageFolder(img_dir,
transforms.Compose([
transforms.Grayscale(),
# # Data Augmentation
# transforms.RandomRotation... | _____no_output_____ | MIT | F_Camp/c11_Simple_CNN_hangul.ipynb | woosa7/pytorch |
Define Model | def c_conv(N, K, P=0, S=1):
return int((N + 2*P - K) / S + 1)
def c_pool(N, K):
return int(N/K)
c0 = 36
c1 = c_conv(c0, 3)
c2 = c_conv(c1, 3)
c3 = c_pool(c2, 2)
c4 = c_conv(c3, 3)
c5 = c_conv(c4, 3)
c6 = c_pool(c5, 2)
print(c1, c2, c3, c4, c5, c6)
class CNN(nn.Module):
def __init__(self):
super(C... | _____no_output_____ | MIT | F_Camp/c11_Simple_CNN_hangul.ipynb | woosa7/pytorch |
Test Model | model.eval()
correct = 0
total = 0
for images, labels in test_loader:
images = images.cuda()
outputs = model(images)
# print(outputs.data) # 39 class에 대한 확률
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels.cuda()).sum()
... | correct : 22398
total : 22400
Accuracy of test images: 99.991071
| MIT | F_Camp/c11_Simple_CNN_hangul.ipynb | woosa7/pytorch |
Face and Facial Keypoint detectionAfter you've trained a neural network to detect facial keypoints, you can then apply this network to *any* image that includes faces. The neural network expects a Tensor of a certain size as input and, so, to detect any face, you'll first have to do some pre-processing.1. Detect all t... | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
%matplotlib inline | _____no_output_____ | MIT | Computer_Vision_Nanodegree_Program/01_Facial_Keypoint_Detection/3. Facial Keypoint Detection, Complete Pipeline.ipynb | cilsya/udacity |
Select an image Select an image to perform facial keypoint detection on; you can select any image of faces in the `images/` directory. | import cv2
# load in color image for face detection
image = cv2.imread('images/obamas.jpg')
# switch red and blue color channels
# --> by default OpenCV assumes BLUE comes first, not RED as in many images
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# plot the image
fig = plt.figure(figsize=(9,9))
plt.imshow(image... | _____no_output_____ | MIT | Computer_Vision_Nanodegree_Program/01_Facial_Keypoint_Detection/3. Facial Keypoint Detection, Complete Pipeline.ipynb | cilsya/udacity |
Detect all faces in an imageNext, you'll use one of OpenCV's pre-trained Haar Cascade classifiers, all of which can be found in the `detector_architectures/` directory, to find any faces in your selected image.In the code below, we loop over each face in the original image and draw a red square on each face (in a copy... | # load in a haar cascade classifier for detecting frontal faces
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
# run the detector
# the output here is an array of detections; the corners of each detection box
# if necessary, modify these parameters until you successf... | _____no_output_____ | MIT | Computer_Vision_Nanodegree_Program/01_Facial_Keypoint_Detection/3. Facial Keypoint Detection, Complete Pipeline.ipynb | cilsya/udacity |
Loading in a trained modelOnce you have an image to work with (and, again, you can select any image of faces in the `images/` directory), the next step is to pre-process that image and feed it into your CNN facial keypoint detector.First, load your best model by its filename. | import torch
from models import Net
net = Net()
## TODO: load the best saved model parameters (by your path name)
## You'll need to un-comment the line below and add the correct name for *your* saved model
# net.load_state_dict(torch.load('saved_models/keypoints_model_1.pt'))
## print out your net and prepare it for... | _____no_output_____ | MIT | Computer_Vision_Nanodegree_Program/01_Facial_Keypoint_Detection/3. Facial Keypoint Detection, Complete Pipeline.ipynb | cilsya/udacity |
Keypoint detectionNow, we'll loop over each detected face in an image (again!) only this time, you'll transform those faces in Tensors that your CNN can accept as input images. TODO: Transform each detected face into an input TensorYou'll need to perform the following steps for each detected face:1. Convert the face f... | image_copy = np.copy(image)
# loop over the detected faces from your haar cascade
for (x,y,w,h) in faces:
# Select the region of interest that is the face in the image
roi = image_copy[y:y+h, x:x+w]
## TODO: Convert the face region from RGB to grayscale
## TODO: Normalize the grayscale imag... | _____no_output_____ | MIT | Computer_Vision_Nanodegree_Program/01_Facial_Keypoint_Detection/3. Facial Keypoint Detection, Complete Pipeline.ipynb | cilsya/udacity |
df = pd.read_csv('Downloads/mnist_train.csv',header = None)data = np.array(df)X = (data[:,1:].transpose())/255m = X.shape[1]n = X.shape[0]Y_orig = data[:,0:1].transpose()Y = np.zeros((10,m))for i in range(m): Y[int(Y_orig[0,i]),i] = 1 | def relu(Z):
result = (Z + np.abs(Z))/2
return result
def relu_backward(Z):
result = (Z + np.abs(Z))/(2*np.abs(Z))
return result
def softmax(Z):
temp = np.exp(Z)
result = temp/np.sum(temp,axis = 0,keepdims = True)
return result
def initialize_parameters(layer_dims):
parameters = {}
L... | Its a 5
| MIT | Tests/From Scratch/L layer mnist.ipynb | Sushant-ctrl/MNIST_digitClassifier |
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 | community/en/pdes.ipynb | thezwick/examples |
Partial Differential Equations Run in Google Colab View source on GitHub TensorFlow isn't just for machine learning. Here you will use TensorFlow to simulate the behavior of a [partial differential equation](https://en.wikipedia.org/wiki/Partial_differential_equation). You'll simulate the surface of squ... | #Import libraries for simulation
import tensorflow as tf
assert tf.__version__.startswith('2')
import numpy as np
#Imports for visualization
import PIL.Image
from io import BytesIO
from IPython.display import clear_output, Image, display
| _____no_output_____ | Apache-2.0 | community/en/pdes.ipynb | thezwick/examples |
A function for displaying the state of the pond's surface as an image. | def DisplayArray(a, fmt='jpeg', rng=[0,1]):
"""Display an array as a picture."""
a = (a - rng[0])/float(rng[1] - rng[0])*255
a = np.uint8(np.clip(a, 0, 255))
f = BytesIO()
PIL.Image.fromarray(a).save(f, fmt)
clear_output(wait = True)
display(Image(data=f.getvalue())) | _____no_output_____ | Apache-2.0 | community/en/pdes.ipynb | thezwick/examples |
Computational convenience functions | @tf.function
def make_kernel(a):
"""Transform a 2D array into a convolution kernel"""
a = np.asarray(a)
a = a.reshape(list(a.shape) + [1,1])
return tf.constant(a, dtype=1)
@tf.function
def simple_conv(x, k):
"""A simplified 2D convolution operation"""
x = tf.expand_dims(tf.expand_dims(x, 0), -1)
y = tf.n... | _____no_output_____ | Apache-2.0 | community/en/pdes.ipynb | thezwick/examples |
Define the PDEYour pond is a perfect 500 x 500 square, as is the case for most ponds found in nature. | N = 500 | _____no_output_____ | Apache-2.0 | community/en/pdes.ipynb | thezwick/examples |
Here you create your pond and hit it with some rain drops. | # Initial Conditions -- some rain drops hit a pond
# Set everything to zero
u_init = np.zeros([N, N], dtype=np.float32)
ut_init = np.zeros([N, N], dtype=np.float32)
# Some rain drops hit a pond at random points
for n in range(40):
a,b = np.random.randint(0, N, 2)
u_init[a,b] = np.random.uniform()
DisplayArray(u_... | _____no_output_____ | Apache-2.0 | community/en/pdes.ipynb | thezwick/examples |
Now let's specify the details of the differential equation. | # Parameters:
# eps -- time resolution
# damping -- wave damping
eps = 0.03
damping = 0.04
# Create variables for simulation state
U = tf.Variable(u_init)
Ut = tf.Variable(ut_init) | _____no_output_____ | Apache-2.0 | community/en/pdes.ipynb | thezwick/examples |
Run the simulationThis is where it gets fun -- running time forward with a simple for loop. | # Run 1000 steps of PDE
for i in range(1000):
# Step simulation
# Discretized PDE update rules
U = U + eps * Ut
Ut = Ut + eps * (laplace(U) - damping * Ut)
# Show final image
DisplayArray(U.numpy(), rng=[-0.1, 0.1]) | _____no_output_____ | Apache-2.0 | community/en/pdes.ipynb | thezwick/examples |
NumPyNumpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays. Official NumPy Documentation: https://numpy.org/doc/stable/reference/ | # Install NumPy
# ! pip install numpy | _____no_output_____ | Apache-2.0 | Week 3/numpy.ipynb | mubtasimfuad/ML_AiS_B1 |
Since NumPy is not a default thing in Python. We import this library. When we import a library we allow all the functions and types with the initial of that library. | # Import NumPy
import numpy as np | _____no_output_____ | Apache-2.0 | Week 3/numpy.ipynb | mubtasimfuad/ML_AiS_B1 |
NumPy ArraysA grid of values, all of the same type. **Rank:** number of dimensions of the array **Shape:** an array of tuple of integers giving the size of the array along each dimension. | # Rank 1 array
a = np.array([1, 2, 3])
print(type(a)) # Prints data type
print(a.shape)
print(a[0], a[1], a[2]) # Indexing
a[0] = 5 # Assigning
print(a)
# Rank 2 array
b = np.array([ [1,2,3],
[4,5,6]
])
'''
# of elements in first 3rd bracket... | (2, 3)
1 2 4 6
| Apache-2.0 | Week 3/numpy.ipynb | mubtasimfuad/ML_AiS_B1 |
Special Arrays | a = np.zeros((6,4)) # Create an array of all zeros
a
np.zeros_like(b,dtype=float)
b = np.ones((3,2)) # Create an array of all ones
b
c = np.full((6,4), 7) # Create a constant array
c
d = np.eye(5) # Create a 2x2 identity matrix
d
e = np.random.random((4,3))... | _____no_output_____ | Apache-2.0 | Week 3/numpy.ipynb | mubtasimfuad/ML_AiS_B1 |
Indexing | a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
a
a[:2,:3]
b = a[:2, 1:3]
b
print(a[0, 1]) # Prints "2"
b[0, 0] = 77 # b[0, 0] is the same piece of data as a[0, 1]
print(a[0, 1]) # Prints "77"
a[1, :]
a[1:2, :]
a[:, 1]
a[:, 1:2]
np.arange(2,10,2) | _____no_output_____ | Apache-2.0 | Week 3/numpy.ipynb | mubtasimfuad/ML_AiS_B1 |
Boolean array indexing | a
bool_idx = (a>10)
bool_idx
a[bool_idx]
a [ a>10 ] | _____no_output_____ | Apache-2.0 | Week 3/numpy.ipynb | mubtasimfuad/ML_AiS_B1 |
Data Types | x = np.array([1, 2])
print(x.dtype)
x = np.array([1.0, 2.0])
print(x.dtype)
x = np.array([1, 2], dtype=np.float64) # Foring a particular datatype
print(x,x.dtype)
x.dtype | _____no_output_____ | Apache-2.0 | Week 3/numpy.ipynb | mubtasimfuad/ML_AiS_B1 |
Operations | x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)
x,y
# Adding two arrays element-wise
print(x + y)
print(np.add(x, y))
# Substracting two arrays element-wise
print(x - y)
print(np.subtract(x, y))
# Mutiplication Element-wise
print(x * y)
print(np.multiply(x, y))
# Elementwise... | _____no_output_____ | Apache-2.0 | Week 3/numpy.ipynb | mubtasimfuad/ML_AiS_B1 |
Broadcasting | x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = x + v # Add v to each row of x using broadcasting
print(y)
x = np.array([[1,2,3], [4,5,6]])
y = np.array([4,5])
(x.T+y).T
x, x.shape
x.T, x.T.shape
y, y.shape
x.T+y
(x.T+y).T
x*2
x+2 | _____no_output_____ | Apache-2.0 | Week 3/numpy.ipynb | mubtasimfuad/ML_AiS_B1 |
Backtest Orbit ModelIn this section, we will cover:- How to create a TimeSeriesSplitter- How to create a BackTester and retrieve the backtesting results- How to leverage the backtesting to tune the hyper-paramters for orbit models | %matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import orbit
from orbit.models import LGT, DLT
from orbit.diagnostics.backtest import BackTester, TimeSeriesSplitter
from orbit.diagnostics.plot import plot_bt_predictions
from orbit.diagnostics.metrics import smape, wmape
from ... | _____no_output_____ | Apache-2.0 | docs/tutorials/backtest.ipynb | goncaloperes/orbit |
The way to gauge the performance of a time-series model is through re-training models with different historic periods and check their forecast within certain steps. This is similar to a time-based style cross-validation. More often, we called it `backtest` in time-series modeling.The purpose of this notebook is to illu... | # configs
min_train_len = 380 # minimal length of window length
forecast_len = 20 # length forecast window
incremental_len = 20 # step length for moving forward
ex_splitter = TimeSeriesSplitter(df=data,
min_train_len=min_train_len,
incremental_len=increm... |
------------ Fold: (1 / 3)------------
Train start index: 0 Train end index: 379
Test start index: 380 Test end index: 399
Train start date: 2010-01-03 00:00:00 Train end date: 2017-04-09 00:00:00
Test start date: 2017-04-16 00:00:00 Test end date: 2017-08-27 00:00:00
------------ Fold: (2 / 3)------------
Train star... | Apache-2.0 | docs/tutorials/backtest.ipynb | goncaloperes/orbit |
We can visualize the splits, green is training window and yellow it the forecasting windown. The starting point is always 0 for three splits but window length increases from 380 to 420. | _ = ex_splitter.plot() | _____no_output_____ | Apache-2.0 | docs/tutorials/backtest.ipynb | goncaloperes/orbit |
Rolling window | # configs
min_train_len = 380 # in case of rolling window, this specify the length of window length
forecast_len = 20 # length forecast window
incremental_len = 20 # step length for moving forward
roll_splitter = TimeSeriesSplitter(data,
min_train_len=min_train_len,
... | _____no_output_____ | Apache-2.0 | docs/tutorials/backtest.ipynb | goncaloperes/orbit |
We can visualize the splits, green is training window and yellow it the forecasting windown. The window length is always 380, while the starting point moves forward 20 weeks each steps. | _ = roll_splitter.plot() | _____no_output_____ | Apache-2.0 | docs/tutorials/backtest.ipynb | goncaloperes/orbit |
Specifying number of splits User can also define number of splits using `n_splits` instead of specifying minimum training length. That way, minimum training length will be automatically calculated. | ex_splitter2 = TimeSeriesSplitter(data,
min_train_len=min_train_len,
incremental_len=incremental_len,
forecast_len=forecast_len,
n_splits=5,
wind... | _____no_output_____ | Apache-2.0 | docs/tutorials/backtest.ipynb | goncaloperes/orbit |
TimeSeriesSplitter as generator `TimeSeriesSplitter` is implemented as a genetor, therefore we can call `split()` to loop through it. It comes handy even for tasks other than backtest. | for train_df, test_df, scheme, key in roll_splitter.split():
print('Initial Claim slice {} rolling mean:{:.3f}'.format(key, train_df['claims'].mean())) | Initial Claim slice 0 rolling mean:12.712
Initial Claim slice 1 rolling mean:12.671
Initial Claim slice 2 rolling mean:12.647
| Apache-2.0 | docs/tutorials/backtest.ipynb | goncaloperes/orbit |
Create a BackTester Now, we are ready to do backtest, first let's initialize a `DLT` model and a `BackTester`. You pass in `TimeSeriesSplitter` parameters to `BackTester`. | # instantiate a model
dlt = DLT(
date_col='week',
response_col='claims',
regressor_col=['trend.unemploy', 'trend.filling', 'trend.job'],
seasonality=52,
estimator='stan-map',
)
# configs
min_train_len = 100
forecast_len = 20
incremental_len = 100
window_type = 'expanding'
bt = BackTester(
mo... | _____no_output_____ | Apache-2.0 | docs/tutorials/backtest.ipynb | goncaloperes/orbit |
Backtest fit and predictThe most expensive portion of backtesting is fitting the model iteratively. Thus, we separate the api calls for `fit_predict` and `score` to avoid redundant computation for multiple metrics or scoring methods | bt.fit_predict() | INFO:pystan:COMPILING THE C++ CODE FOR MODEL anon_model_b0a449c7523386cce384e92a998e71c8 NOW.
| Apache-2.0 | docs/tutorials/backtest.ipynb | goncaloperes/orbit |
Once `fit_predict()` is called, the fitted models and predictions can be easily retrieved from `BackTester`. Here the data is grouped by the date, split_key, and whether or not that observation is part of the training or test data | predicted_df = bt.get_predicted_df()
predicted_df.head() | _____no_output_____ | Apache-2.0 | docs/tutorials/backtest.ipynb | goncaloperes/orbit |
We also provide a plotting utility to visualize the predictions against the actuals for each split. | plot_bt_predictions(predicted_df, metrics=smape, ncol=2, include_vline=True); | _____no_output_____ | Apache-2.0 | docs/tutorials/backtest.ipynb | goncaloperes/orbit |
Users might find this useful for any custom computations that may need to be performed on the set of predicted data. Note that the columns are renamed to generic and consistent names. Sometimes, it might be useful to match the data back to the original dataset for ad-hoc diagnostics. This can easily be done by merging ... | predicted_df.merge(data, left_on='date', right_on='week') | _____no_output_____ | Apache-2.0 | docs/tutorials/backtest.ipynb | goncaloperes/orbit |
Backtest ScoringThe main purpose of `BackTester` are the evaluation metrics. Some of the most widely used metrics are implemented and built into the `BackTester` API.The default metric list is **smape, wmape, mape, mse, mae, rmsse**. | bt.score() | _____no_output_____ | Apache-2.0 | docs/tutorials/backtest.ipynb | goncaloperes/orbit |
It is possible to filter for only specific metrics of interest, or even implement your own callable and pass into the `score()` method. For example, see this function that uses last observed value as a predictor and computes the `mse`. Or `naive_error` which computes the error as the delta between predicted values and ... | def mse_naive(test_actual):
actual = test_actual[1:]
predicted = test_actual[:-1]
return np.mean(np.square(actual - predicted))
def naive_error(train_actual, test_predicted):
train_mean = np.mean(train_actual)
return np.mean(np.abs(test_predicted - train_mean))
bt.score(metrics=[mse_naive, naive_er... | _____no_output_____ | Apache-2.0 | docs/tutorials/backtest.ipynb | goncaloperes/orbit |
It doesn't take additional time to refit and predict the model, since the results are stored when `fit_predict()` is called. Check docstrings for function criteria that is required for it to be supported with this api. In some cases, we may want to evaluate our metrics on both train and test data. To do this you can ca... | bt.score(include_training_metrics=True) | _____no_output_____ | Apache-2.0 | docs/tutorials/backtest.ipynb | goncaloperes/orbit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.