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 |
|---|---|---|---|---|---|
Fancy HTML popup | import branca
m = folium.Map([43, -100], zoom_start=4)
html = """
<h1> This is a big popup</h1><br>
With a few lines of code...
<p>
<code>
from numpy import *<br>
exp(-2*pi)
</code>
</p>
"""
folium.Marker([30, -100], popup=html).add_to(m)
m | _____no_output_____ | MIT | examples/Popups.ipynb | uni-3/folium |
You can also put any HTML code inside of a Popup, thaks to the `IFrame` object. | m = folium.Map([43, -100], zoom_start=4)
html = """
<h1> This popup is an Iframe</h1><br>
With a few lines of code...
<p>
<code>
from numpy import *<br>
exp(-2*pi)
</code>
</p>
"""
iframe = branca.element.IFrame(html=html, width=500, height=300)
popup = folium.Popup(iframe,... | _____no_output_____ | MIT | examples/Popups.ipynb | uni-3/folium |
Note that you can put another `Figure` into an `IFrame` ; this should let you do stange things... | # Let's create a Figure, with a map inside.
f = branca.element.Figure()
folium.Map([-25, 150], zoom_start=3).add_to(f)
# Let's put the figure into an IFrame.
iframe = branca.element.IFrame(width=500, height=300)
f.add_to(iframe)
# Let's put the IFrame in a Popup
popup = folium.Popup(iframe, max_width=2650)
# Let's c... | _____no_output_____ | MIT | examples/Popups.ipynb | uni-3/folium |
Copyright 2018 The TensorFlow Probability Authors.Licensed under the Apache License, Version 2.0 (the "License"); | #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | _____no_output_____ | Apache-2.0 | site/en-snapshot/probability/examples/Eight_Schools.ipynb | NarimaneHennouni/docs-l10n |
Eight schools View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook The eight schools problem ([Rubin 1981](https://www.jstor.org/stable/1164617)) considers the effectiveness of SAT coaching programs conducted in parallel at eight schools. It has become a classi... | import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import tensorflow.compat.v2 as tf
import tensorflow_probability as tfp
from tensorflow_probability import distributions as tfd
import warnings
tf.enable_v2_behavior()
plt.style.use("ggplot")
warnings.filterwarnings('ignore') | _____no_output_____ | Apache-2.0 | site/en-snapshot/probability/examples/Eight_Schools.ipynb | NarimaneHennouni/docs-l10n |
The DataFrom Bayesian Data Analysis, section 5.5 (Gelman et al. 2013):> *A study was performed for the Educational Testing Service to analyze the effects of special coaching programs for SAT-V (Scholastic Aptitude Test-Verbal) in each of eight high schools. The outcome variable in each study was the score on a special... | num_schools = 8 # number of schools
treatment_effects = np.array(
[28, 8, -3, 7, -1, 1, 18, 12], dtype=np.float32) # treatment effects
treatment_stddevs = np.array(
[15, 10, 16, 11, 9, 11, 10, 18], dtype=np.float32) # treatment SE
fig, ax = plt.subplots()
plt.bar(range(num_schools), treatment_effects, yerr=... | _____no_output_____ | Apache-2.0 | site/en-snapshot/probability/examples/Eight_Schools.ipynb | NarimaneHennouni/docs-l10n |
ModelTo capture the data, we use a hierarchical normal model. It follows the generative process,$$\begin{align*}\mu &\sim \text{Normal}(\text{loc}{=}0,\ \text{scale}{=}10) \\\log\tau &\sim \text{Normal}(\text{loc}{=}5,\ \text{scale}{=}1) \\\text{for } & i=1\ldots 8:\\& \theta_i \sim \text{Normal}\left(\text{loc}{=}\mu... | model = tfd.JointDistributionSequential([
tfd.Normal(loc=0., scale=10., name="avg_effect"), # `mu` above
tfd.Normal(loc=5., scale=1., name="avg_stddev"), # `log(tau)` above
tfd.Independent(tfd.Normal(loc=tf.zeros(num_schools),
scale=tf.ones(num_schools),
... | _____no_output_____ | Apache-2.0 | site/en-snapshot/probability/examples/Eight_Schools.ipynb | NarimaneHennouni/docs-l10n |
Bayesian InferenceGiven data, we perform Hamiltonian Monte Carlo (HMC) to calculate the posterior distribution over the model's parameters. | num_results = 5000
num_burnin_steps = 3000
# Improve performance by tracing the sampler using `tf.function`
# and compiling it using XLA.
@tf.function(autograph=False, experimental_compile=True)
def do_sampling():
return tfp.mcmc.sample_chain(
num_results=num_results,
num_burnin_steps=num_burnin_steps,
... | _____no_output_____ | Apache-2.0 | site/en-snapshot/probability/examples/Eight_Schools.ipynb | NarimaneHennouni/docs-l10n |
We can observe the shrinkage toward the group `avg_effect` above. | print("Inferred posterior mean: {0:.2f}".format(
np.mean(school_effects_samples[:,])))
print("Inferred posterior mean se: {0:.2f}".format(
np.std(school_effects_samples[:,]))) | Inferred posterior mean: 6.97
Inferred posterior mean se: 10.41
| Apache-2.0 | site/en-snapshot/probability/examples/Eight_Schools.ipynb | NarimaneHennouni/docs-l10n |
CriticismTo get the posterior predictive distribution, i.e., a model of new data $y^*$ given the observed data $y$:$$ p(y^*|y) \propto \int_\theta p(y^* | \theta)p(\theta |y)d\theta$$we override the values of the random variables in the model to set them to the mean of the posterior distribution, and sample from that ... | sample_shape = [5000]
_, _, _, predictive_treatment_effects = model.sample(
value=(tf.broadcast_to(np.mean(avg_effect, 0), sample_shape),
tf.broadcast_to(np.mean(avg_stddev, 0), sample_shape),
tf.broadcast_to(np.mean(school_effects_standard, 0),
sample_shape + [num_... | _____no_output_____ | Apache-2.0 | site/en-snapshot/probability/examples/Eight_Schools.ipynb | NarimaneHennouni/docs-l10n |
We can look at the residuals between the treatment effects data and the predictions of the model posterior. These correspond with the plot above which shows the shrinkage of the estimated effects toward the population average. | treatment_effects - prediction | _____no_output_____ | Apache-2.0 | site/en-snapshot/probability/examples/Eight_Schools.ipynb | NarimaneHennouni/docs-l10n |
Because we have a distribution of predictions for each school, we can consider the distribution of residuals as well. | residuals = treatment_effects - predictive_treatment_effects
fig, axes = plt.subplots(4, 2, sharex=True, sharey=True)
fig.set_size_inches(12, 10)
fig.tight_layout()
for i, ax in enumerate(axes):
sns.kdeplot(residuals[:, 2*i].numpy(), ax=ax[0], shade=True)
ax[0].title.set_text(
"School {} treatment effect resi... | _____no_output_____ | Apache-2.0 | site/en-snapshot/probability/examples/Eight_Schools.ipynb | NarimaneHennouni/docs-l10n |
Create series in python | import pandas as pd
ice_cream = ['vanilla','chocolate','mousse','rocky road']
pd.Series(ice_cream)
lottery = [1,2,8,4,5,22,8,9]
pd.Series(lottery)
registration = [True, False, False, True, True, True]
pd.Series(registration)
merriam = {"Work":"Office","Play":"Stadium","Study":"Class"}
pd.Series(merriam)
## Intro to At... | _____no_output_____ | MIT | Series.ipynb | MKamyab1991/Pandas_class |
Task Structured Tabular Data: Dataset Link:Dataset can be found at " /data/structured_data/data.csv " in the respective challenge's repo. Description:Tabular data is usually given in csv format (comma-separated-value). CSV files can be read and manipulated using pandas and numpy library in python. Most common datatype... | # Import the required libraries
# Use terminal commands like "pip install numpy" to install packages
import numpy as np
import pandas as pd
# import sklearn if and when required | _____no_output_____ | MIT | task_1_tabular.ipynb | DeepConnectAI/challenge-week-1 |
Introduction to Python In this lesson we will learn the basics of the Python programming language (version 3). We won't learn everything about Python but enough to do some basic machine learning. Variables Variables are objects in Python that can hold anything with numbers or text. Let's look at how to create some v... | # Numerical example
x = 99
print (x)
x = 27 # Added numerical value of 27
print (x)
x=55 # Added numerical value of 55
print (x)
"""changed numerical values of x"""
# Text example
x = "learning to code is fun" # Changed text to "learning to code is fun" and "tomorrow"
print (x)
x="tomorrow"
print(x)
"""changed sen... | 300
56
| MIT | notebooks/Python-in-2-days/D1_L3_Python/__Python_Summary__.ipynb | slamb89/ml_training |
Variables can come in lots of different types. Even within numerical variables, you can have integers (int), floats (float), etc. All text based variables are of type string (str). We can see what type a variable is by printing its type. | # int variable
x = 2
print (x)
print (type(x))
x = 1
print (x)
print (type(x))
# float variable
x = 7.7
print (x)
print (type(x))
x = 2.25
print (x)
print (type(x))
# text variable
x = "hello Sheri"
print (x)
print (type(x))
x = "Thunderstorms"
print (x)
print (type(x))
# boolean variable
x = False
print (x)
pri... | 2
<class 'int'>
1
<class 'int'>
7.7
<class 'float'>
2.25
<class 'float'>
hello Sheri
<class 'str'>
Thunderstorms
<class 'str'>
False
<class 'bool'>
True
<class 'bool'>
| MIT | notebooks/Python-in-2-days/D1_L3_Python/__Python_Summary__.ipynb | slamb89/ml_training |
It's good practice to know what types your variables are. When you want to use numerical operations on them, they need to be compatible. | # int variables
a = 6
b = 2
print (a + b)
# string variables
a = "6"
b = "2"
print (a + b)
a = "4"
b = "3"
c = "5"
print (a + b + c)
a = 4
b = 3
c = 5
print (a + b + c)
"""Changed existing value of int and string variables. Created new variables""" | 8
62
435
12
| MIT | notebooks/Python-in-2-days/D1_L3_Python/__Python_Summary__.ipynb | slamb89/ml_training |
Lists Lists are objects in Python that can hold a ordered sequence of numbers **and** text. | # Creating a list
list_x = [2, "hello", 1]
print (list_x)
list_a = [1, "sheri lamb", 4]
print (list_a)
"""Created a new list a"""
# Adding to a list
list_x.append(7)
print (list_x)
list_a.append("tomorrow")
print (list_a)
"""Added 'tomorrow' to my list"""
# Accessing items at specific location in a list
print ("lis... | [2, 'hi', 1, 7, 7, 7, 2.4, 'world']
[1, 2, 'fire', 4, 7, 'Stella']
| MIT | notebooks/Python-in-2-days/D1_L3_Python/__Python_Summary__.ipynb | slamb89/ml_training |
Tuples Tuples are also objects in Python that can hold data but you cannot replace their values (for this reason, tuples are called immutable, whereas lists are known as mutable). | # Creating a tuple
tuple_x = (3.0, "hello")
print (tuple_x)
tuple_y = (5.0, "Star")
print (tuple_y)
"""Created tuple y"""
# Adding values to a tuple
tuple_x = tuple_x + (5.6,)
print (tuple_x)
tuple_z = tuple_y + (2.4,)
print (tuple_z)
"""added 2.4 to tuple_z"""
# Trying to change a tuples value (you can't, this sho... | _____no_output_____ | MIT | notebooks/Python-in-2-days/D1_L3_Python/__Python_Summary__.ipynb | slamb89/ml_training |
Dictionaries Dictionaries are Python objects that hold key-value pairs. In the example dictionary below, the keys are the "name" and "eye_color" variables. They each have a value associated with them. A dictionary cannot have two of the same keys. | # Creating a dictionary
dog = {"name": "dog",
"eye_color": "brown"}
print (dog)
print (dog["name"])
print (dog["eye_color"])
MAC = {"brand": "MAC", "color": "red"}
print (MAC)
print (MAC["brand"])
print (MAC["color"])
"""Created a dictionary for MAC lipstick"""
# Changing the value for a key
dog["eye_color"]... | 3
3
| MIT | notebooks/Python-in-2-days/D1_L3_Python/__Python_Summary__.ipynb | slamb89/ml_training |
If statements You can use `if` statements to conditionally do something. | # If statement
x = 4
if x < 1:
score = "low"
elif x <= 4:
score = "medium"
else:
score = "high"
print (score)
x = 5
if x < 2:
score = "low"
elif x <= 5:
score = "medium"
else:
score = "high"
print (score)
x = 10
print (score)
x = 1
print (score)
"""Added additional if statements (x = 5)"""
#... | it worked
it almost worked
| MIT | notebooks/Python-in-2-days/D1_L3_Python/__Python_Summary__.ipynb | slamb89/ml_training |
Loops In Python, you can use `for` loop to iterate over the elements of a sequence such as a list or tuple, or use `while` loop to do something repeatedly as long as a condition holds. | # For loop
x = 2 # x variable will start at 2 instead of 1
for i in range(5): # goes from i=0 to i=4 range is 5 instead of 3
x += 1 # same as x = x + 1
print ("i={0}, x={1}".format(i, x)) # printing with multiple variables(
# Loop through items in a list
x = 2 # changed x variable to 2, now x will start at... | 9
8
7
6
5
4
3
| MIT | notebooks/Python-in-2-days/D1_L3_Python/__Python_Summary__.ipynb | slamb89/ml_training |
Functions Functions are a way to modularize reusable pieces of code. | # Create a function
def Shamel(x): # Redefined function's name
x += 5 # Changed value of x
return x
# Use the function
score = 1
score = Shamel(x=score)
print (score)
# Function with multiple inputs
def join_name (first_name, middle_name, last_name): # Re-defined function
joined_name = first_name + " " + ... | Sheri Nicole Lamb
| MIT | notebooks/Python-in-2-days/D1_L3_Python/__Python_Summary__.ipynb | slamb89/ml_training |
Classes Classes are a fundamental piece of object oriented programming in Python. | # Creating the class
class Cars(object): # Changed class to Cars
# Initialize the class
def __init__(self, brand, color, name): # Changed "species" to "brand"
self.brand = brand
self.color = color
self.name = name
# For printing
def __str__(self):
return "{0} {1} na... | Spitfire Orange Jeep named Sunshine.
Sunshine
| MIT | notebooks/Python-in-2-days/D1_L3_Python/__Python_Summary__.ipynb | slamb89/ml_training |
CHAPTER 14 - Probabilistic Reasoning over Time George Tzanetakis, University of Victoria WORKPLAN The section number is based on the 4th edition of the AIMA textbook and is the suggestedreading for this week. Each list entry provides just the additional sections. For example the Expected reading include the section... | %matplotlib inline
import matplotlib.pyplot as plt
from scipy import stats
import numpy as np
from hmmlearn import hmm
class Random_Variable:
def __init__(self, name, values, probability_distribution):
self.name = name
self.values = values
self.probability_distribution = probabi... | _____no_output_____ | CC0-1.0 | csc421_tzanetakis_probabilistic_reasonining_time.ipynb | oscarsandford/csc421_tzanetakis |
Generating random weather samples with a IID model with no time dependenciesLet's first create some random samples of a symbolic random variable corresponding to the weather with two values Sunny (S) and cloudy (C) and generate random weather for 365 days. The assumption in this model is that the weather of each day i... | values = ['S', 'C']
probabilities = [0.9, 0.1]
weather = Random_Variable('weather', values, probabilities)
samples = weather.sample(365)
print(",".join(samples)) | S,C,S,S,S,C,S,C,S,S,C,C,S,C,C,C,S,C,C,S,C,C,C,S,S,S,C,S,S,S,S,S,S,C,C,S,S,S,C,C,S,S,S,S,S,S,C,C,C,S,S,S,C,C,S,C,C,S,C,S,C,S,C,S,S,S,C,S,S,S,C,C,C,C,S,C,C,C,C,C,C,C,C,C,S,S,C,C,C,S,S,S,S,C,C,C,C,S,S,S,C,S,C,S,S,C,S,S,S,C,S,C,C,S,C,S,C,C,C,S,C,C,C,S,C,C,S,C,C,S,C,S,C,C,S,S,S,C,S,S,C,S,C,S,C,C,S,S,S,S,S,C,S,S,C,S,C,C,C,C,... | CC0-1.0 | csc421_tzanetakis_probabilistic_reasonining_time.ipynb | oscarsandford/csc421_tzanetakis |
Now let lets visualize these samples using yellow for sunny and grey for cloudy | state2color = {}
state2color['S'] = 'yellow'
state2color['C'] = 'grey'
def plot_weather_samples(samples, state2color, title):
colors = [state2color[x] for x in samples]
x = np.arange(0, len(colors))
y = np.ones(len(colors))
plt.figure(figsize=(10,1))
plt.bar(x, y, color=colors, width=1)
plt.t... | _____no_output_____ | CC0-1.0 | csc421_tzanetakis_probabilistic_reasonining_time.ipynb | oscarsandford/csc421_tzanetakis |
Markov ChainNow instead of independently sampling the weather random variable lets form a markov chain. The Markov chain will start at a particular state and then will either stay in the same state or transition to a different state based on a transition probability matrix. To accomplish that we basically create a ran... | def markov_chain(transmat, state, state_names, samples):
(rows, cols) = transmat.shape
rvs = []
values = list(np.arange(0,rows))
# create random variables for each row of transition matrix
for r in range(rows):
rv = Random_Variable("row" + str(r), values, transmat[r])
rvs.a... | _____no_output_____ | CC0-1.0 | csc421_tzanetakis_probabilistic_reasonining_time.ipynb | oscarsandford/csc421_tzanetakis |
Generating samples using a Hidden Markov Model Lets now look at how a Hidden Markov Model would work by having a Markov Chain to generate a sequence of states and for each state having a different emission probability. When sunny we will output red or yellow with higher probabilities and when cloudy black or blue. Fir... | state2color = {}
state2color['S'] = 'yellow'
state2color['C'] = 'grey'
# generate random samples for a year
samples = weather.sample(365)
states = markov_chain(transmat1,0,['S','C'], 365)
plot_weather_samples(states, state2color, "markov chain 1")
# create two random variables one of the sunny state and one for the... | _____no_output_____ | CC0-1.0 | csc421_tzanetakis_probabilistic_reasonining_time.ipynb | oscarsandford/csc421_tzanetakis |
Multinomial HMM Lets do the same generation process using the multinomail HMM model supported by the *hmmlearn* python package. | transmat = np.array([[0.7, 0.3],
[0.2, 0.8]])
start_prob = np.array([1.0, 0.0])
# yellow and red have high probs for sunny
# blue and grey have high probs for cloudy
emission_probs = np.array([[0.6, 0.3, 0.1, 0.0],
[0.0, 0.1, 0.4, 0.5]])
model = hmm.MultinomialHMM(n... | _____no_output_____ | CC0-1.0 | csc421_tzanetakis_probabilistic_reasonining_time.ipynb | oscarsandford/csc421_tzanetakis |
Estimating the parameters of an HMMLet's sample the generative HMM and get a sequence of 1000 observations. Now we can learn in an unsupervised way the paraemters of a two component multinomial HMM just using these observations. Then we can compare the learned parameters with the original parameters of the model used ... | # generate the samples
X, Z = model.sample(10000)
# learn a new model
estimated_model = hmm.MultinomialHMM(n_components=2, n_iter=10000).fit(X)
| _____no_output_____ | CC0-1.0 | csc421_tzanetakis_probabilistic_reasonining_time.ipynb | oscarsandford/csc421_tzanetakis |
Let's compare the estimated model parameters with the original model. | print("Transition matrix")
print("Estimated model:")
print(estimated_model.transmat_)
print("Original model:")
print(model.transmat_)
print("Emission probabilities")
print("Estimated model")
print(estimated_model.emissionprob_)
print("Original model")
print(model.emissionprob_) | Transition matrix
Estimated model:
[[0.51221102 0.48778898]
[0.50955673 0.49044327]]
Original model:
[[0.7 0.3]
[0.2 0.8]]
Emission probabilities
Estimated model
[[0.18583389 0.21418596 0.33339236 0.26658778]
[0.29659401 0.12915002 0.22585028 0.34840569]]
Original model
[[0.6 0.3 0.1 0. ]
[0. 0.1 0.4 0.5]]
| CC0-1.0 | csc421_tzanetakis_probabilistic_reasonining_time.ipynb | oscarsandford/csc421_tzanetakis |
Predicting a sequence of states given a sequence of observationsWe can also use the trained HMM model to predict a sequence of hidden states given a sequence of observations. This is the task of maximum likelihood sequence estimation. For example in Speech Recognition it would correspond to estimating a sequence of ph... | Z2 = estimated_model.predict(X)
state2color = {}
state2color[0] = 'yellow'
state2color[1] = 'grey'
plot_weather_samples(Z, state2color, 'Original states')
plot_weather_samples(Z2, state2color, 'Predicted states')
# note the reversal of colors for the states as the order of components is not the same.
# we can easily... | _____no_output_____ | CC0-1.0 | csc421_tzanetakis_probabilistic_reasonining_time.ipynb | oscarsandford/csc421_tzanetakis |
The estimated model can be sampled just like the original model | X, Z = estimated_model.sample(365)
state2color = {}
state2color[0] = 'yellow'
state2color[1] = 'grey'
plot_weather_samples(Z, state2color, 'states generated by estimated model ')
samples = [item for sublist in X for item in sublist]
obs2color = {}
obs2color[0] = 'yellow'
obs2color[1] = 'red'
obs2color[2] = 'blue'
o... | _____no_output_____ | CC0-1.0 | csc421_tzanetakis_probabilistic_reasonining_time.ipynb | oscarsandford/csc421_tzanetakis |
Numerical Simulation Laboratory (NSL) Numerical exercises 10 Exercise 10.1By adapting your Genetic Algorithm code, developed during the Numerical Exercise 9, write a C++ code to solve the TSP with a **Simulated Annealing** (SA) algorithm. Apply your code to the optimization of a path among - 30 cities randomly pl... | import numpy as np
import matplotlib.pyplot as plt
from os import system
from matplotlib.pyplot import figure
from time import time
start = time() | _____no_output_____ | MIT | LSN_exercise_10/Ex_10.ipynb | LeonardoAlchieri/LSN_exercises |
CIRCUMFERENCE | form = 0
system('sh clean.sh')
system('./genetic.exe '+str(form))
results = np.loadtxt("results.txt", skiprows=1)
temps = results[:,0]
paths = results[:,1]
figure(figsize=(10,7), dpi=70)
plt.plot(temps, paths)
plt.axhline(2*np.pi, color='red', label='2π')
plt.xlabel("Temperature")
plt.ylabel("Path lengths")
plt.legend(... | _____no_output_____ | MIT | LSN_exercise_10/Ex_10.ipynb | LeonardoAlchieri/LSN_exercises |
SQUARE | form = 1
system('sh clean.sh')
system('./genetic.exe '+str(form))
results = np.loadtxt("results.txt", skiprows=1)
temps = results[:,0]
paths = results[:,1]
figure(figsize=(10,7), dpi=70)
plt.plot(temps, paths)
plt.xlabel("Temperature")
plt.ylabel("Path lengths")
plt.grid(True)
plt.show()
print('-- Best path reached:', ... | -- Time for computation: 6.15 sec
| MIT | LSN_exercise_10/Ex_10.ipynb | LeonardoAlchieri/LSN_exercises |
Exercise 10.2Parallelize with MPI libraries your Simulated Annealing code in order to solve the TSP by performing a *Random Search* with **parallel SA searches of the optimal path**:each node should perform an independent SA search and only in the end you will compare the results of each node.Apply your code to the *u... | best_conf = np.zeros((4, 31, 2))
results = np.zeros((4, 1000, 2))
for rank in range(0,4):
init = np.loadtxt("Parallel/best_conf"+str(rank)+".txt", skiprows=1)
init_2 = np.loadtxt("Parallel/results"+str(rank)+".txt", skiprows=1)
best_conf[rank, :, :] = init[:,:]
results[rank,:,:] = init_2[:,:]
for rank i... | _____no_output_____ | MIT | LSN_exercise_10/Ex_10.ipynb | LeonardoAlchieri/LSN_exercises |
OpEn Rust Examples: with General Gradient FunctionIn this example, we are going to use a function that can obtain the gradient of any given function. This sort of function was used in relaxed_ik rust version. Now, we are trying to use this approach for [the previous example that we implemented before](https://github.c... | extern crate optimization_engine;
use optimization_engine::{
alm::*,
constraints::*, panoc::*, *
};
extern crate nalgebra;
use nalgebra::base::{*};
// use nalgebra::base::{Matrix4, Matrix4x2, Matrix4x1};
// use std::cmp; | _____no_output_____ | MIT | tools_examples/OpEn/examples_rust/OpEn_Rust_examples_general_diff.ipynb | inmo-jang/optimisation |
Problem Master ClassYou should note that `AlmFactory` should have `f` and `df` being with `fn f(u: &[f64], cost: &mut f64) -> Result` and `fn df(u: &[f64], grad: &mut [f64]) -> Result`, respectively. It means that it could be nicer if we have a master class that can simply turn out `f` or `df` values. Such an architec... | pub struct ProblemMaster{
p_obs: Matrix2x1<f64>, // Obstacle Position
p: Vec<f64> // parameters (slice)
}
impl ProblemMaster{
pub fn init(_p: Vec<f64>, _p_obs: Matrix2x1<f64>) -> Self {
let p = _p;
let p_obs = _p_obs;
Self{p, p_obs}
}
// Cost function
pu... | _____no_output_____ | MIT | tools_examples/OpEn/examples_rust/OpEn_Rust_examples_general_diff.ipynb | inmo-jang/optimisation |
Main function | fn main(_p: &[f64], _centre: &[f64]) {
/// ===========================================
let mut p_obs = Matrix2x1::new(0.0, 0.0);
for i in 0.._centre.len(){
p_obs[(i,0)] = _centre[i];
}
let mut p: Vec<f64> = Vec::new();
for i in 0.._p.len(){
p.push(_p[i]);
}
... | _____no_output_____ | MIT | tools_examples/OpEn/examples_rust/OpEn_Rust_examples_general_diff.ipynb | inmo-jang/optimisation |
Result Case (1) : $\mathbf{p} = [0.5, 0.0, 0.0]$; and $\mathbf{c} = [0.0, 0.0]$ | main(&[0.5, 0.0, 0.0], &[0.0, 0.0]); |
Solver result : AlmOptimizerStatus {
exit_status: Converged,
num_outer_iterations: 88,
num_inner_iterations: 1178,
last_problem_norm_fpr: 0.0000006,
lagrange_multipliers: Some(
[
5.0298889,
3.9940012,
],
),
solve_time: 1.2774560ms,
penalty: 5737.... | MIT | tools_examples/OpEn/examples_rust/OpEn_Rust_examples_general_diff.ipynb | inmo-jang/optimisation |
Case (2) : $\mathbf{p} = [0.5, 0.0, 0.0]$; and $\mathbf{c} = [-0.25, 0.0]$ | main(&[0.5, 0.0, 0.0], &[-0.25, 0.0]); |
Solver result : AlmOptimizerStatus {
exit_status: Converged,
num_outer_iterations: 73,
num_inner_iterations: 249,
last_problem_norm_fpr: 0.0000009,
lagrange_multipliers: Some(
[
5.0161011,
5.5350137,
],
),
solve_time: 426.3990000µs,
penalty: 2897... | MIT | tools_examples/OpEn/examples_rust/OpEn_Rust_examples_general_diff.ipynb | inmo-jang/optimisation |
Case (3) : $\mathbf{p} = [0.5, -0.5, 0.0]$; and $\mathbf{c} = [0.0, 0.0]$ | main(&[0.5, -0.5, 0.0], &[0.0, 0.0]); |
Solver result : AlmOptimizerStatus {
exit_status: Converged,
num_outer_iterations: 60,
num_inner_iterations: 876,
last_problem_norm_fpr: 0.0000001,
lagrange_multipliers: Some(
[
5.0008478,
0.8368964,
],
),
solve_time: 951.4560000µs,
penalty: 1463... | MIT | tools_examples/OpEn/examples_rust/OpEn_Rust_examples_general_diff.ipynb | inmo-jang/optimisation |
Case (4) : $\mathbf{p} = [0.1, 0.0, 0.0]$; and $\mathbf{c} = [0.5, 0.0]$ | main(&[0.1, 0.0, 0.0], &[0.5, 0.0]); |
Solver result : AlmOptimizerStatus {
exit_status: Converged,
num_outer_iterations: 97,
num_inner_iterations: 334,
last_problem_norm_fpr: 0.0000001,
lagrange_multipliers: Some(
[
5.0000000,
0.9943379,
],
),
solve_time: 663.6030000µs,
penalty: 9345... | MIT | tools_examples/OpEn/examples_rust/OpEn_Rust_examples_general_diff.ipynb | inmo-jang/optimisation |
Case (5) : $\mathbf{p} = [-0.5, -0.5864, 0.0]$; and $\mathbf{c} = [-3.0, 2.0]$ | main(&[0.5, -0.5864, 0.0], &[-3.0, 2.0]); |
Solver result : AlmOptimizerStatus {
exit_status: Converged,
num_outer_iterations: 15,
num_inner_iterations: 18,
last_problem_norm_fpr: 0.0000003,
lagrange_multipliers: Some(
[
5.0000000,
0.9999921,
],
),
solve_time: 44.3680000µs,
penalty: 179.58... | MIT | tools_examples/OpEn/examples_rust/OpEn_Rust_examples_general_diff.ipynb | inmo-jang/optimisation |
$$\newcommand\bs[1]{\boldsymbol{1}}\newcommand\norm[1]{\left\lVert1\right\rVert}$$ IntroductionWe will see some major concepts of linear algebra in this chapter. It is also quite heavy so hang on! We will start with getting some ideas on eigenvectors and eigenvalues. We will develop on the idea that a matrix can be se... | A = np.array([[-1, 3], [2, -2]])
A
v = np.array([[2], [1]])
v | _____no_output_____ | MIT | Chapters/2.07 Eigendecomposition/2.7 Eigendecomposition.ipynb | anamulmb/Math-to-Hone-your-DS-Skill |
Let's plot this vector: | plotVectors([v.flatten()], cols=['#1190FF'])
plt.ylim(-1, 4)
plt.xlim(-1, 4) | _____no_output_____ | MIT | Chapters/2.07 Eigendecomposition/2.7 Eigendecomposition.ipynb | anamulmb/Math-to-Hone-your-DS-Skill |
Now, we will apply the matrix $\bs{A}$ to this vector and plot the old vector (light blue) and the new one (orange): | Av = A.dot(v)
print(Av)
plotVectors([v.flatten(), Av.flatten()], cols=['#1190FF', '#FF9A13'])
plt.ylim(-1, 4)
plt.xlim(-1, 4) | [[1]
[2]]
| MIT | Chapters/2.07 Eigendecomposition/2.7 Eigendecomposition.ipynb | anamulmb/Math-to-Hone-your-DS-Skill |
We can see that applying the matrix $\bs{A}$ has the effect of modifying the vector.Now that you can think of matrices as linear transformation recipes, let's see the case of a very special type of vector: the eigenvector. Eigenvectors and eigenvaluesWe have seen an example of a vector transformed by a matrix. Now ima... | A = np.array([[5, 1], [3, 3]])
A
v = np.array([[1], [1]])
v
Av = A.dot(v)
orange = '#FF9A13'
blue = '#1190FF'
plotVectors([Av.flatten(), v.flatten()], cols=[blue, orange])
plt.ylim(-1, 7)
plt.xlim(-1, 7) | _____no_output_____ | MIT | Chapters/2.07 Eigendecomposition/2.7 Eigendecomposition.ipynb | anamulmb/Math-to-Hone-your-DS-Skill |
We can see that their directions are the same! Another eigenvector of $\bs{A}$ is$$\bs{v}=\begin{bmatrix} 1\\\\ -3\end{bmatrix}$$because$$\begin{bmatrix} 5 & 1\\\\ 3 & 3\end{bmatrix}\begin{bmatrix} 1\\\\ -3\end{bmatrix} = \begin{bmatrix} 2\\\\ -6\end{bmatrix}$$and$$2 \times \begin{bmatrix} 1\... | v = np.array([[1], [-3]])
v
Av = A.dot(v)
plotVectors([Av.flatten(), v.flatten()], cols=[blue, orange])
plt.ylim(-7, 1)
plt.xlim(-1, 3) | _____no_output_____ | MIT | Chapters/2.07 Eigendecomposition/2.7 Eigendecomposition.ipynb | anamulmb/Math-to-Hone-your-DS-Skill |
This example shows that the eigenvectors $\bs{v}$ are vectors that change only in scale when we apply the matrix $\bs{A}$ to them. Here the scales were 6 for the first eigenvector and 2 to the second but $\lambda$ can take any real or even complex value. Find eigenvalues and eigenvectors in PythonNumpy provides a func... | A = np.array([[5, 1], [3, 3]])
A
np.linalg.eig(A) | _____no_output_____ | MIT | Chapters/2.07 Eigendecomposition/2.7 Eigendecomposition.ipynb | anamulmb/Math-to-Hone-your-DS-Skill |
We can see that the eigenvalues are the same than the ones we used before: 6 and 2 (first array).The eigenvectors correspond to the columns of the second array. This means that the eigenvector corresponding to $\lambda=6$ is:$$\begin{bmatrix} 0.70710678\\\\ 0.70710678\end{bmatrix}$$The eigenvector corresponding t... | v = np.array([[1], [-3]])
Av = A.dot(v)
v_np = [-0.31622777, 0.9486833]
plotVectors([Av.flatten(), v.flatten(), v_np], cols=[blue, orange, 'blue'])
plt.ylim(-7, 1)
plt.xlim(-1, 3) | _____no_output_____ | MIT | Chapters/2.07 Eigendecomposition/2.7 Eigendecomposition.ipynb | anamulmb/Math-to-Hone-your-DS-Skill |
We can see that the vector found with Numpy (in dark blue) is a scaled version of our preceding $\begin{bmatrix} 1\\\\ -3\end{bmatrix}$. Rescaled vectorsAs we saw it with numpy, if $\bs{v}$ is an eigenvector of $\bs{A}$, then any rescaled vector $s\bs{v}$ is also an eigenvector of $\bs{A}$. The eigenvalue of the... | V = np.array([[1, 1], [1, -3]])
V
V_inv = np.linalg.inv(V)
V_inv | _____no_output_____ | MIT | Chapters/2.07 Eigendecomposition/2.7 Eigendecomposition.ipynb | anamulmb/Math-to-Hone-your-DS-Skill |
So let's plug$$\bs{V}^{-1}=\begin{bmatrix} 0.75 & 0.25\\\\ 0.25 & -0.25\end{bmatrix}$$into our equation:$$\begin{align*}&\bs{V}\cdot diag(\bs{\lambda}) \cdot \bs{V}^{-1}\\\\&=\begin{bmatrix} 1 & 1\\\\ 1 & -3\end{bmatrix}\begin{bmatrix} 6 & 0\\\\ 0 & 2\end{bmatrix}\begin{bmatrix} 0.75 & 0.25\\\\ ... | lambdas = np.diag([6,2])
lambdas
V.dot(lambdas).dot(V_inv) | _____no_output_____ | MIT | Chapters/2.07 Eigendecomposition/2.7 Eigendecomposition.ipynb | anamulmb/Math-to-Hone-your-DS-Skill |
That confirms our previous calculation. Real symmetric matrixIn the case of real symmetric matrices (more details about symmetric matrices in [2.6](https://hadrienj.github.io/posts/Deep-Learning-Book-Series-2.6-Special-Kinds-of-Matrices-and-Vectors/)), the eigendecomposition can be expressed as$$\bs{A} = \bs{Q}\Lambd... | A = np.array([[6, 2], [2, 3]])
A
eigVals, eigVecs = np.linalg.eig(A)
eigVecs
eigVals = np.diag(eigVals)
eigVals
eigVecs.dot(eigVals).dot(eigVecs.T) | _____no_output_____ | MIT | Chapters/2.07 Eigendecomposition/2.7 Eigendecomposition.ipynb | anamulmb/Math-to-Hone-your-DS-Skill |
We can see that the result corresponds to our initial matrix. Quadratic form to matrix formEigendecomposition can be used to optimize quadratic functions. We will see that when $\bs{x}$ takes the values of an eigenvector, $f(\bs{x})$ takes the value of its corresponding eigenvalue. When $\bs{x}$ takes the values of... | t = np.linspace(0, 2*np.pi, 100)
x = np.cos(t)
y = np.sin(t)
plt.figure()
plt.plot(x, y)
plt.xlim(-1.5, 1.5)
plt.ylim(-1.5, 1.5)
plt.show() | _____no_output_____ | MIT | Chapters/2.07 Eigendecomposition/2.7 Eigendecomposition.ipynb | anamulmb/Math-to-Hone-your-DS-Skill |
Then, we will transform each of these points by applying a matrix $\bs{A}$. This is the goal of the function bellow that takes a matrix as input and will draw- the origin set of unit vectors- the transformed set of unit vectors- the eigenvectors- the eigenvectors scalled by their eigenvalues | def linearTransformation(transformMatrix):
orange = '#FF9A13'
blue = '#1190FF'
# Create original set of unit vectors
t = np.linspace(0, 2*np.pi, 100)
x = np.cos(t)
y = np.sin(t)
# Calculate eigenvectors and eigenvalues
eigVecs = np.linalg.eig(transformMatrix)[1]
eigVals = np.diag(np... | _____no_output_____ | MIT | Chapters/2.07 Eigendecomposition/2.7 Eigendecomposition.ipynb | anamulmb/Math-to-Hone-your-DS-Skill |
We can see the unit circle in dark blue, the non scaled eigenvectors in light blue, the transformed unit circle in green and the scaled eigenvectors in yellow.It is worth noting that the eigenvectors are orthogonal here because the matrix is symmetric. Let's try with a non-symmetric matrix: | A = np.array([[1,1], [-1, 4]])
linearTransformation(A) | _____no_output_____ | MIT | Chapters/2.07 Eigendecomposition/2.7 Eigendecomposition.ipynb | anamulmb/Math-to-Hone-your-DS-Skill |
Lab 01 : Linear module -- demo | import torch
import torch.nn as nn | _____no_output_____ | MIT | codes/labs_lecture03/lab01_linear_module/linear_module_demo.ipynb | xb-trainings/IPAM_2018 |
Make a _Linear Module_ that takes input of size 5 and return output of size 3 | mod = nn.Linear(5,3,bias=True)
print(mod) | Linear(in_features=5, out_features=3, bias=True)
torch.Size([3, 5])
torch.Size([3])
| MIT | codes/labs_lecture03/lab01_linear_module/linear_module_demo.ipynb | xb-trainings/IPAM_2018 |
Let's make a random tensor of size 5: | x=torch.rand(5)
print(x)
print(x.size()) | tensor([0.5148, 0.6442, 0.5563, 0.4040, 0.9193])
torch.Size([5])
| MIT | codes/labs_lecture03/lab01_linear_module/linear_module_demo.ipynb | xb-trainings/IPAM_2018 |
Feed it to the module: | y=mod(x)
print(y) | tensor([ 0.3300, -0.1137, 0.6271], grad_fn=<ThAddBackward>)
| MIT | codes/labs_lecture03/lab01_linear_module/linear_module_demo.ipynb | xb-trainings/IPAM_2018 |
The output y is computed according to the formula:$$\begin{bmatrix}y_1\\ y_2 \\y_3 \end{bmatrix} =\begin{bmatrix}w_{11} & w_{12} & w_{13}& w_{14}& w_{15} \\w_{21} & w_{22} & w_{23}& w_{24}& w_{25} \\w_{31} & w_{32} & w_{33}& w_{34}& w_{35} \\\end{bmatrix}\begin{bmatrix}x_1\\ x_2 \\x_3 \\ x_4 \\x_5\end{bmatrix}+\begin{... | print(mod.weight)
print(mod.weight.size())
print(mod.bias)
print(mod.bias.size()) | Parameter containing:
tensor([0.2860, 0.0411, 0.3160], requires_grad=True)
torch.Size([3])
| MIT | codes/labs_lecture03/lab01_linear_module/linear_module_demo.ipynb | xb-trainings/IPAM_2018 |
If we want we can change the internal parameters of the module: | mod.weight[0,0]=0
mod.weight[0,1]=1
mod.weight[0,2]=2
print(mod.weight) | Parameter containing:
tensor([[ 0.0000, 1.0000, 2.0000, 0.3214, -0.0462],
[-0.3800, 0.4037, 0.0042, 0.4156, -0.4236],
[ 0.2434, 0.2813, 0.1570, -0.4028, 0.0869]], grad_fn=<CopySlices>)
| MIT | codes/labs_lecture03/lab01_linear_module/linear_module_demo.ipynb | xb-trainings/IPAM_2018 |
We can also make a Linear module without bias: | mod2 = nn.Linear(5,3,bias=False)
print(mod2)
print(mod2.weight)
print(mod2.bias) | None
| MIT | codes/labs_lecture03/lab01_linear_module/linear_module_demo.ipynb | xb-trainings/IPAM_2018 |
Data Augmentation on CIFAR10In this exercise we will use data augmentation to increase the available training data and thus improve the network training performance. We will use the same network architecture as in the previous exercise. Preparation | # load tensorboard extension
%load_ext tensorboard
# import torch and other libraries
import os
import numpy as np
import sklearn.metrics as metrics
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.optim import Adam
!pip install cifar2png
# check if ... | _____no_output_____ | MIT | exercises/classification/5_data_augmentation.ipynb | constantinpape/dl-teaching-resources |
Data AugmentationThe goal of data augmentation is to increase the amount of training data by transforming the input images in a way that they still resemble realistic images. Popular transformations used in data augmentation include rotations, image flips, color jitter or additive noise.Here, we will start with two tr... | # define random augmentations
import skimage.color as color
def random_flip(image, target, probability=.5):
""" Randomly mirror the image across the vertical axis.
"""
if np.random.rand() < probability:
image = np.array([np.fliplr(im) for im in image])
return image, target
def random_color_jitt... | _____no_output_____ | MIT | exercises/classification/5_data_augmentation.ipynb | constantinpape/dl-teaching-resources |
Normalization layersIn addition to convolutional layers and pooling layers, another important part of neural networks are normalization layers.These layers keep their input normalized using a learned normalization. The first type of normalization introduced has been [BatchNorm](https://arxiv.org/abs/1502.03167), which... | import torch.nn.functional as F
class CNNBatchNorm(nn.Module):
def __init__(self, n_classes):
super().__init__()
self.n_classes = n_classes
# the convolutions
self.conv1 = nn.Conv2d(in_channels=3, out_channels=12, kernel_size=5)
self.conv2 = nn.Conv2d(in_channels=12, out_ch... | _____no_output_____ | MIT | exercises/classification/5_data_augmentation.ipynb | constantinpape/dl-teaching-resources |
KFServing Sample In this notebook, we provide two samples for demonstrating KFServing SDK and YAML versions. Setup1. Your ~/.kube/config should point to a cluster with [KFServing installed](https://github.com/kubeflow/kfserving/blob/master/docs/DEVELOPER_GUIDE.mddeploy-kfserving).2. Your cluster's Istio Ingress gatewa... | !pip install kfserving kubernetes --user
from kubernetes import client
from kfserving import KFServingClient
from kfserving import constants
from kfserving import utils
from kfserving import V1alpha2EndpointSpec
from kfserving import V1alpha2PredictorSpec
from kfserving import V1alpha2TensorflowSpec
from kfserving imp... | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
Define namespace where InferenceService needs to be deployed to. If not specified, below function defines namespace to the current one where SDK is running in the cluster, otherwise it will deploy to default namespace. | namespace = utils.get_default_target_namespace() | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
Label namespace so you can run inference tasks in it | !kubectl label namespace $namespace serving.kubeflow.org/inferenceservice=enabled | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
Define InferenceServiceFirstly define default endpoint spec, and then define the inferenceservice basic on the endpoint spec. | api_version = constants.KFSERVING_GROUP + '/' + constants.KFSERVING_VERSION
default_endpoint_spec = V1alpha2EndpointSpec(
predictor=V1alpha2PredictorSpec(
tensorflow=V1alpha2TensorflowSpec(
storage_uri='gs://kfserving-samples/models/ten... | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
Create InferenceServiceCall KFServingClient to create InferenceService. | KFServing = KFServingClient()
KFServing.create(isvc) | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
Check the InferenceService | KFServing.get('flower-sample', namespace=namespace, watch=True, timeout_seconds=120) | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
Invoke EndpointIf you want to invoke endpoint by yourself, you can copy and paste below code block and execute in your local environment. Remember you should have a `kfserving-flowers-input.json` file in the same directory when you execute. | %%bash
MODEL_NAME=flower-sample
INPUT_PATH=@./kfserving-flowers-input.json
INGRESS_GATEWAY=istio-ingressgateway
SERVICE_HOSTNAME=$(kubectl get inferenceservice ${MODEL_NAME} -n $namespace -o jsonpath='{.status.url}' | cut -d "/" -f 3)
curl -v -H "Host: ${SERVICE_HOSTNAME}" http://localhost:8080/v1/models/$MODEL_NAME:... | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
Expected Output```* Trying 34.83.190.188...* TCP_NODELAY set* Connected to 34.83.190.188 (34.83.190.188) port 80 (0)> POST /v1/models/flowers-sample:predict HTTP/1.1> Host: flowers-sample.default.svc.cluster.local> User-Agent: curl/7.60.0> Accept: */*> Content-Length: 16201> Content-Type: application/x-www-form-urlen... | canary_endpoint_spec = V1alpha2EndpointSpec(
predictor=V1alpha2PredictorSpec(
tensorflow=V1alpha2TensorflowSpec(
storage_uri='gs://kfserving-samples/models/tensorflow/flowers-2',
resources=V1ResourceRequirement... | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
Rollout more traffic to canary of the InferenceServiceRollout traffice percent to 50% to canary version. | KFServing.rollout_canary('flower-sample', percent=50, namespace=namespace,
watch=True, timeout_seconds=120) | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
Users send request to service 100 times. | %%bash
MODEL_NAME=flowers-sample
INPUT_PATH=@./kfserving-flowers-input.json
INGRESS_GATEWAY=istio-ingressgateway
SERVICE_HOSTNAME=$(kubectl get inferenceservice ${MODEL_NAME} -n $namespace -o jsonpath='{.status.url}' | cut -d "/" -f 3)
for i in {0..100};
do
curl -v -H "Host: ${SERVICE_HOSTNAME}" http://localhost:80... | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
check if traffic is split | %%bash
default_count=$(kubectl get replicaset -n $namespace -l serving.knative.dev/configuration=flowers-sample-predictor-default -o jsonpath='{.items[0].status.observedGeneration}')
canary_count=$(kubectl get replicaset -n $namespace -l serving.knative.dev/configuration=flowers-sample-predictor-canary -o jsonpath='{.... | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
Promote Canary to Default | KFServing.promote('flower-sample', namespace=namespace, watch=True, timeout_seconds=120) | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
Delete the InferenceService | KFServing.delete('flower-sample', namespace=namespace) | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
2. Sample for Kfserving YAMLNote: You should execute all the code blocks in your local environment. Create the InferenceServiceApply the CRD | !kubectl apply -n $namespace -f kfserving-flowers.yaml | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
Expected Output```$ inferenceservice.serving.kubeflow.org/flowers-sample configured``` Run a predictionUse `istio-ingressgateway` as your `INGRESS_GATEWAY` if you are deploying KFServing as part of Kubeflow install, and not independently. | %%bash
MODEL_NAME=flowers-sample
INPUT_PATH=@./kfserving-flowers-input.json
INGRESS_GATEWAY=istio-ingressgateway
SERVICE_HOSTNAME=$(kubectl get inferenceservice ${MODEL_NAME} -n $namespace -o jsonpath='{.status.url}' | cut -d "/" -f 3)
curl -v -H "Host: ${SERVICE_HOSTNAME}" http://localhost:8080/v1/models/$MODEL_NAME... | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
If you stop making requests to the application, you should eventually see that your application scales itself back down to zero. Watch the pod until you see that it is `Terminating`. This should take approximately 90 seconds. | !kubectl get pods --watch -n $namespace | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
Note: To exit the watch, use `ctrl + c`. Canary RolloutTo test a canary rollout, you can use the tensorflow-canary.yaml Apply the CRD | !kubectl apply -n $namespace -f kfserving-flowers-canary.yaml | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
To verify if your traffic split percenage is applied correctly, you can use the following command: | !kubectl get inferenceservices -n $namespace | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
The output should looks the similar as below:```NAME READY URL DEFAULT TRAFFIC CANARY TRAFFIC AGEflowers-sample True http://flowers-sample.default.example.com 90 10 48s``` | %%bash
MODEL_NAME=flowers-sample
INPUT_PATH=@./kfserving-flowers-input.json
INGRESS_GATEWAY=istio-ingressgateway
SERVICE_HOSTNAME=$(kubectl get inferenceservice ${MODEL_NAME} -n $namespace -o jsonpath='{.status.url}' | cut -d "/" -f 3)
for i in {0..100};
do
curl -v -H "Host: ${SERVICE_HOSTNAME}" http://localhost:80... | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
Verify if traffic split | %%bash
default_count=$(kubectl get replicaset -n $namespace -l serving.knative.dev/configuration=flowers-sample-predictor-default -o jsonpath='{.items[0].status.observedGeneration}')
canary_count=$(kubectl get replicaset -n $namespace -l serving.knative.dev/configuration=flowers-sample-predictor-canary -o jsonpath='{.... | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
Clean Up Resources | !kubectl delete inferenceservices flowers-sample -n $namespace | _____no_output_____ | Apache-2.0 | 10_pipeline/kubeflow/wip/07_01_KFServing.ipynb | MarcusFra/workshop |
"Folio 03: MLP Classifier"> "[ML 3/3] Use Neural Networks for Data Classification with Keras"- toc: true- branch: master- badges: true- image: images/ipynb/mlp_clf_main.png- comments: false- author: Giaco Stantino- categories: [portfolio project, machine learning]- hide: false- search_exclude: true- permalink: /blog/f... | #collapse-hide
import pandas as pd
import numpy as np
import tensorflow as tf
# # # set random seeds
import random
random.seed(42)
np.random.seed(42)
tf.random.set_seed(42)
# # #
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
#collapse-hide
def getDataRepo(data='demographics'):
"""
r... | statistics data has been read
segments data has been read
| Apache-2.0 | _notebooks/2022-03-28-mlp-classifier.ipynb | giastantino/repository |
Data transformationWe are going to use power transform as in clustering notebook. Let's check if anything is missing in imported data. | #collapse-hide
print(f"NaN values in the data:\n-----------------\n{client_df.isna().sum()}")
#hide
print(client_df.info()) | <class 'pandas.core.frame.DataFrame'>
Int64Index: 8223 entries, 0 to 8222
Data columns (total 13 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 client_id 8223 non-null int64
1 attr... | Apache-2.0 | _notebooks/2022-03-28-mlp-classifier.ipynb | giastantino/repository |
***Define data X and targets y for our neural network. | from sklearn.model_selection import train_test_split
# define target y and data X
X = client_df.drop(['client_id','segment', 'attrition_flag'],axis=1).values
y = client_df[['segment']] | _____no_output_____ | Apache-2.0 | _notebooks/2022-03-28-mlp-classifier.ipynb | giastantino/repository |
Transform the data and encode the targets. We need to one-hot encode the target classes as neural network will return 'probability' for each class in separate neurons. | from sklearn.preprocessing import PowerTransformer, LabelEncoder
from keras.utils import np_utils
# encode data X
ptr = PowerTransformer()
X = ptr.fit_transform(X)
# encode target y
encoder = LabelEncoder()
encoded_y = encoder.fit_transform(np.ravel(y))
# convert integers to dummy variables (i.e. one hot encoded)
dum... | _____no_output_____ | Apache-2.0 | _notebooks/2022-03-28-mlp-classifier.ipynb | giastantino/repository |
Split the data into training and testing dataset. | from sklearn.model_selection import train_test_split
# define the 80_20 train_test splits
X_train, X_test, y_train, y_test = train_test_split(X, dummy_y, test_size=0.2, random_state=42) | _____no_output_____ | Apache-2.0 | _notebooks/2022-03-28-mlp-classifier.ipynb | giastantino/repository |
Baseline model In this notebook we are using Multilayer Perceptron as our classifier. Let's define the base model with 10 neurons in the hidden layer. | from keras.models import Sequential
from keras.layers import Dense, Dropout
# define number of input features
input_features = X_train.shape[1]
# uncompiled model
def uncompiled_base(input_dim=4):
# create model
model = Sequential()
model.add(Dense(10, input_dim=input_dim, activation='linear'))
model.add(Dense... | BASELINE accuracy: 96.64 validation accuracy: 97.11
| Apache-2.0 | _notebooks/2022-03-28-mlp-classifier.ipynb | giastantino/repository |
The baseline model with linear neuron scores around 97% in training. Let's try to best it with modifications. Activation Function The activation function is performed on the sum of all inputs, for the classic perceptron it was a unipolar function, which output was a binary function. However, in modern neural networks... | def get_active_model(input_dim=4, act_fun='relu'):
# create model
model = Sequential()
model.add(Dense(10, input_dim=input_dim, activation=act_fun))
model.add(Dense(4, activation='softmax'))
# compile model
model.compile(loss='categorical_crossentropy',
optimizer='adam',
m... | Sigmoid model accuracy: 95.97 validation accuracy: 95.44
ReLU model accuracy: 97.21 validation accuracy: 97.19
Softmax model accuracy: 96.45 validation accuracy: 96.20
| Apache-2.0 | _notebooks/2022-03-28-mlp-classifier.ipynb | giastantino/repository |
In our case model with ReLU activation function outperform other MLPs. It has 0.0.6% better accuracy than the baseline model with linear function, which is 17% error reduction! Let's use the ReLU function for further experiments.> Warning: Sometimes sigmoid or softmax function may outperform ReLu based models when chan... | def get_model(input_dim=4, hidden_layers=[], act_fun='relu'):
# create model
model = Sequential()
# add initial layer
model.add(Dense(hidden_layers[0], input_dim=input_dim, activation=act_fun))
# add hidden layers
for layer in hidden_layers[1:]:
model.add(Dense(layer, activation=act_fun))
# add final l... | hidden layers: [10] accuracy: 96.37 validation accuracy: 96.05
hidden layers: [50] accuracy: 98.19 validation accuracy: 97.64
hidden layers: [10, 10] accuracy: 96.88 validation accuracy: 96.20
hidden layers: [50, 50] accuracy: 99.14 validation accuracy: 97.80
hidden layers: [100, 100] accuracy: 99.28 ... | Apache-2.0 | _notebooks/2022-03-28-mlp-classifier.ipynb | giastantino/repository |
We can see that increasing number of layers and neurons has a positive impact on training accuracy, however it is not that obvious for validation subset. We can see that models bigger than `[50, 50]` hidden layers do better in training but not in validation - this suggests that bigger models are overfitting. In other w... | # batch sizes
batches = [1, 10, 20, 50, 100]
# model results history dictionary
history = dict()
# define model
mlp = get_model(input_dim=input_features, hidden_layers=[50,50])
# iterate through batch sizes
for b in batches:
story = mlp.fit(X_train, y_train, validation_split=0.2, epochs=100, batch_size=b, verbose=0)
... | _____no_output_____ | Apache-2.0 | _notebooks/2022-03-28-mlp-classifier.ipynb | giastantino/repository |
In the above figure we can clearly see that accuracy score for `batch_size = 1` is very irregular and thus not predictible. On the other hand, for large batch sizes score is stable, which suggest that network doesn't learn new features with consequent epochs. Therefore we are going to proceed with `batch_size = 10`, wh... | # fit the model
model = get_model(input_dim=input_features, hidden_layers=[50,50],)
history = model.fit(X_train, y_train, validation_split=0.2, epochs=150, batch_size=10, verbose=0)
#collapse-hide
# define dataframe with model metrics
df = pd.DataFrame(history.history, columns=history.history.keys())
# setup figure
fi... | _____no_output_____ | Apache-2.0 | _notebooks/2022-03-28-mlp-classifier.ipynb | giastantino/repository |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.