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 fit the O-C points measured above using MCMC by calling the run_mcmc() function We plot both the fit, as well as the triangle plot showing the two- (and one-)dimensional posterior distributions (these can be suppressed by setting the optional parameters "plot_oc" and "plot_triangle" to False)
sampler, fit_mcmc, oc_sigmas, param_means, param_sigmas, fit_at_points, K =\ octs.run_mcmc(oc_jd, oc_oc, oc_sd, prior_ranges, pos, nsteps = 31000, discard = 1000, thin = 300, processes=1)
100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 31000/31000 [03:08<00:00, 164.32it/s] 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 20000/20000 [00:02<00:00, 8267.13it/s]
MIT
06498_oc.ipynb
gerhajdu/rrl_binaries_1
The estimated LTTE parameters are:
print("Orbital period: {:d} +- {:d} [d]".format(int(param_means[0]), int(param_sigmas[0]))) print("Projected semi-major axis: {:.3f} +- {:.3f} [AU]".format(param_means[2]*173.144633, ...
Orbital period: 2803 +- 3 [d] Projected semi-major axis: 2.492 +- 0.010 [AU] Eccentricity: 0.136 +- 0.008 Argumen of periastron: -76 +- 3 [deg] Periastron passage time: 6538 +- 24 [HJD-2450000] Period-change rate: -0.002 +- 0.005 [d/Myr] RV semi-amplitude: 9.76 +- 0...
MIT
06498_oc.ipynb
gerhajdu/rrl_binaries_1
Consensus Optimization This notebook contains the code for the toy experiment in the paper [The Numerics of GANs](https://arxiv.org/abs/1705.10461).
%load_ext autoreload %autoreload 2 import tensorflow as tf from tensorflow.contrib import slim import numpy as np import scipy as sp from scipy import stats from matplotlib import pyplot as plt import sys, os from tqdm import tqdm_notebook tf.reset_default_graph() def kde(mu, tau, bbox=[-5, 5, -5, 5], save_file="", xl...
MIT
notebooks/mog-eigval-dist.ipynb
LMescheder/TheNumericsOfGANs
Getting Started with Tensorflow
import tensorflow as tf # Create TensorFlow object called tensor hello_constant = tf.constant('Hello World!') with tf.Session() as sess: # Run the tf.constant operation in the session output = sess.run(hello_constant) print(output); A = tf.constant(1234) B = tf.constant([123, 456, 789]) C = tf.constant(...
_____no_output_____
MIT
TensorFlowIntro/.ipynb_checkpoints/TensorFlowIntroduction-checkpoint.ipynb
dschmoeller/03TrafficSignClassifierCNN
Build a Neural Network with Tensorflow
# Coding example for building a neural network with tensorflow # Quiz Solution import tensorflow as tf output = None hidden_layer_weights = [ [0.1, 0.2, 0.4], [0.4, 0.6, 0.6], [0.5, 0.9, 0.1], [0.8, 0.2, 0.8]] out_weights = [ [0.1, 0.6], [0.2, 0.1], [0.7, 0.9]] # Weights and biases weights...
_____no_output_____
MIT
TensorFlowIntro/.ipynb_checkpoints/TensorFlowIntroduction-checkpoint.ipynb
dschmoeller/03TrafficSignClassifierCNN
Deep Neural Networks in Tensorflow
# For stacking muliple layers --> Deep NN # Store layers weight & bias weights = { 'hidden_layer': tf.Variable(tf.random_normal([n_input, n_hidden_layer])), 'out': tf.Variable(tf.random_normal([n_hidden_layer, n_classes])) } biases = { 'hidden_layer': tf.Variable(tf.random_normal([n_hidden_layer])), 'o...
_____no_output_____
MIT
TensorFlowIntro/.ipynb_checkpoints/TensorFlowIntroduction-checkpoint.ipynb
dschmoeller/03TrafficSignClassifierCNN
Saving Variables and trained Models and load them backYou save the particular **session** in a file
import tensorflow as tf # The file path to save the data save_file = './model.ckpt' # Two Tensor Variables: weights and bias weights = tf.Variable(tf.truncated_normal([2, 3])) bias = tf.Variable(tf.truncated_normal([3])) # Class used to save and/or restore Tensor Variables saver = tf.train.Saver() with tf.Session()...
_____no_output_____
MIT
TensorFlowIntro/.ipynb_checkpoints/TensorFlowIntroduction-checkpoint.ipynb
dschmoeller/03TrafficSignClassifierCNN
... same works for models. Just train a NN like shown above and save the session afterwards Dropout for regularization in Tensorflow
# In tensorflow, dropout is just another "layer" in the model #During training, a good starting value for keep_prob is 0.5. #During testing, use a keep_prob value of 1.0 to keep all units and maximize the power of the model. keep_prob = tf.placeholder(tf.float32) # probability to keep units hidden_layer = tf.add(tf.m...
_____no_output_____
MIT
TensorFlowIntro/.ipynb_checkpoints/TensorFlowIntroduction-checkpoint.ipynb
dschmoeller/03TrafficSignClassifierCNN
Convolutinal Neural Network (CNN)
# Note the output shape of conv will be [1, 16, 16, 20]. # It's 4D to account for batch size, but more importantly, it's not [1, 14, 14, 20]. # This is because the padding algorithm TensorFlow uses is not exactly the same as the one above. # An alternative algorithm is to switch padding from 'SAME' to 'VALID' input ...
_____no_output_____
MIT
TensorFlowIntro/.ipynb_checkpoints/TensorFlowIntroduction-checkpoint.ipynb
dschmoeller/03TrafficSignClassifierCNN
Example code for constructing a CNN
# Load data set # Batch, scale and one-hot-encode it # Set Parameters from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets(".", one_hot=True, reshape=False) import tensorflow as tf # Parameters learning_rate = 0.00001 epochs = 10 batch_size = 128 # Number of samples to calcu...
_____no_output_____
MIT
TensorFlowIntro/.ipynb_checkpoints/TensorFlowIntroduction-checkpoint.ipynb
dschmoeller/03TrafficSignClassifierCNN
LeNet Architecture Load DataLoad the MNIST data, which comes pre-loaded with TensorFlow.You do not need to modify this section.
from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", reshape=False) X_train, y_train = mnist.train.images, mnist.train.labels X_validation, y_validation = mnist.validation.images, mnist.validation.labels X_test, y_test = mnist.test.images, mn...
_____no_output_____
MIT
TensorFlowIntro/.ipynb_checkpoints/TensorFlowIntroduction-checkpoint.ipynb
dschmoeller/03TrafficSignClassifierCNN
Split up data into training, validation and test set
import numpy as np # Pad images with 0s X_train = np.pad(X_train, ((0,0),(2,2),(2,2),(0,0)), 'constant') X_validation = np.pad(X_validation, ((0,0),(2,2),(2,2),(0,0)), 'constant') X_test = np.pad(X_test, ((0,0),(2,2),(2,2),(0,0)), 'constant') print("Updated Image Shape: {}".format(X_train[0].shape))
_____no_output_____
MIT
TensorFlowIntro/.ipynb_checkpoints/TensorFlowIntroduction-checkpoint.ipynb
dschmoeller/03TrafficSignClassifierCNN
Visualize DataView a sample from the dataset.You do not need to modify this section.
import random import numpy as np import matplotlib.pyplot as plt %matplotlib inline index = random.randint(0, len(X_train)) image = X_train[index].squeeze() plt.figure(figsize=(1,1)) plt.imshow(image, cmap="gray") print(y_train[index])
_____no_output_____
MIT
TensorFlowIntro/.ipynb_checkpoints/TensorFlowIntroduction-checkpoint.ipynb
dschmoeller/03TrafficSignClassifierCNN
Preprocess DataShuffle the training data.You do not need to modify this section.
from sklearn.utils import shuffle X_train, y_train = shuffle(X_train, y_train)
_____no_output_____
MIT
TensorFlowIntro/.ipynb_checkpoints/TensorFlowIntroduction-checkpoint.ipynb
dschmoeller/03TrafficSignClassifierCNN
Setup TensorFlowThe `EPOCH` and `BATCH_SIZE` values affect the training speed and model accuracy.
import tensorflow as tf EPOCHS = 10 BATCH_SIZE = 128
_____no_output_____
MIT
TensorFlowIntro/.ipynb_checkpoints/TensorFlowIntroduction-checkpoint.ipynb
dschmoeller/03TrafficSignClassifierCNN
InputThe LeNet architecture accepts a 32x32xC image as input, where C is the number of color channels. Since MNIST images are grayscale, C is 1 in this case. Architecture**Layer 1: Convolutional.** The output shape should be 28x28x6.**Activation.** Your choice of activation function.**Pooling.** The output shape shoul...
from tensorflow.contrib.layers import flatten def LeNet(x): # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer mu = 0 sigma = 0.1 weights = { 'wc1': tf.Variable(tf.random_normal([5, 5, 1, 6])), 'wc2': tf.Variable(tf.ra...
_____no_output_____
MIT
TensorFlowIntro/.ipynb_checkpoints/TensorFlowIntroduction-checkpoint.ipynb
dschmoeller/03TrafficSignClassifierCNN
Features and LabelsTrain LeNet to classify [MNIST](http://yann.lecun.com/exdb/mnist/) data.`x` is a placeholder for a batch of input images.`y` is a placeholder for a batch of output labels.
x = tf.placeholder(tf.float32, (None, 32, 32, 1)) y = tf.placeholder(tf.int32, (None)) one_hot_y = tf.one_hot(y, 10)
_____no_output_____
MIT
TensorFlowIntro/.ipynb_checkpoints/TensorFlowIntroduction-checkpoint.ipynb
dschmoeller/03TrafficSignClassifierCNN
Training PipelineCreate a training pipeline that uses the model to classify MNIST data.
rate = 0.001 logits = LeNet(x) cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits) loss_operation = tf.reduce_mean(cross_entropy) optimizer = tf.train.AdamOptimizer(learning_rate = rate) training_operation = optimizer.minimize(loss_operation)
_____no_output_____
MIT
TensorFlowIntro/.ipynb_checkpoints/TensorFlowIntroduction-checkpoint.ipynb
dschmoeller/03TrafficSignClassifierCNN
Model EvaluationEvaluate how well the loss and accuracy of the model for a given dataset.
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1)) accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) saver = tf.train.Saver() def evaluate(X_data, y_data): num_examples = len(X_data) total_accuracy = 0 sess = tf.get_default_session() for offset in ra...
_____no_output_____
MIT
TensorFlowIntro/.ipynb_checkpoints/TensorFlowIntroduction-checkpoint.ipynb
dschmoeller/03TrafficSignClassifierCNN
Train the ModelRun the training data through the training pipeline to train the model.Before each epoch, shuffle the training set.After each epoch, measure the loss and accuracy of the validation set.Save the model after training.
with tf.Session() as sess: sess.run(tf.global_variables_initializer()) num_examples = len(X_train) print("Training...") print() for i in range(EPOCHS): X_train, y_train = shuffle(X_train, y_train) for offset in range(0, num_examples, BATCH_SIZE): end = offset + BATCH...
_____no_output_____
MIT
TensorFlowIntro/.ipynb_checkpoints/TensorFlowIntroduction-checkpoint.ipynb
dschmoeller/03TrafficSignClassifierCNN
Evaluate the Model (on the test set)Once you are completely satisfied with your model, evaluate the performance of the model on the test set.Be sure to only do this once!If you were to measure the performance of your trained model on the test set, then improve your model, and then measure the performance of your model...
with tf.Session() as sess: saver.restore(sess, tf.train.latest_checkpoint('.')) test_accuracy = evaluate(X_test, y_test) print("Test Accuracy = {:.3f}".format(test_accuracy))
_____no_output_____
MIT
TensorFlowIntro/.ipynb_checkpoints/TensorFlowIntroduction-checkpoint.ipynb
dschmoeller/03TrafficSignClassifierCNN
pip install pydicom # Import tensorflow import logging import tensorflow as tf import keras.backend as K # Helper libraries import math import numpy as np import pandas as pd import pydicom import os import sys import time # Imports for dataset manipulation from sklearn.model_selection import train_test_split from k...
_____no_output_____
Apache-2.0
ipynbs/reshape_demo.ipynb
zbytes/fsqs-tips-tricks-notes
20 Sept 2019 RULESDate: Level 2 heading Example Heading: Level 3 heading Method Heading: Level 4 heading References 1. [Forester_W._Isen;_J._Moura]_DSP_for_MATLAB_and_La Volume II(z-lib.org)2. H. K. Dass, Advanced Engineering Mathematics3. [Forester_W._Isen;_J._Moura]_DSP_for_MATLAB_and_La Volume I(z-lib.org)4. [Jo...
import numpy as np from sympy import oo import math import sympy as sp import matplotlib.pyplot as plt import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D from IPython.display import display from IPython.display import display_latex from sympy import latex import math from scipy import signal from datetime...
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
Setup
sp.init_printing(use_latex = True) z, f, i = sp.symbols('z f i') x, k = sp.symbols('x k')
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
Methods
# Usage: display_equation('u_x', x) def display_equation(idx, symObj): if(isinstance(idx, str)): eqn = '\\[' + idx + ' = ' + latex(symObj) + '\\]' display_latex(eqn, raw=True) else: eqn = '\\[' + latex(idx) + ' = ' + latex(symObj) + '\\]' display_latex(eqn, raw=True) return #...
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
Z Transform
display_full_latex('X(z) = \sum_{-\infty}^{\infty} x[n]z^{-n}')
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
Tests Convert Symbolic to Numeric
f = x**2 f = sp.lambdify(x, f, 'numpy') f(2) display_equation('f(x)', sp.summation(3**k, ( k, -oo, oo ))) display_equation('F(z)', sp.summation(3**k/z**k, ( k, -oo, oo )))
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
Partial Fractions
f = 1/(x**2 + x - 6) display_equation('f(x)', f) f = sp.apart(f) display_equation('f(x)_{canonical}', f)
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
Piecewise
f1 = 5**k f2 = 3**k f = sp.Piecewise((f1, k < 0), (f2, k >= 0)) display_equation('f(k)', f)
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
21 Sept 2019 Positive Time / Causal
f1 = k **2 f2 = 3**k f = f1 * sp.Heaviside(k) # or #f = sp.Piecewise((0, k < 0), (f1, k >= 0)) display_equation('f(k)', f) sp.plot(f, (k, -10, 10))
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
Stem Plot
x = np.linspace(0.1, 2 * np.pi, 41) y = np.sin(x) plt.stem(x, y) plt.show()
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
zplane Plot
b = np.array([1, 1, 0, 0]) a = np.array([1, 1, 1]) zplane(b,a)
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
Filter
g = (1 + z**-2)/(1-1.2*z**-1+0.81*z**-2) display_equation('F(z)', g) b = np.array([1,1]) a = np.array([1,-1.2,0.81]) x = np.ones((1, 8)) # Response y = signal.lfilter(b, a, x) # Reverse signal.lfilter(a, b, y)
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
[1] Example 2.2
radFreq = np.arange(0, 2*np.pi, 2*np.pi/499) g = np.exp(1j*radFreq) Zxform= 1/(1-0.7*g**(-1)) plt.plot(radFreq/np.pi,abs(Zxform)) plt.title('Graph') plt.xlabel('Frequency, Units of Ο€') plt.ylabel('H(x)') plt.grid(True) plt.show()
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
[2] Chapter 19, Example 5
f = 3**(-k) display_ztrans(f, k, (-4, 3))
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
[2] Example 9
f1 = 5**k f2 = 3**k f = sp.Piecewise((f1, k < 0), (f2, k >= 0)) display_ztrans(f, k, (-3, 3)) p = sum_of_GP(z/5, z/5) q = sum_of_GP(1, 3/z) display_equation('F(z)', sp.ratsimp(q + p))
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
28 Sept, 2019 [3] Folding formula fperceived = [ f - fsampling * NINT( f / fsampling ) ] 9 Oct, 2019 [3] Section 4.3 Equations
display_full_latex('F \\rightarrow analog') display_full_latex('f \\rightarrow discrete') display_full_latex('Nyquist frequency = F_s') display_full_latex('Folding frequency = \\frac{F_s}{2}') display_full_latex('F_{max} = \\frac{F_s}{2}') display_full_latex('T = \\frac{1}{F_s}') display_full_latex('f = \\frac{F}{F_s}'...
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
14 Oct, 2019
n = sp.symbols('n') x = np.arange(0, 10, 1) y = x * np.heaviside(x, 1) f = sp.Piecewise((0, n < 0), (n, n >= 0)) display_equation('u_r(n)', f) plt.stem(x, y) plt.plot(x, y, 'g-') plt.xticks(np.arange(0, 10, 1)) plt.yticks(np.arange(0, 10, 1)) plt.xlabel('n') plt.ylabel('x(n)') plt.grid(True) plt.show() display_full_...
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
16 Oct, 2019 General form of the input-output relationships
display_full_latex('y(n) = -\\sum^N _{k = 1}a_k y(n-k) + \\sum^M _{k = 0}b_k x(n-k)')
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
[4] Example 3.2
h = np.array([1, 2, 1, -1]) x = np.array([1, 2, 3, 1]) y = np.convolve(h, x, mode='full') #y = signal.convolve(h, x, mode='full', method='auto') print(y) fig, (ax_orig, ax_h, ax_x) = plt.subplots(3, 1, sharex=True) ax_orig.plot(h) ax_orig.set_title('Impulse Response') ax_orig.margins(0, 0.1) ax_h.plot(x) ax_h.set_titl...
[ 1 4 8 8 3 -2 -1]
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
17 Oct, 2019 Sum of an AP with common ratio r and first term a, starting from the zeroth term
a, r = sp.symbols('a r') s = sp.summation(a*r**k, ( k, 0, n )) display_equation('S_n', s)
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
Sum of positive powers of a
a = sp.symbols('a') s = sp.summation(a**k, ( k, 0, n )) display_equation('S_n', s)
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
[3] 4.12.3 Single Pole IIR
SR = 24 b = 1 p = 0.8 y = np.zeros((1, SR)).ravel() x = np.zeros((1, SR + 1)).ravel() x[0] = 1 y[0] = b * x[0] for n in range(1, SR): y[n] = b * x[n] + p * y[n - 1] plt.stem(y)
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
Copying the method above for [4] 4.1 Averaging
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) y[0] = b * x[0] for n in range(1, len(x)): y[n] = (n/(n + 1)) * y[n - 1] + (1/(n + 1)) * x[n] print(y[n], '\n')
5.5
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
My Recursive Averaging Implementation
def avg(x, n): if (n < 0): return 0 else: return (n/(n + 1)) * avg(x, n - 1) + (1/(n + 1)) * x[n] x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) average = avg(x, len(x) - 1) print(average)
5.5
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
Performance Comparism
from timeit import timeit code_rec = ''' import numpy as np def avg(x, n): if (n < 0): return 0 else: return (n/(n + 1)) * avg(x, n - 1) + (1/(n + 1)) * x[n] x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) average = avg(x, len(x) - 1) ''' code_py = ''' import numpy as np x = np.array(...
Running time using my recursive average function: 9.264100000000001e-05 Running time using python sum function: 4.1410000000000005e-05 Running time using loop python function: 7.479999999999987e-06
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
[4] Example 4.1
def rec_sqrt(x, n): if (n == -1): return 1 else: return (1/2) * (rec_sqrt(x, n - 1) + (x[n]/rec_sqrt(x, n - 1))) A = 2 x = np.ones((1, 5)).ravel() * A print(rec_sqrt(x, len(x) - 1)) b = np.array([1, 1, 1, 1, 1]) a = np.array([1, 0, 0]) zplane(b,a)
_____no_output_____
MIT
.ipynb_checkpoints/DSP-checkpoint.ipynb
Valentine-Efagene/Jupyter-Notebooks
langages de script – Python Modules et packages M1 IngΓ©nierie Multilingue – INaLCOclement.plancq@ens.fr Les modules et les packages permettent d'ajouter des fonctionnalitΓ©s Γ  PythonUn module est un fichier (```.py```) qui contient des fonctions et/ou des classes. Et de la documentation bien sΓ»rUn package est un rΓ©pe...
%%file operations.py # -*- coding: utf-8 -*- """ Module pour le cours sur les modules OpΓ©rations arithmΓ©tiques """ def addition(a, b): """ Ben une addition quoi : a + b """ return a + b def soustraction(a, b): """ Une soustraction :Β a - b """ return a - b
_____no_output_____
MIT
modules.ipynb
LoicGrobol/python-im
Pour l'utiliser on peut :* l'importer par son nom
import operations operations.addition(2, 4)
_____no_output_____
MIT
modules.ipynb
LoicGrobol/python-im
* l'importer et modifier son nom
import operations as op op.addition(2, 4)
_____no_output_____
MIT
modules.ipynb
LoicGrobol/python-im
* importer une partie du module
from operations import addition addition(2, 4)
_____no_output_____
MIT
modules.ipynb
LoicGrobol/python-im
* importer l'intΓ©gralitΓ© du module
from operations import * addition(2, 4) soustraction(4, 2)
_____no_output_____
MIT
modules.ipynb
LoicGrobol/python-im
En rΓ©alitΓ© seules les fonctions et/ou les classes ne commenΓ§ant pas par '_' sont importΓ©es. L'utilisation de `import *` n'est pas recommandΓ©e. Parce que, comme vous le savez Β« *explicit is better than implicit* Β». Et en ajoutant les fonctions dans l'espace de nommage du script vous pouvez Γ©craser des fonctions existant...
import operations type(operations)
_____no_output_____
MIT
modules.ipynb
LoicGrobol/python-im
``import`` ajoute des attributs au module
import operations print(f"name : {operations.__name__}") print(f"file : {operations.__file__}") print(f"doc :Β {operations.__doc__}")
_____no_output_____
MIT
modules.ipynb
LoicGrobol/python-im
Un package
! tree operations_pack
_____no_output_____
MIT
modules.ipynb
LoicGrobol/python-im
Un package python peut contenir des modules, des rΓ©pertoires et sous-rΓ©pertoires, et bien souvent du non-python :Β de la doc html, des donnΓ©es pour les tests, etc… Le rΓ©pertoire principal et les rΓ©pertoires contenant des modules python doivent contenir un fichier `__init__.py` `__init__.py` peut Γͺtre vide, contenir du c...
import operations_pack.simple operations_pack.simple.addition(2, 4) from operations_pack import simple simple.soustraction(4, 2)
_____no_output_____
MIT
modules.ipynb
LoicGrobol/python-im
``__all__`` dans ``__init__.py`` dΓ©finit quels seront les modules qui seront importΓ©s avec ``import *``
from operations_pack.avance import * multi.multiplication(2,4)
_____no_output_____
MIT
modules.ipynb
LoicGrobol/python-im
OΓΉ sont les modules et les packages ? Pour que ``import`` fonctionne il faut que les modules soient dans le PATH.
import sys sys.path
_____no_output_____
MIT
modules.ipynb
LoicGrobol/python-im
``sys.path`` est une liste, vous pouvez la modifier
sys.path.append("[...]") # le chemin vers le dossier operations_pack sys.path
_____no_output_____
MIT
modules.ipynb
LoicGrobol/python-im
DSPT6 - Adding Data Science to a Web ApplicationThe purpose of this notebook is to demonstrate:- Simple online analysis of data from a user of the Twitoff app or an API- Train a more complicated offline model, and serialize the results for online use
import sqlite3 import pickle import pandas as pd # Connect to sqlite database conn = sqlite3.connect('../twitoff/twitoff.sqlite') def get_data(query, conn): '''Function to get data from SQLite DB''' cursor = conn.cursor() result = cursor.execute(query).fetchall() # Get columns from cursor object ...
_____no_output_____
MIT
notebooks/LS333_DSPT6_Model_Demo.ipynb
DrewRust/DSPT6-Twitoff
Working with Watson Machine Learning This notebook should be run in a Watson Studio project, using **Default Python 3.7.x** runtime environment. **If you are viewing this in Watson Studio and do not see Python 3.7.x in the upper right corner of your screen, please update the runtime now.** It requires service credent...
import warnings warnings.filterwarnings('ignore') !rm -rf /home/spark/shared/user-libs/python3.7* !pip install --upgrade pandas==1.2.3 --no-cache | tail -n 1 !pip install --upgrade requests==2.23 --no-cache | tail -n 1 !pip install --upgrade numpy==1.20.3 --user --no-cache | tail -n 1 !pip install SciPy --no-cache | t...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Provision services and configure credentials If you have not already, provision an instance of IBM Watson OpenScale using the [OpenScale link in the Cloud catalog](https://cloud.ibm.com/catalog/services/watson-openscale). Your Cloud API key can be generated by going to the [**Users** section of the Cloud console](http...
CLOUD_API_KEY = "***" IAM_URL="https://iam.ng.bluemix.net/oidc/token"
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
If you have not already, provision an instance of IBM Watson OpenScale using the [OpenScale link in the Cloud catalog](https://cloud.ibm.com/catalog/services/watson-openscale).Your Cloud API key can be generated by going to the [**Users** section of the Cloud console](https://cloud.ibm.com/iam/users). From that page, c...
WML_CREDENTIALS = { "url": "https://us-south.ml.cloud.ibm.com", "apikey": CLOUD_API_KEY }
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
WML credentials example using IAM_token **NOTE**: If IAM_TOKEN is used for authentication and you receive unauthorized/expired token error at any steps, please create a new token and reinitiate clients authentication.
# #uncomment this cell if want to use IAM_TOKEN # import requests # def generate_access_token(): # headers={} # headers["Content-Type"] = "application/x-www-form-urlencoded" # headers["Accept"] = "application/json" # auth = HTTPBasicAuth("bx", "bx") # data = { # "grant_type": "urn:ibm:params...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Cloud object storage detailsIn next cells, you will need to paste some credentials to Cloud Object Storage. If you haven't worked with COS yet please visit [getting started with COS tutorial](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-getting-started). You can find `COS_API_KEY_ID` and ...
COS_API_KEY_ID = "***" COS_RESOURCE_CRN = "***" # eg "crn:v1:bluemix:public:cloud-object-storage:global:a/3bf0d9003abfb5d29761c3e97696b71c:d6f04d83-6c4f-4a62-a165-696756d63903::" COS_ENDPOINT = "***" # Current list avaiable at https://control.cloud-object-storage.cloud.ibm.com/v2/endpoints BUCKET_NAME = "***" training...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
This tutorial can use Databases for PostgreSQL, Db2 Warehouse, or a free internal verison of PostgreSQL to create a datamart for OpenScale.If you have previously configured OpenScale, it will use your existing datamart, and not interfere with any models you are currently monitoring. Do not update the cell below.If you ...
DB_CREDENTIALS = None #DB_CREDENTIALS= {"hostname":"","username":"","password":"","database":"","port":"","ssl":True,"sslmode":"","certificate_base64":""} KEEP_MY_INTERNAL_POSTGRES = True
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Run the notebookAt this point, the notebook is ready to run. You can either run the cells one at a time, or click the **Kernel** option above and select **Restart and Run All** to run all the cells. Model building and deployment In this section you will learn how to train Spark MLLib model and next deploy it as web-...
!rm house_price_regression.csv !wget https://raw.githubusercontent.com/IBM/watson-openscale-samples/main/IBM%20Cloud/WML/assets/data/house_price/house_price_regression.csv import pandas as pd import numpy as np pd_data = pd.read_csv("house_price_regression.csv") pd_data.head()
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Explore data Save training data to Cloud Object Storage
import ibm_boto3 from ibm_botocore.client import Config, ClientError cos_client = ibm_boto3.resource("s3", ibm_api_key_id=COS_API_KEY_ID, ibm_service_instance_id=COS_RESOURCE_CRN, ibm_auth_endpoint="https://iam.bluemix.net/oidc/token", config=Config(signature_version="oauth"), endpoint_url=COS_ENDP...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Create a model
from sklearn.model_selection import train_test_split from sklearn.impute import SimpleImputer pd_data.dropna(axis=0, subset=['SalePrice'], inplace=True) label = pd_data.SalePrice feature_data = pd_data.drop(['SalePrice'], axis=1).select_dtypes(exclude=['object']) train_X, test_X, train_y, test_y = train_test_split(fea...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
wrap xgboost with scikit pipeline
from sklearn.pipeline import Pipeline xgb_model_imputer = SimpleImputer(missing_values=np.nan, strategy='mean') pipeline = Pipeline(steps=[('Imputer', xgb_model_imputer), ('xgb', model)]) model_xgb=pipeline.fit(train_X, train_y) # make predictions predictions = model_xgb.predict(test_X) from sklearn.metrics import mean...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Publish the model
import json from ibm_watson_machine_learning import APIClient wml_client = APIClient(WML_CREDENTIALS) wml_client.version
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Listing all the available spaces
wml_client.spaces.list(limit=10) WML_SPACE_ID='***' # use space id here wml_client.set.default_space(WML_SPACE_ID)
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Remove existing model and deployment
MODEL_NAME="house_price_xgbregression" DEPLOYMENT_NAME="house_price_xgbregression_deployment" deployments_list = wml_client.deployments.get_details() for deployment in deployments_list["resources"]: model_id = deployment["entity"]["asset"]["id"] deployment_id = deployment["metadata"]["id"] if deployment["me...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Deploy the model The next section of the notebook deploys the model as a RESTful web service in Watson Machine Learning. The deployed model will have a scoring URL you can use to send data to the model for predictions.
deployment_details = wml_client.deployments.create( model_uid, meta_props={ wml_client.deployments.ConfigurationMetaNames.NAME: "{}".format(DEPLOYMENT_NAME), wml_client.deployments.ConfigurationMetaNames.ONLINE: {} } ) scoring_url = wml_client.deployments.get_scoring_href(deployment_details...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Sample scoring
fields = feature_data.columns.tolist() values = [ test_X[0].tolist() ] scoring_payload = {"input_data": [{"fields": fields, "values": values}]} scoring_payload scoring_response = wml_client.deployments.score(deployment_uid, scoring_payload) scoring_response
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Configure OpenScale The notebook will now import the necessary libraries and set up a Python OpenScale client.
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator,BearerTokenAuthenticator from ibm_watson_openscale import * from ibm_watson_openscale.supporting_classes.enums import * from ibm_watson_openscale.supporting_classes import * authenticator = IAMAuthenticator(apikey=CLOUD_API_KEY) wos_client = APIClient(au...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Create schema and datamart Set up datamart Watson OpenScale uses a database to store payload logs and calculated metrics. If database credentials were **not** supplied above, the notebook will use the free, internal lite database. If database credentials were supplied, the datamart will be created there **unless** th...
wos_client.data_marts.show() data_marts = wos_client.data_marts.list().result.data_marts if len(data_marts) == 0: if DB_CREDENTIALS is not None: if SCHEMA_NAME is None: print("Please specify the SCHEMA_NAME and rerun the cell") print('Setting up external datamart') added_data_m...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Remove existing service provider connected with used WML instance. Multiple service providers for the same engine instance are avaiable in Watson OpenScale. To avoid multiple service providers of used WML instance in the tutorial notebook the following code deletes existing service provder(s) and then adds new one.
SERVICE_PROVIDER_NAME = "xgboost_WML V2" SERVICE_PROVIDER_DESCRIPTION = "Added by tutorial WOS notebook." service_providers = wos_client.service_providers.list().result.service_providers for service_provider in service_providers: service_instance_name = service_provider.entity.name if service_instance_name == S...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Add service provider Watson OpenScale needs to be bound to the Watson Machine Learning instance to capture payload data into and out of the model. **Note:** You can bind more than one engine instance if needed by calling `wos_client.service_providers.add` method. Next, you can refer to particular service provider usin...
added_service_provider_result = wos_client.service_providers.add( name=SERVICE_PROVIDER_NAME, description=SERVICE_PROVIDER_DESCRIPTION, service_type=ServiceTypes.WATSON_MACHINE_LEARNING, deployment_space_id = WML_SPACE_ID, operational_space_id = "production", credentials=...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Subscriptions Remove existing House price model subscriptions This code removes previous subscriptions to the House price model to refresh the monitors with the new model and new data.
wos_client.subscriptions.show()
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
This code removes previous subscriptions to the House price model to refresh the monitors with the new model and new data.
subscriptions = wos_client.subscriptions.list().result.subscriptions for subscription in subscriptions: sub_model_id = subscription.entity.asset.asset_id if sub_model_id == model_uid: wos_client.subscriptions.delete(subscription.metadata.id) print('Deleted existing subscription for model', sub_m...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
This code creates the model subscription in OpenScale using the Python client API. Note that we need to provide the model unique identifier, and some information about the model itself. This code creates the model subscription in OpenScale using the Python client API. Note that we need to provide the model unique iden...
feature_cols=feature_data.columns.tolist() #categorical_cols=X.select_dtypes(include=['object']).columns from ibm_watson_openscale.base_classes.watson_open_scale_v2 import ScoringEndpointRequest subscription_details = wos_client.subscriptions.add( data_mart_id=data_mart_id, service_provider_id=service_p...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Get subscription list
wos_client.subscriptions.show()
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Score the model so we can configure monitors
import random fields = feature_data.columns.tolist() values = random.sample(test_X.tolist(), 2) scoring_payload = {"input_data": [{"fields": fields, "values": values}]} predictions = wml_client.deployments.score(deployment_uid, scoring_payload) print("Single record scoring result:", "\n fields:", prediction...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Check if WML payload logging worked else manually store payload records
import uuid from ibm_watson_openscale.supporting_classes.payload_record import PayloadRecord time.sleep(5) pl_records_count = wos_client.data_sets.get_records_count(payload_data_set_id) print("Number of records in the payload logging table: {}".format(pl_records_count)) if pl_records_count == 0: print("Payload logg...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Quality monitoring and feedback logging Enable quality monitoring
import time time.sleep(10) target = Target( target_type=TargetTypes.SUBSCRIPTION, target_id=subscription_id ) parameters = { "min_feedback_data_size": 50 } quality_monitor_details = wos_client.monitor_instances.create( data_mart_id=data_mart_id, background_mode=False, monitor_definition...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Feedback logging The code below downloads and stores enough feedback data to meet the minimum threshold so that OpenScale can calculate a new accuracy measurement. It then kicks off the accuracy monitor. The monitors run hourly, or can be initiated via the Python API, the REST API, or the graphical user interface. Ge...
feedback_dataset_id = None feedback_dataset = wos_client.data_sets.list(type=DataSetTypes.FEEDBACK, target_target_id=subscription_id, target_target_type=TargetTypes.SUBSCRIPTION).result print(feedback_dataset) feedback_dat...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Fairness, drift monitoring and explanations Fairness configurationThe code below configures fairness monitoring for our model. It turns on monitoring for one features, MSSubClass. In each case, we must specify: * Which model feature to monitor * One or more **majority** groups, which are values of that feature tha...
wos_client.monitor_instances.show() #wos_client.monitor_instances.delete(drift_monitor_instance_id,background_mode=False) target = Target( target_type=TargetTypes.SUBSCRIPTION, target_id=subscription_id ) parameters = { "features": [ { "feature": "MSSubClass", "majori...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Drift configuration Note: you can choose to enable/disable (True or False) model or data drift within config
monitor_instances = wos_client.monitor_instances.list().result.monitor_instances for monitor_instance in monitor_instances: monitor_def_id=monitor_instance.entity.monitor_definition_id if monitor_def_id == "drift" and monitor_instance.entity.target.target_id == subscription_id: wos_client.monitor_instan...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Score the model again now that monitoring is configured This next section randomly selects 200 records from the data feed and sends those records to the model for predictions. This is enough to exceed the minimum threshold for records set in the previous section, which allows OpenScale to begin calculating fairness.
!wget https://raw.githubusercontent.com/IBM/watson-openscale-samples/main/IBM%20Cloud/WML/assets/data/house_price/custom_scoring_payloads_50_regression.json with open('custom_scoring_payloads_50_regression.json', 'r') as scoring_file: scoring_data = json.load(scoring_file) import random with open('custom_scoring_p...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Run fairness monitor Kick off a fairness monitor run on current data. The monitor runs hourly, but can be manually initiated using the Python client, the REST API, or the graphical user interface.
run_details = wos_client.monitor_instances.run(monitor_instance_id=fairness_monitor_instance_id, background_mode=False) time.sleep(10) wos_client.monitor_instances.show_metrics(monitor_instance_id=fairness_monitor_instance_id)
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Run drift monitorKick off a drift monitor run on current data. The monitor runs every hour, but can be manually initiated using the Python client, the REST API.
drift_run_details = wos_client.monitor_instances.run(monitor_instance_id=drift_monitor_instance_id, background_mode=False) time.sleep(5) wos_client.monitor_instances.show_metrics(monitor_instance_id=drift_monitor_instance_id)
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Configure Explainability Finally, we provide OpenScale with the training data to enable and configure the explainability features.
target = Target( target_type=TargetTypes.SUBSCRIPTION, target_id=subscription_id ) parameters = { "enabled": True } explainability_details = wos_client.monitor_instances.create( data_mart_id=data_mart_id, background_mode=False, monitor_definition_id=wos_client.monitor_definitions.MONITORS.EXPLAI...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Run explanation for sample record
pl_records_resp = wos_client.data_sets.get_list_of_records(data_set_id=payload_data_set_id, limit=1, offset=0).result scoring_ids = [pl_records_resp["records"][0]["entity"]["values"]["scoring_id"]] print("Running explanations on scoring IDs: {}".format(scoring_ids)) explanation_types = ["lime", "contrastive"] result = ...
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Additional data to help debugging
print('Datamart:', data_mart_id) print('Model:', model_uid) print('Deployment:', deployment_uid)
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
Identify transactions for Explainability Transaction IDs identified by the cells below can be copied and pasted into the Explainability tab of the OpenScale dashboard.
wos_client.data_sets.show_records(payload_data_set_id, limit=5)
_____no_output_____
Apache-2.0
IBM Cloud/WML/notebooks/regression/xgboost_scikit_wrapper/Watson OpenScale and Watson ML Engine Regression.ipynb
arsuryan/watson-openscale-samples
This Notebook uses a Session Event Dataset from E-Commerce Website (https://www.kaggle.com/mkechinov/ecommerce-behavior-data-from-multi-category-store and https://rees46.com/) to build an Outlier Detection based on an Autoencoder.
import mlflow import numpy as np import os import shutil import pandas as pd import tensorflow as tf import tensorflow.keras as keras import tensorflow_hub as hub from itertools import product # enable gpu growth if gpu is available gpu_devices = tf.config.experimental.list_physical_devices('GPU') for device in gpu_de...
INFO:tensorflow:Mixed precision compatibility check (mixed_float16): OK Your GPU will likely run quickly with dtype policy mixed_float16 as it has compute capability of at least 7.0. Your GPU: GeForce RTX 2070 SUPER, compute capability 7.5 numpy 1.19.4 mlflow 1.14.1 tensorflow 2.4.0 tensorflo...
MIT
outlier_detection/training_outlier_detection.ipynb
felix-exel/kfserving-advanced
Setting Registry and Tracking URI for MLflow
# Use this registry uri when mlflow is created by docker container with a mysql db backend #registry_uri = os.path.expandvars('mysql+pymysql://${MYSQL_USER}:${MYSQL_PASSWORD}@localhost:3306/${MYSQL_DATABASE}') # Use this registry uri when mlflow is running locally by the command: # "mlflow server --backend-store-uri s...
_____no_output_____
MIT
outlier_detection/training_outlier_detection.ipynb
felix-exel/kfserving-advanced
The Data is taken from https://www.kaggle.com/mkechinov/ecommerce-behavior-data-from-multi-category-store and https://rees46.com/ Each record/line in the file has the following fields:1. event_time: When did the event happened (UTC)2. event_type: Event type: one of [view, cart, remove_from_cart, purchase] 3. product_i...
# Read first 500.000 Rows for chunk in pd.read_table("2019-Dec.csv", sep=",", header=0, infer_datetime_format=True, low_memory=False, chunksize=500000): # Filter out other event types than 'view' chunk = chunk[chunk['event_type'] == 'view'] # Filter out ...
Mean: 284.7710546866538 Std: 349.46740231584886 Sessions: (61296,) Unique Products: (38515,) Unique category_code: (134,)
MIT
outlier_detection/training_outlier_detection.ipynb
felix-exel/kfserving-advanced
Delete Rows with equal or less than 6 Product Occurrences
count_product_id_mapped = df.groupby('product_id').count() products_to_delete = count_product_id_mapped.loc[count_product_id_mapped['embedding_0'] <= 6].index products_to_delete
_____no_output_____
MIT
outlier_detection/training_outlier_detection.ipynb
felix-exel/kfserving-advanced