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 need a first order system, so convert the second order system $$m \ddot{u} + k u = 0,\quad u(0) = u_0,\quad \dot{u}(0) = \dot{u}_0$$into $$\left\{ \begin{array}{l} \dot u = v\\ \dot v = \ddot u = -\frac{ku}{m}\end{array} \right.$$You need to define a function that computes the right hand side of above equation: | def rhseqn(t, x, xdot):
""" we create rhs equations for the problem"""
xdot[0] = x[1]
xdot[1] = - k/m * x[0] | _____no_output_____ | BSD-3-Clause | ipython_examples/Simple Oscillator.ipynb | tinosulzer/odes |
To solve the ODE you define an ode object, specify the solver to use, here cvode, and pass the right hand side function. You request the solution at specific timepoints by passing an array of times to the solve member. | solver = ode('cvode', rhseqn, old_api=False)
solution = solver.solve([0., 1., 2.], initx)
print('\n t Solution Exact')
print('------------------------------------')
for t, u in zip(solution.values.t, solution.values.y):
print('{0:>4.0f} {1:15.6g} {2:15.6g}'.format(t, u[0],
initx[0]*np.... |
t Solution Exact
------------------------------------
0 1 1
1 -0.370694 -0.370682
2 -0.691508 -0.691484
| BSD-3-Clause | ipython_examples/Simple Oscillator.ipynb | tinosulzer/odes |
You can continue the solver by passing further times. Calling the solve routine reinits the solver, so you can restart at whatever time. To continue from the last computed solution, pass the last obtained time and solution. **Note:** The solver performes better if it can take into account history information, so avoid ... | #Solve over the next hour by continuation
times = np.linspace(0, 3600, 61)
times[0] = solution.values.t[-1]
solution = solver.solve(times, solution.values.y[-1])
if solution.errors.t:
print ('Error: ', solution.message, 'Error at time', solution.errors.t)
print ('Computed Solutions:')
print('\n t Solution ... | Error: Could not reach endpoint Error at time 24.5780834078
Computed Solutions:
t Solution Exact
------------------------------------
2 -0.691508 -0.691484
| BSD-3-Clause | ipython_examples/Simple Oscillator.ipynb | tinosulzer/odes |
The solution fails at a time around 24 seconds. Erros can be due to many things. Here however the reason is simple: we try to make too large jumps in time output. Increasing the allowed steps the solver can take will fix this. This is the **max_steps** option of cvode: | solver = ode('cvode', rhseqn, old_api=False, max_steps=5000)
solution = solver.solve(times, solution.values.y[-1])
if solution.errors.t:
print ('Error: ', solution.message, 'Error at time', solution.errors.t)
print ('Computed Solutions:')
print('\n t Solution Exact')
print('-----------------------... | Computed Solutions:
t Solution Exact
------------------------------------
2 -0.691508 -0.691484
60 0.843074 0.843212
120 0.372884 0.373054
180 -0.235749 -0.235745
240 -0.756553 -0.756932
300 -0.996027 -0.996814
360... | BSD-3-Clause | ipython_examples/Simple Oscillator.ipynb | tinosulzer/odes |
To plot the simple oscillator, we show a (t,x) plot of the solution. Doing this over 60 seconds can be done as follows: | #plot of the oscilator
solver = ode('cvode', rhseqn, old_api=False)
times = np.linspace(0,60,600)
solution = solver.solve(times, initx)
plt.plot(solution.values.t,[x[0] for x in solution.values.y])
plt.xlabel('Time [s]')
plt.ylabel('Position [m]')
plt.show() | _____no_output_____ | BSD-3-Clause | ipython_examples/Simple Oscillator.ipynb | tinosulzer/odes |
You can refine the tolerances from their defaults to obtain more accurate solutions | options1= {'rtol': 1e-6, 'atol': 1e-12, 'max_steps': 50000} # default rtol and atol
options2= {'rtol': 1e-15, 'atol': 1e-25, 'max_steps': 50000}
solver1 = ode('cvode', rhseqn, old_api=False, **options1)
solver2 = ode('cvode', rhseqn, old_api=False, **options2)
solution1 = solver1.solve([0., 1., 60], initx)
solutio... |
t Solution1 Solution2 Exact
-----------------------------------------------------
0 1 1 1
1 -0.37069371 -0.37068197 -0.37068197
60 0.8430298 0.84321153 0.84321153
| BSD-3-Clause | ipython_examples/Simple Oscillator.ipynb | tinosulzer/odes |
Simple Oscillator Example: Stepwise runningWhen using the *solve* method, you solve over a period of time you decided before. In some problems you might want to solve and decide on the output when to stop. Then you use the *step* method. The same example as above using the step method can be solved as follows. You def... | solver = ode('cvode', rhseqn, old_api=False)
time = 0.
solver.init_step(time, initx)
plott = []
plotx = []
while True:
time += 0.1
# fix roundoff error at end
if time > 60: time = 60
solution = solver.step(time)
if solution.errors.t:
print ('Error: ', solution.message, 'Error at time', solut... | _____no_output_____ | BSD-3-Clause | ipython_examples/Simple Oscillator.ipynb | tinosulzer/odes |
The solver interpolates solutions to return the solution at the required output times: | print ('plott length:', len(plott), ', last computation times:', plott[-15:]); | plott length: 600 , last computation times: [58.60000000000056, 58.700000000000564, 58.800000000000566, 58.90000000000057, 59.00000000000057, 59.10000000000057, 59.20000000000057, 59.30000000000057, 59.400000000000574, 59.500000000000576, 59.60000000000058, 59.70000000000058, 59.80000000000058, 59.90000000000058, 60.0]... | BSD-3-Clause | ipython_examples/Simple Oscillator.ipynb | tinosulzer/odes |
Simple Oscillator Example: Internal Solver Stepwise runningWhen using the *solve* method, you solve over a period of time you decided before. With the *step* method you solve by default towards a desired output time after which you can continue solving the problem. For full control, you can also compute problems using... | solver = ode('cvode', rhseqn, old_api=False, one_step_compute=True)
time = 0.
solver.init_step(time, initx)
plott = []
plotx = []
while True:
solution = solver.step(60)
if solution.errors.t:
print ('Error: ', solution.message, 'Error at time', solution.errors.t)
break
#we store output for pl... | _____no_output_____ | BSD-3-Clause | ipython_examples/Simple Oscillator.ipynb | tinosulzer/odes |
By inspection of the returned times you can see how efficient the solver can solve this problem: | print ('plott length:', len(plott), ', last computation times:', plott[-15:]); | plott length: 1328 , last computation times: [59.2297953049153, 59.28543421477497, 59.34107312463465, 59.39671203449432, 59.452350944353995, 59.50798985421367, 59.56362876407334, 59.61926767393302, 59.67490658379269, 59.730545493652365, 59.78618440351204, 59.84182331337171, 59.897462223231386, 59.95310113309106, 60.0]
| BSD-3-Clause | ipython_examples/Simple Oscillator.ipynb | tinosulzer/odes |
Siamese networks with TensorFlow 2.0/KerasIn this example, we'll implement a simple siamese network system, which verifyies whether a pair of MNIST images is of the same class (true) or not (false). _This example is partially based on_ [https://github.com/keras-team/keras/blob/master/examples/mnist_siamese.py](https:/... | import random
import numpy as np
import tensorflow as tf | _____no_output_____ | MIT | Chapter10/siamese.ipynb | arifmudi/Advanced-Deep-Learning-with-Python |
We'll continue with the `create_pairs` function, which creates a training dataset of equal number of true/false pairs of each MNIST class. | def create_pairs(inputs: np.ndarray, labels: np.ndarray):
"""Create equal number of true/false pairs of samples"""
num_classes = 10
digit_indices = [np.where(labels == i)[0] for i in range(num_classes)]
pairs = list()
labels = list()
n = min([len(digit_indices[d]) for d in range(num_classes)])... | _____no_output_____ | MIT | Chapter10/siamese.ipynb | arifmudi/Advanced-Deep-Learning-with-Python |
Next, we'll define the base network of the siamese system: | def create_base_network():
"""The shared encoding part of the siamese network"""
return tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.1),
tf.keras.layers.Dense(128, activation='relu'),
tf.... | _____no_output_____ | MIT | Chapter10/siamese.ipynb | arifmudi/Advanced-Deep-Learning-with-Python |
Next, let's load the regular MNIST training and validation sets and create true/false pairs out of them: | # Load the train and test MNIST datasets
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_train.astype(np.float32)
x_test = x_test.astype(np.float32)
x_train /= 255
x_test /= 255
input_shape = x_train.shape[1:]
# Create true/false training and testing pairs
train_pairs, tr_labels ... | _____no_output_____ | MIT | Chapter10/siamese.ipynb | arifmudi/Advanced-Deep-Learning-with-Python |
Then, we'll build the siamese system, which includes the `base_network`, the 2 siamese paths `encoder_a` and `encoder_b`, the `l1_dist` measure, and the combined `model`: | # Create the siamese network
# Start from the shared layers
base_network = create_base_network()
# Create first half of the siamese system
input_a = tf.keras.layers.Input(shape=input_shape)
# Note how we reuse the base_network in both halfs
encoder_a = base_network(input_a)
# Create the second half of the siamese sy... | _____no_output_____ | MIT | Chapter10/siamese.ipynb | arifmudi/Advanced-Deep-Learning-with-Python |
Finally, we can train the model and check the validation accuracy, which reaches 99.37%: | # Train
model.compile(loss='binary_crossentropy',
optimizer=tf.keras.optimizers.Adam(),
metrics=['accuracy'])
model.fit([train_pairs[:, 0], train_pairs[:, 1]], tr_labels,
batch_size=128,
epochs=20,
validation_data=([test_pairs[:, 0], test_pairs[:, 1]], test_lab... | Train on 108400 samples, validate on 17820 samples
Epoch 1/20
108400/108400 [==============================] - 5s 44us/sample - loss: 0.3328 - accuracy: 0.8540 - val_loss: 0.2435 - val_accuracy: 0.9184
Epoch 2/20
108400/108400 [==============================] - 4s 37us/sample - loss: 0.1612 - accuracy: 0.9409 - val_los... | MIT | Chapter10/siamese.ipynb | arifmudi/Advanced-Deep-Learning-with-Python |
IntroductionJuan Camilo Henao LondonoExercise from [Hacker rank](https://www.hackerrank.com/challenges/write-a-function/problem) Write a functionWe add a Leap Day on February 29, almost every four years. The leap day is an extra, or intercalary day and we add it to the shortest month of the year, February.In the Greg... | def is_leap(year):
if (year%400 == 0 and year%100 == 0):
return True
elif (year%4 == 0 and year%100 != 0):
return True
return False
year = int(input())
print(is_leap(year)) | 2019
False
| MIT | 01_introduction/06_write_a_function.ipynb | juanhenao21/hack_rank |
Best implementation in the discussion From the discussion:> you should know that doing something like the setup for this challenge inclines you to do is a bad practice. Never do the following:```Pythondef f(): if condition: return True else: return False``` | def is_leap(year):
return year % 4 == 0 and (year % 400 == 0 or year % 100 != 0)
year = int(input())
print(is_leap(year)) | 2019
False
| MIT | 01_introduction/06_write_a_function.ipynb | juanhenao21/hack_rank |
BBoxerwGradCAM This class forms boundary boxes (rectangle and polygon) using GradCAM outputs for a given image.The purpose of this class is to develop Rectangle and Polygon coordinates that define an object based on an image classification model. The 'automatic' creation of these coordinates, which are often included ... | # Imports for loading learner and the GradCAM class
from fastai import *
from fastai.vision import *
from fastai.callbacks.hooks import *
import scipy.ndimage | _____no_output_____ | MIT | BBOX_GRADCAM_demo_example.ipynb | zalkikar/BBOX_GradCAM |
The following cell contains the widely used GradCAM class for pretrained image classification models (unedited). | #@title GradCAM Class
class GradCam():
@classmethod
def from_interp(cls,learn,interp,img_idx,ds_type=DatasetType.Valid,include_label=False):
# produce heatmap and xb_grad for pred label (and actual label if include_label is True)
if ds_type == DatasetType.Valid:
ds = interp.data.val... | _____no_output_____ | MIT | BBOX_GRADCAM_demo_example.ipynb | zalkikar/BBOX_GradCAM |
I connect to google drive (this notebook was made on google colab for GPU usage) and load my pretrained learner. | from google.colab import drive
drive.mount('/content/drive')
base_dir = '/content/drive/My Drive/fellowshipai-data/final_3_class_data_train_test_split'
def get_data(sz): # This function returns an ImageDataBunch with a given image size
return ImageDataBunch.from_folder(base_dir+'/', train='train', valid='valid', # 0... | /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old... | MIT | BBOX_GRADCAM_demo_example.ipynb | zalkikar/BBOX_GradCAM |
My pretrained learner correctly classified the image as raw with probability 0.996.Note that images with very low noise and accurate feature importances (as with the example image) are The learner is focusing on the steak in center view (heatmap pixels indicate feature importance). | from BBOXES_from_GRADCAM import BBoxerwGradCAM # load class from .py file
image_resizing_scale = [400,300]
bbox_scaling = [1,1,1,1]
bbox = BBoxerwGradCAM(learn,
gcam_heatmap,
example_image,
image_resizing_scale,
bbox_scaling)
for ... | _____no_output_____ | MIT | BBOX_GRADCAM_demo_example.ipynb | zalkikar/BBOX_GradCAM |
Decision Tree ref: http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html | import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.datasets import load_breast_cancer
from sklearn.tree import DecisionTreeClassifier
# Load data
cancer = load_breast_cancer()
print(cancer.feature_names)
print... | ['mean radius' 'mean texture' 'mean perimeter' 'mean area'
'mean smoothness' 'mean compactness' 'mean concavity'
'mean concave points' 'mean symmetry' 'mean fractal dimension'
'radius error' 'texture error' 'perimeter error' 'area error'
'smoothness error' 'compactness error' 'concavity error'
'concave points erro... | MIT | mod09.ipynb | theabc50111/machine_learning_tibame |
Random Forest ref: http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html | from sklearn.ensemble import RandomForestClassifier
# Load data
cancer = load_breast_cancer()
x = cancer.data
y = cancer.target
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
model = RandomForestClassifier(max_depth=6, n_estimators=10)
model.fit(x_train, y_train)
y_pred = model.predict(x... | number of correct sample: 112
accuracy: 0.9824561403508771
| MIT | mod09.ipynb | theabc50111/machine_learning_tibame |
Importing libraries and methods from thermograms, ml_training and ultilites modules | import numpy as np
print('Project MLaDECO')
print('Author: Viswambhar Yasa')
print('Software version: 0.1')
from sklearn.preprocessing import MinMaxScaler, StandardScaler
import tensorflow as tf
from tensorflow.keras import models
from thermograms.Utilities import Utilities
from ml_training.dataset_generation.fourier_... | Project MLaDECO
Author: Viswambhar Yasa
Software version: 0.1
| MIT | ml_training/dataset_generation/masks/segmentation_mask_metal.ipynb | viswambhar-yasa/LaDECO |
Importing dataset for training | root_path = r'utilites/datasets'
data_file_name = r'metal_data.hdf5'
thermal_class = Utilities()
thermal_data,experiment_list=thermal_class.open_file(root_path, data_file_name,True)
experiment_name=r'2021-12-15-Materialstudie_Metallproben-ML3-laserbehandelte_Probe-1000W-10s'
experimental_data=thermal_data[experiment_na... | Experiments in the file
1 : 2021-12-15-Materialstudie_Metallproben-ML1-laserbehandelte_Probe-1000W-10s
2 : 2021-12-15-Materialstudie_Metallproben-ML2-laserbehandelte_Probe-1000W-10s
3 : 2021-12-15-Materialstudie_Metallproben-ML3-laserbehandelte_Probe-1000W-10s
A total of 3 experiments are loaded in file
| MIT | ml_training/dataset_generation/masks/segmentation_mask_metal.ipynb | viswambhar-yasa/LaDECO |
Checking the shape and file format of the thermographic experiment dataset | experimental_data | _____no_output_____ | MIT | ml_training/dataset_generation/masks/segmentation_mask_metal.ipynb | viswambhar-yasa/LaDECO |
Identifying the reflection phase index | input_data, reflection_st_index, reflection_end_index = fourier_transformation(experimental_data,
scaling_type='normalization', index=1)
from PIL import Image | _____no_output_____ | MIT | ml_training/dataset_generation/masks/segmentation_mask_metal.ipynb | viswambhar-yasa/LaDECO |
Performing data normalization to improve the learning ability of machine learning model by scaling down the data between a smaller range | from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.model_selection import train_test_split
exp_data=np.array(experimental_data)
standardizing = StandardScaler()
std_output_data = standardizing.fit_transform(
exp_data.reshape(exp_data.shape[0], -1)).reshape(exp_data.shape)
norma... | _____no_output_____ | MIT | ml_training/dataset_generation/masks/segmentation_mask_metal.ipynb | viswambhar-yasa/LaDECO |
Plotting thermograms after gaussian normalization and min max scaling operation | from mpl_toolkits.axes_grid1 import make_axes_locatable
fig = plt.figure(figsize=(10,5))
ax1 = fig.add_subplot(121)
im1 = ax1.imshow(std_output_data[:,:,400].astype(np.float32), cmap='RdYlBu_r', interpolation='None')
ax1.set_title('Gaussian distribution scaling')
divider = make_axes_locatable(ax1)
cax = divider.append... | _____no_output_____ | MIT | ml_training/dataset_generation/masks/segmentation_mask_metal.ipynb | viswambhar-yasa/LaDECO |
Extracting information from gray scale image and saving it in png format | from PIL import Image
from keras.preprocessing.image import array_to_img,img_to_array
data=experimental_data
plt.figure()
plt.imshow(d[:,:,500],cmap='RdYlBu_r')
#plt.imshow(std_output_data[:,:,250].astype(np.float64),cmap='gray')
plt.savefig("Documents/temp/metal_output.png")
plt.axis('off')
img=plt.imread('Documents/... | _____no_output_____ | MIT | ml_training/dataset_generation/masks/segmentation_mask_metal.ipynb | viswambhar-yasa/LaDECO |
Performing principal companant analysis to features by filtering intensity | EOFs=principal_componant_analysis(experimental_data)
img1 = Image.fromarray(EOFs[:,:,0].astype(np.int8))
#img2 = Image.fromarray(EOFs[:,:,0].astype(np.float32))
plt.imshow(np.squeeze(EOFs),cmap='YlOrRd_r')
plt.colorbar()
plt.savefig("Documents/temp/metal_PCA.png",dpi=600,bbox_inches='tight',transparent=True)
mask=np.ze... | _____no_output_____ | MIT | ml_training/dataset_generation/masks/segmentation_mask_metal.ipynb | viswambhar-yasa/LaDECO |
Final mask of the dataset | plt.imshow(mask)
import cv2
img1 = cv2.imread('Documents/temp/metal_mask1.png',0)
print(img1.shape) | (256, 256)
| MIT | ml_training/dataset_generation/masks/segmentation_mask_metal.ipynb | viswambhar-yasa/LaDECO |
converting the image format data to a numpy array format and scaling it between integer values based on number of features | img1[img1==255]=1
plt.imshow(img1,cmap='binary_r')
plt.colorbar() | _____no_output_____ | MIT | ml_training/dataset_generation/masks/segmentation_mask_metal.ipynb | viswambhar-yasa/LaDECO |
Saving the segmentation mask | name='ml_training/dataset_generation/annots/'+experiment_name
np.save(name,img1)
ar=np.load(name+'.npy')
plt.imshow(ar,cmap='gray')
plt.colorbar() | _____no_output_____ | MIT | ml_training/dataset_generation/masks/segmentation_mask_metal.ipynb | viswambhar-yasa/LaDECO |
Hierarchical Clustering **Hierarchical clustering** refers to a class of clustering methods that seek to build a **hierarchy** of clusters, in which some clusters contain others. In this assignment, we will explore a top-down approach, recursively bipartitioning the data using k-means. **Note to Amazon EC2 users**: To... | from __future__ import print_function # to conform python 2.x print to python 3.x
import turicreate
import matplotlib.pyplot as plt
import numpy as np
import sys
import os
import time
from scipy.sparse import csr_matrix
from sklearn.cluster import KMeans
from sklearn.metrics import pairwise_distances
%matplotlib inline | _____no_output_____ | MIT | 4-ml-clustering-and-retrieval/Week_6-assignment.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
Load the Wikipedia dataset | wiki = turicreate.SFrame('people_wiki.sframe/') | _____no_output_____ | MIT | 4-ml-clustering-and-retrieval/Week_6-assignment.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
As we did in previous assignments, let's extract the TF-IDF features: | wiki['tf_idf'] = turicreate.text_analytics.tf_idf(wiki['text']) | _____no_output_____ | MIT | 4-ml-clustering-and-retrieval/Week_6-assignment.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
To run k-means on this dataset, we should convert the data matrix into a sparse matrix. | from em_utilities import sframe_to_scipy # converter
# This will take about a minute or two.
wiki = wiki.add_row_number()
tf_idf, map_word_to_index = sframe_to_scipy(wiki, 'tf_idf') | _____no_output_____ | MIT | 4-ml-clustering-and-retrieval/Week_6-assignment.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
To be consistent with the k-means assignment, let's normalize all vectors to have unit norm. | from sklearn.preprocessing import normalize
tf_idf = normalize(tf_idf) | _____no_output_____ | MIT | 4-ml-clustering-and-retrieval/Week_6-assignment.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
Bipartition the Wikipedia dataset using k-means Recall our workflow for clustering text data with k-means:1. Load the dataframe containing a dataset, such as the Wikipedia text dataset.2. Extract the data matrix from the dataframe.3. Run k-means on the data matrix with some value of k.4. Visualize the clustering resul... | def bipartition(cluster, maxiter=400, num_runs=4, seed=None):
'''cluster: should be a dictionary containing the following keys
* dataframe: original dataframe
* matrix: same data, in matrix format
* centroid: centroid for this particular cluster'''
data_m... | _____no_output_____ | MIT | 4-ml-clustering-and-retrieval/Week_6-assignment.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
The following cell performs bipartitioning of the Wikipedia dataset. Allow 2+ minutes to finish.Note. For the purpose of the assignment, we set an explicit seed (`seed=1`) to produce identical outputs for every run. In pratical applications, you might want to use different random seeds for all runs. | %%time
wiki_data = {'matrix': tf_idf, 'dataframe': wiki} # no 'centroid' for the root cluster
left_child, right_child = bipartition(wiki_data, maxiter=100, num_runs=1, seed=0) | /home/offbeat/Environments/turicreate/lib/python3.7/site-packages/sklearn/cluster/_kmeans.py:974: FutureWarning: 'n_jobs' was deprecated in version 0.23 and will be removed in 0.25.
" removed in 0.25.", FutureWarning)
| MIT | 4-ml-clustering-and-retrieval/Week_6-assignment.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
Let's examine the contents of one of the two clusters, which we call the `left_child`, referring to the tree visualization above. | left_child | _____no_output_____ | MIT | 4-ml-clustering-and-retrieval/Week_6-assignment.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
And here is the content of the other cluster we named `right_child`. | right_child | _____no_output_____ | MIT | 4-ml-clustering-and-retrieval/Week_6-assignment.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
Visualize the bipartition We provide you with a modified version of the visualization function from the k-means assignment. For each cluster, we print the top 5 words with highest TF-IDF weights in the centroid and display excerpts for the 8 nearest neighbors of the centroid. | def display_single_tf_idf_cluster(cluster, map_index_to_word):
'''map_index_to_word: SFrame specifying the mapping betweeen words and column indices'''
wiki_subset = cluster['dataframe']
tf_idf_subset = cluster['matrix']
centroid = cluster['centroid']
# Print top 5 words with larges... | _____no_output_____ | MIT | 4-ml-clustering-and-retrieval/Week_6-assignment.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
Let's visualize the two child clusters: | display_single_tf_idf_cluster(left_child, map_word_to_index)
display_single_tf_idf_cluster(right_child, map_word_to_index) | 113949:0.040
113949:0.036
113949:0.029
113949:0.029
113949:0.028
* Todd Williams 0.95468
todd michael williams born february 13 1971 in syracuse new york is a former major league
baseball relief pitcher he attended east syracuseminoa high school
* Gord Sherven ... | MIT | 4-ml-clustering-and-retrieval/Week_6-assignment.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
The right cluster consists of athletes and artists (singers and actors/actresses), whereas the left cluster consists of non-athletes and non-artists. So far, we have a single-level hierarchy consisting of two clusters, as follows: ``` Wikipedia ... | non_athletes_artists = left_child
athletes_artists = right_child | _____no_output_____ | MIT | 4-ml-clustering-and-retrieval/Week_6-assignment.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
Using the bipartition function, we produce two child clusters of the athlete cluster: | # Bipartition the cluster of athletes and artists
left_child_athletes_artists, right_child_athletes_artists = bipartition(athletes_artists, maxiter=100, num_runs=6, seed=1) | /home/offbeat/Environments/turicreate/lib/python3.7/site-packages/sklearn/cluster/_kmeans.py:974: FutureWarning: 'n_jobs' was deprecated in version 0.23 and will be removed in 0.25.
" removed in 0.25.", FutureWarning)
| MIT | 4-ml-clustering-and-retrieval/Week_6-assignment.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
The left child cluster mainly consists of athletes: | display_single_tf_idf_cluster(left_child_athletes_artists, map_word_to_index) | 113949:0.054
113949:0.043
113949:0.038
113949:0.035
113949:0.030
* Tony Smith (footballer, born 1957) 0.94677
anthony tony smith born 20 february 1957 is a former footballer who played as a central de
fender in the football league in the 1970s and
* Justin Knoedler ... | MIT | 4-ml-clustering-and-retrieval/Week_6-assignment.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
On the other hand, the right child cluster consists mainly of artists (singers and actors/actresses): | display_single_tf_idf_cluster(right_child_athletes_artists, map_word_to_index) | 113949:0.045
113949:0.043
113949:0.035
113949:0.031
113949:0.031
* Alessandra Aguilar 0.93880
alessandra aguilar born 1 july 1978 in lugo is a spanish longdistance runner who specialis
es in marathon running she represented her country in the event
* Heather Samuel ... | MIT | 4-ml-clustering-and-retrieval/Week_6-assignment.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
Our hierarchy of clusters now looks like this:``` Wikipedia + | +--------------------------+--------------------+ | ... | athletes = left_child_athletes_artists
artists = right_child_athletes_artists | _____no_output_____ | MIT | 4-ml-clustering-and-retrieval/Week_6-assignment.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
Cluster of athletes In answering the following quiz question, take a look at the topics represented in the top documents (those closest to the centroid), as well as the list of words with highest TF-IDF weights.Let us bipartition the cluster of athletes. | left_child_athletes, right_child_athletes = bipartition(athletes, maxiter=100, num_runs=6, seed=1)
display_single_tf_idf_cluster(left_child_athletes, map_word_to_index)
display_single_tf_idf_cluster(right_child_athletes, map_word_to_index) | 113949:0.110
113949:0.102
113949:0.051
113949:0.046
113949:0.045
* Steve Springer 0.89370
steven michael springer born february 11 1961 is an american former professional baseball
player who appeared in major league baseball as a third baseman and
* Dave Ford ... | MIT | 4-ml-clustering-and-retrieval/Week_6-assignment.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
**Quiz Question**. Which diagram best describes the hierarchy right after splitting the `athletes` cluster? Refer to the quiz form for the diagrams. **Caution**. The granularity criteria is an imperfect heuristic and must be taken with a grain of salt. It takes a lot of manual intervention to obtain a good hierarchy of... | %%time
# Bipartition the cluster of non-athletes
left_child_non_athletes_artists, right_child_non_athletes_artists = bipartition(non_athletes_artists, maxiter=100, num_runs=3, seed=1)
display_single_tf_idf_cluster(left_child_non_athletes_artists, map_word_to_index)
display_single_tf_idf_cluster(right_child_non_athlete... | 113949:0.039
113949:0.030
113949:0.023
113949:0.021
113949:0.015
* Madonna (entertainer) 0.96092
madonna louise ciccone tkoni born august 16 1958 is an american singer songwriter actress
and businesswoman she achieved popularity by pushing the boundaries of lyrical
* Janet Jackson ... | MIT | 4-ml-clustering-and-retrieval/Week_6-assignment.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
The clusters are not as clear, but the left cluster has a tendency to show important female figures, and the right one to show politicians and government officials.Let's divide them further. | female_figures = left_child_non_athletes_artists
politicians_etc = right_child_non_athletes_artists
politicians_etc = left_child_non_athletes_artists
female_figures = right_child_non_athletes_artists | _____no_output_____ | MIT | 4-ml-clustering-and-retrieval/Week_6-assignment.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
**Quiz Question**. Let us bipartition the clusters `female_figures` and `politicians`. Which diagram best describes the resulting hierarchy of clusters for the non-athletes? Refer to the quiz for the diagrams.**Note**. Use `maxiter=100, num_runs=6, seed=1` for consistency of output. | left_female_figures, right_female_figures = bipartition(female_figures, maxiter=100, num_runs=6, seed=1)
left_politicians_etc, right_politicians_etc = bipartition(politicians_etc, maxiter=100, num_runs=6, seed=1)
display_single_tf_idf_cluster(left_female_figures, map_word_to_index)
display_single_tf_idf_cluster(right_f... | 113949:0.027
113949:0.023
113949:0.017
113949:0.016
113949:0.015
* Julian Knowles 0.96904
julian knowles is an australian composer and performer specialising in new and emerging te
chnologies his creative work spans the fields of composition for theatre dance
* Peter Combe ... | MIT | 4-ml-clustering-and-retrieval/Week_6-assignment.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
콜모고로프의 공리 1) 모든 사건에 대해 확률은 실수이고 0 또는 양수이다. - $P(A) \geq 0$ 2) 표본공간(전체집합) 이라는 사건(부분집합)에대 대한 확률은 1이다. - $P(\Omega) = 1$ 3) 공통원소가 없는 두 사건의 합집합의 확률은 사건별 확률의 합이다 - $A\cap B = \emptyset \rightarrow P(A\cup B) = P(A) + P(B)$ ----- 확률 성질 요약 1) 공집합의 확률 - $P(0) = \emptyset$ 2) 여집합의 확률 - $P(A\complement... | from pgmpy.factors.discrete import JointProbabilityDistribution as JPD
px = JPD(['X'], [2], np.array([12, 8]) / 20)
print(px)
py = JPD(['Y'], [2], np.array([10, 10])/20)
print(py)
pxy = JPD(['X', 'Y'], [2, 2], np.array([3, 9, 7, 1])/20)
print(pxy)
pxy2 = JPD(['X', 'Y'], [2, 2], np.array([6, 6, 4, 4, ])/20)
print(pxy2) | +------+------+----------+
| X | Y | P(X,Y) |
+======+======+==========+
| X(0) | Y(0) | 0.3000 |
+------+------+----------+
| X(0) | Y(1) | 0.3000 |
+------+------+----------+
| X(1) | Y(0) | 0.2000 |
+------+------+----------+
| X(1) | Y(1) | 0.2000 |
+------+------+----------+
| MIT | MATH/17_joint_probability_conditional_probability.ipynb | CATERINA-SEUL/Data-Science-School |
---- marginal_distribution() - 인수로 받은 확률변수에 대한 주변확률분포를 구함 - $X$의 주변확률을 구해라 ---- - 결합확률로 부터 주변확률 $P(A),P(A^\complement)$ 를 계산 | pmx = pxy.marginal_distribution(['X'], inplace=False)
print(pmx) | +------+--------+
| X | P(X) |
+======+========+
| X(0) | 0.6000 |
+------+--------+
| X(1) | 0.4000 |
+------+--------+
| MIT | MATH/17_joint_probability_conditional_probability.ipynb | CATERINA-SEUL/Data-Science-School |
marginalize() - 인수로 받은 확률변수를 주변화(marginalize)하여 나머지 확률 변수에 대한 주변확률분포를 구한다. - $X$를 구하기 위해서 $Y$를 없애라! (== 배타적인 사건으로 써라)---- - 결합확률로부터 $P(A) , P(A^\complement)$ 를 계산 | pmx = pxy.marginalize(['Y'], inplace=False)
print(pmx) | +------+--------+
| X | P(X) |
+======+========+
| X(0) | 0.6000 |
+------+--------+
| X(1) | 0.4000 |
+------+--------+
| MIT | MATH/17_joint_probability_conditional_probability.ipynb | CATERINA-SEUL/Data-Science-School |
- 결합확률로부터 $P(B),P(B^\complement)$를 계산 | py = pxy.marginal_distribution(['Y'], inplace=False)
print(pmy)
py = pxy.marginalize(['X'], inplace=False)
print(py) | +------+--------+
| Y | P(Y) |
+======+========+
| Y(0) | 0.5000 |
+------+--------+
| Y(1) | 0.5000 |
+------+--------+
| MIT | MATH/17_joint_probability_conditional_probability.ipynb | CATERINA-SEUL/Data-Science-School |
conditional_distribution() - 어떤 확률변수가 어떤 사건이 되는 조건에 대해 조건부확률값을 계산 --- - 결합확률로부터 조건부확률 $P(B|A),P(B^\complement|A)$ 를 계산 | py_on_x0 = pxy.conditional_distribution([('X', 0)], inplace=False)
print(py_on_x0) | +------+--------+
| Y | P(Y) |
+======+========+
| Y(0) | 0.2500 |
+------+--------+
| Y(1) | 0.7500 |
+------+--------+
| MIT | MATH/17_joint_probability_conditional_probability.ipynb | CATERINA-SEUL/Data-Science-School |
- 결합확률로부터 조건부확률 $P(B|A^\complement),P(B^\complement|A^\complement)$ 를 계산 | py_on_x1 = pxy.conditional_distribution([('X', 1)], inplace=False)
print(py_on_x1) | +------+--------+
| Y | P(Y) |
+======+========+
| Y(0) | 0.8750 |
+------+--------+
| Y(1) | 0.1250 |
+------+--------+
| MIT | MATH/17_joint_probability_conditional_probability.ipynb | CATERINA-SEUL/Data-Science-School |
- 결합확률로부터 조건부확률 $P(A|B),P(A^\complement|B)$ 를 계산 | px_on_y0 = pxy.conditional_distribution([('Y', 0)], inplace=False)
print(px_on_y0)
px_on_y1 = pxy.conditional_distribution([('Y', 1)], inplace=False)
print(px_on_y1) | +------+--------+
| X | P(X) |
+======+========+
| X(0) | 0.9000 |
+------+--------+
| X(1) | 0.1000 |
+------+--------+
| MIT | MATH/17_joint_probability_conditional_probability.ipynb | CATERINA-SEUL/Data-Science-School |
check_independence() - 두 확률변수 간의 독립 확인 가능. * 독립 : $P(A,B) = P(A)P(B)$ - 독립인 경우에는 결합확률을 다 구할 필요가 없다 . | pxy.check_independence(['X'], ['Y']) | _____no_output_____ | MIT | MATH/17_joint_probability_conditional_probability.ipynb | CATERINA-SEUL/Data-Science-School |
- JointProbabilityDistribution 객체끼리 곱하면 두 분포가 독립이라는 가정하에 결합확률을 구함 | # 독립이 아님
print(px*py)
print(pxy)
pxy2.check_independence(['X'], ['Y']) | _____no_output_____ | MIT | MATH/17_joint_probability_conditional_probability.ipynb | CATERINA-SEUL/Data-Science-School |
This notebook preprocesses subject 8 for Question 1: Can we predict if the subject will select Gamble or Safebet *before* the button press time? Behavior data | ## Explore behavior data using pandas
import pandas as pd
beh_dir = '../data/decision-making/data/data_behav'
# os.listdir(beh_dir)
# S08
beh8_df = pd.read_csv(os.path.join(beh_dir,'gamble.data.s08.csv')) | _____no_output_____ | MIT | Misc/.ipynb_checkpoints/preprocess-checkpoint.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Choice.class will be our outcome variable | beh8_df.groupby('choice.class').nunique() | _____no_output_____ | MIT | Misc/.ipynb_checkpoints/preprocess-checkpoint.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Great, we have 100 trials per choice: Gamble vs Safebet. | # This will be the outcome variable: beh8_df['choice.class']
y8 = beh8_df['choice.class'].values | _____no_output_____ | MIT | Misc/.ipynb_checkpoints/preprocess-checkpoint.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Save y-data | mkdir ../data/decision-making/data/data_preproc
np.save('../data/decision-making/data/data_preproc/y8',y8)
ls ../data/decision-making/data/data_preproc | y8.npy
| MIT | Misc/.ipynb_checkpoints/preprocess-checkpoint.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Neural data | sfreq = 1000
neur_dir = '../data/decision-making/data/data_ephys'
# os.listdir(neur_dir)
from scipy.io import loadmat
neur8 = loadmat(os.path.join(neur_dir, 's08_ofc_hg_events.mat'))
neur8['buttonpress_events_hg'].shape
%matplotlib inline
import matplotlib.pyplot as plt
# first electrode
plt.plot(neur8['buttonpres... | _____no_output_____ | MIT | Misc/.ipynb_checkpoints/preprocess-checkpoint.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Convert format of data to work for "decoding over time" For decoding over time the data X is the epochs data of shape n_epochs x n_channels x n_times. As the last dimension of X is the time an estimator will be fit on every time instant. | neur8['buttonpress_events_hg'].shape | _____no_output_____ | MIT | Misc/.ipynb_checkpoints/preprocess-checkpoint.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Notice that current shape is n_epochs (200) x n_times (3000) x n_channels (10) | X8 = np.swapaxes(neur8['buttonpress_events_hg'],1,2)
X8.shape | _____no_output_____ | MIT | Misc/.ipynb_checkpoints/preprocess-checkpoint.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Hooray, now it's n_epochs x n_channels x n_times. Save out X8 | np.save('../data/decision-making/data/data_preproc/X8',X8) | _____no_output_____ | MIT | Misc/.ipynb_checkpoints/preprocess-checkpoint.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
EOPF S2 MSI L1 A/B Products Data Structure Proposal | from IPython.display import IFrame
from utils import display
from EOProductDataStructure import EOProductBuilder, EOVariableBuilder, EOGroupBuilder
import yaml | _____no_output_____ | Apache-2.0 | eopf-notebooks/eopf_product_data_structure/EOPF_S2_MSI_L1AB.ipynb | CSC-DPR/notebooks |
Display function | def set_variables(yaml_group, eopf_group):
variables = yaml_group['variables']
for var in variables:
variable = EOVariableBuilder(var, default_attrs=True)
try:
variable.dtype = variables[var].split('->')[1]
except:
variable.dtype = "string"
pass
... | _____no_output_____ | Apache-2.0 | eopf-notebooks/eopf_product_data_structure/EOPF_S2_MSI_L1AB.ipynb | CSC-DPR/notebooks |
1. Read S1 MSI Product | path_product="data/s2_msi_l1ab.yaml"
product = None
with open(path_product, "r") as stream:
try:
product = yaml.safe_load(stream)['product']
except yaml.YAMLError as exc:
print(exc)
s2_msi = EOProductBuilder("S2_MSI_L1AB__", coords=EOGroupBuilder('coords'))
for key, values in product... | _____no_output_____ | Apache-2.0 | eopf-notebooks/eopf_product_data_structure/EOPF_S2_MSI_L1AB.ipynb | CSC-DPR/notebooks |
Object Detection with SSD Here we demostrate detection on example images using SSD with PyTorch | import os
import sys
module_path = os.path.abspath(os.path.join('..'))
if module_path not in sys.path:
sys.path.append(module_path)
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
import numpy as np
import cv2
if torch.cuda.is_available():
torch.set_d... | _____no_output_____ | MIT | demo/demo.ipynb | joshnn/SSD.Pytorch |
Build SSD300 in Test Phase1. Build the architecture, specifyingsize of the input image (300), and number of object classes to score (21 for VOC dataset)2. Next we load pretrained weights on the VOC0712 trainval dataset | net = build_ssd('test', 300, 21) # initialize SSD
net.load_weights('../weights/ssd300_VOC_28000.pth') | _____no_output_____ | MIT | demo/demo.ipynb | joshnn/SSD.Pytorch |
Load Image Here we just load a sample image from the VOC07 dataset | # image = cv2.imread('./data/example.jpg', cv2.IMREAD_COLOR) # uncomment if dataset not downloaded
%matplotlib inline
from matplotlib import pyplot as plt
from data import VOCDetection, VOC_ROOT, VOCAnnotationTransform
# here we specify year (07 or 12) and dataset ('test', 'val', 'train')
testset = VOCDetection(VOC_R... | _____no_output_____ | MIT | demo/demo.ipynb | joshnn/SSD.Pytorch |
Pre-process the input. Using the torchvision package, we can create a Compose of multiple built-in transorm ops to apply For SSD, at test time we use a custom BaseTransform callable toresize our image to 300x300, subtract the dataset's mean rgb values, and swap the color channels for input to SSD300. | x = cv2.resize(image, (300, 300)).astype(np.float32)
x -= (104.0, 117.0, 123.0)
x = x.astype(np.float32)
x = x[:, :, ::-1].copy()
plt.imshow(x)
x = torch.from_numpy(x).permute(2, 0, 1) | _____no_output_____ | MIT | demo/demo.ipynb | joshnn/SSD.Pytorch |
SSD Forward Pass Now just wrap the image in a Variable so it is recognized by PyTorch autograd | xx = Variable(x.unsqueeze(0)) # wrap tensor in Variable
if torch.cuda.is_available():
xx = xx.cuda()
y = net(xx) | _____no_output_____ | MIT | demo/demo.ipynb | joshnn/SSD.Pytorch |
Parse the Detections and View ResultsFilter outputs with confidence scores lower than a threshold Here we choose 60% | from data import VOC_CLASSES as labels
top_k=10
plt.figure(figsize=(10,10))
colors = plt.cm.hsv(np.linspace(0, 1, 21)).tolist()
plt.imshow(rgb_image) # plot the image for matplotlib
currentAxis = plt.gca()
detections = y.data
# scale each detection back up to the image
scale = torch.Tensor(rgb_image.shape[1::-1]).re... | _____no_output_____ | MIT | demo/demo.ipynb | joshnn/SSD.Pytorch |
Data Attribute Recommendation - TechED 2020 INT260Getting started with the Python SDK for the Data Attribute Recommendation service. Business ScenarioWe will consider a business scenario involving product master data. The creation and maintenance of this product master data requires the careful manual selection of th... | ! pip install data-attribute-recommendation-sdk | _____no_output_____ | Apache-2.0 | exercises/ex1-DAR/teched2020-INT260_Data_Attribute_Recommendation.ipynb | SAP-samples/teched2020-INT260 |
*Note: If you are not using a Jupyter notebook, but instead a regular Python development environment, we recommend using a Python virtual environment to set up your development environment. Please see [the dedicated tutorial to learn how to install the SDK inside a Python virtual environment](https://developers.sap.com... | # First, set up logging so we can see the actions performed by the SDK behind the scenes
import logging
import sys
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
from pprint import pprint # for nicer output formatting
import json
import os
if not os.path.exists("key.json"):
msg = "key.json is not fou... | _____no_output_____ | Apache-2.0 | exercises/ex1-DAR/teched2020-INT260_Data_Attribute_Recommendation.ipynb | SAP-samples/teched2020-INT260 |
Summary Exercise 01.1In exercise 01.1, we have covered the following topics:* How to install the Python SDK for Data Attribute Recommendation* How to obtain a service key for the Data Attribute Recommendation service Exercise 01.2*Back to [table of contents](Table-of-Contents)**To perform this exercise, you need to e... | ! wget -O bestBuy.csv "https://raw.githubusercontent.com/SAP-samples/data-attribute-recommendation-postman-tutorial-sample/master/Tutorial_Example_Dataset.csv"
# If you receive a "command not found" error (i.e. on Windows), try curl instead of wget:
# ! curl -o bestBuy.csv "https://raw.githubusercontent.com/SAP-samples... | _____no_output_____ | Apache-2.0 | exercises/ex1-DAR/teched2020-INT260_Data_Attribute_Recommendation.ipynb | SAP-samples/teched2020-INT260 |
Let's inspect the data: | # if you are experiencing an import error here, run the following in a new cell:
# ! pip install pandas
import pandas as pd
df = pd.read_csv("bestBuy.csv")
df.head(5)
print()
print(f"Data has {df.shape[0]} rows and {df.shape[1]} columns.") | _____no_output_____ | Apache-2.0 | exercises/ex1-DAR/teched2020-INT260_Data_Attribute_Recommendation.ipynb | SAP-samples/teched2020-INT260 |
The CSV contains the several products. For each product, the description, the manufacturer and the price are given. Additionally, three levels of the products hierarchy are given.The first product, a set of AAA batteries, is located in the following place in the product hierarchy:```level1_category: Connected H... | from sap.aibus.dar.client.data_manager_client import DataManagerClient
dataset_schema = {
"features": [
{"label": "manufacturer", "type": "CATEGORY"},
{"label": "description", "type": "TEXT"},
{"label": "price", "type": "NUMBER"}
],
"labels": [
{"label": "level1_category", "... | _____no_output_____ | Apache-2.0 | exercises/ex1-DAR/teched2020-INT260_Data_Attribute_Recommendation.ipynb | SAP-samples/teched2020-INT260 |
The API responds with the newly created DatasetSchema resource. The service assigned an ID to the schema. We save this ID in a variable, as we will need it when we upload the data. Uploading the Data to the service The [`DataManagerClient`](https://data-attribute-recommendation-python-sdk.readthedocs.io/en/latest/api.... | dataset_resource = data_manager.create_dataset("my-bestbuy-dataset", dataset_schema_id)
dataset_id = dataset_resource["id"]
print()
print("Dataset created:")
pprint(dataset_resource)
print()
print(f"Dataset ID: {dataset_id}")
# Compress file first for a faster upload
! gzip -9 -c bestBuy.csv > bestBuy.csv.gz | _____no_output_____ | Apache-2.0 | exercises/ex1-DAR/teched2020-INT260_Data_Attribute_Recommendation.ipynb | SAP-samples/teched2020-INT260 |
Note that the data upload can take a few minutes. Please do not restart the process while the cell is still running. | # Open in binary mode.
with open('bestBuy.csv.gz', 'rb') as file_handle:
dataset_resource = data_manager.upload_data_to_dataset(dataset_id, file_handle)
print()
print("Dataset after data upload:")
print()
pprint(dataset_resource) | _____no_output_____ | Apache-2.0 | exercises/ex1-DAR/teched2020-INT260_Data_Attribute_Recommendation.ipynb | SAP-samples/teched2020-INT260 |
Note that the Dataset status changed from `NO_DATA` to `VALIDATING`.Dataset validation is a background process. The status will eventually change from `VALIDATING` to `SUCCEEDED`.The SDK provides the [`DataManagerClient.wait_for_dataset_validation()`](https://data-attribute-recommendation-python-sdk.readthedocs.io/en/l... | dataset_resource = data_manager.wait_for_dataset_validation(dataset_id)
print()
print("Dataset after validation has finished:")
print()
pprint(dataset_resource) | _____no_output_____ | Apache-2.0 | exercises/ex1-DAR/teched2020-INT260_Data_Attribute_Recommendation.ipynb | SAP-samples/teched2020-INT260 |
If the status is `FAILED` instead of `SUCCEEDED`, then the `validationMessage` will contain details about the validation failure. To better understand the Dataset lifecycle, refer to the [corresponding document on help.sap.com](https://help.sap.com/viewer/105bcfd88921418e8c29b24a7a402ec3/SHIP/en-US/a9b7429687a04e769dbc... | from sap.aibus.dar.client.model_manager_client import ModelManagerClient
from sap.aibus.dar.client.exceptions import DARHTTPException
model_manager = ModelManagerClient.construct_from_service_key(SERVICE_KEY)
model_template_id = "d7810207-ca31-4d4d-9b5a-841a644fd81f" # hierarchical template
model_name = "bestbuy-hier... | _____no_output_____ | Apache-2.0 | exercises/ex1-DAR/teched2020-INT260_Data_Attribute_Recommendation.ipynb | SAP-samples/teched2020-INT260 |
The job is now running in the background. Similar to the DatasetValidation, we have to poll the job until it succeeds.The SDK provides the [`ModelManagerClient.wait_for_job()`](https://data-attribute-recommendation-python-sdk.readthedocs.io/en/latest/api.htmlsap.aibus.dar.client.model_manager_client.ModelManagerClient.... | job_resource = model_manager.wait_for_job(job_id)
print()
print("Job resource after training is finished:")
pprint(job_resource) | _____no_output_____ | Apache-2.0 | exercises/ex1-DAR/teched2020-INT260_Data_Attribute_Recommendation.ipynb | SAP-samples/teched2020-INT260 |
To better understand the Training Job lifecycle, see the [corresponding document on help.sap.com](https://help.sap.com/viewer/105bcfd88921418e8c29b24a7a402ec3/SHIP/en-US/0fc40aa077ce4c708c1e5bfc875aa3be.html). IntermissionThe model training will take between 5 and 10 minutes.In the meantime, we can explore the availab... | model_resource = model_manager.read_model_by_name(model_name)
print()
pprint(model_resource) | _____no_output_____ | Apache-2.0 | exercises/ex1-DAR/teched2020-INT260_Data_Attribute_Recommendation.ipynb | SAP-samples/teched2020-INT260 |
In the model resource, the `validationResult` key provides information about model performance. You can also use these metrics to compare performance of different [ModelTemplates](Selecting-the-right-ModelTemplate) or different datasets. Summary Exercise 01.3In exercise 01.3, we have covered the following topics:* How... | deployment_resource = model_manager.create_deployment(model_name)
deployment_id = deployment_resource["id"]
print()
print("Deployment resource:")
print()
pprint(deployment_resource)
print(f"Deployment ID: {deployment_id}") | _____no_output_____ | Apache-2.0 | exercises/ex1-DAR/teched2020-INT260_Data_Attribute_Recommendation.ipynb | SAP-samples/teched2020-INT260 |
*Note: if you are using a trial account and you see errors such as 'The resource can no longer be used. Usage limit has been reached', consider [cleaning up the service instance](Cleaning-up-a-service-instance) to free up limited trial resources.* Similar to the data upload and the training job, model deployment is an ... | deployment_resource = model_manager.wait_for_deployment(deployment_id)
print()
print("Finished deployment resource:")
print()
pprint(deployment_resource) | _____no_output_____ | Apache-2.0 | exercises/ex1-DAR/teched2020-INT260_Data_Attribute_Recommendation.ipynb | SAP-samples/teched2020-INT260 |
Once the Deployment is in status `SUCCEEDED`, we can run inference requests. To better understand the Deployment lifecycle, see the [corresponding document on help.sap.com](https://help.sap.com/viewer/105bcfd88921418e8c29b24a7a402ec3/SHIP/en-US/f473b5b19a3b469e94c40eb27623b4f0.html). *For trial users: the deployment wi... | from sap.aibus.dar.client.inference_client import InferenceClient
inference = InferenceClient.construct_from_service_key(SERVICE_KEY)
objects_to_be_classified = [
{
"features": [
{"name": "manufacturer", "value": "Energizer"},
{"name": "description", "value": "Alkaline batteries; 1... | _____no_output_____ | Apache-2.0 | exercises/ex1-DAR/teched2020-INT260_Data_Attribute_Recommendation.ipynb | SAP-samples/teched2020-INT260 |
*Note: For trial accounts, you only have a limited number of objects which you can classify.* You can also try to come up with your own example: |
my_own_items = [
{
"features": [
{"name": "manufacturer", "value": "EDIT THIS"},
{"name": "description", "value": "EDIT THIS"},
{"name": "price", "value": "0.00"},
],
},
]
inference_response = inference.create_inference_request(model_name, my_own_items)
p... | _____no_output_____ | Apache-2.0 | exercises/ex1-DAR/teched2020-INT260_Data_Attribute_Recommendation.ipynb | SAP-samples/teched2020-INT260 |
You can also classify multiple objects at once. For each object, the `top_n` parameter determines how many predictions are returned. | objects_to_be_classified = [
{
"objectId": "optional-identifier-1",
"features": [
{"name": "manufacturer", "value": "Energizer"},
{"name": "description", "value": "Alkaline batteries; 1.5V"},
{"name": "price", "value": "5.99"},
],
},
{
"ob... | _____no_output_____ | Apache-2.0 | exercises/ex1-DAR/teched2020-INT260_Data_Attribute_Recommendation.ipynb | SAP-samples/teched2020-INT260 |
We can see that the service now returns the `n-best` predictions for each label as indicated by the `top_n` parameter.In some cases, the predicted category has the special value `nan`. In the `bestBuy.csv` data set, not all records have the full set of three categories. Some records only have a top-level category. The ... | # Inspect all video games with just a top-level category entry
video_games = df[df['level1_category'] == 'Video Games']
video_games.loc[df['level2_category'].isna() & df['level3_category'].isna()].head(5) | _____no_output_____ | Apache-2.0 | exercises/ex1-DAR/teched2020-INT260_Data_Attribute_Recommendation.ipynb | SAP-samples/teched2020-INT260 |
To learn how to execute inference calls without the SDK just using the underlying RESTful API, see [Inference without the SDK](Inference-without-the-SDK). Summary Exercise 01.4In exercise 01.4, we have covered the following topics:* How to deploy a previously trained model* How to execute inference requests against a ... | # Clean up all resources created earlier
CLEANUP_SESSION = False
def cleanup_session():
model_manager.delete_deployment_by_id(deployment_id) # this can take a few seconds
model_manager.delete_model_by_name(model_name)
model_manager.delete_job_by_id(job_id)
data_manager.delete_dataset_by_id(dataset_id... | _____no_output_____ | Apache-2.0 | exercises/ex1-DAR/teched2020-INT260_Data_Attribute_Recommendation.ipynb | SAP-samples/teched2020-INT260 |
Resources*Back to [table of contents](Table-of-Contents)* SDK Resources* [SDK source code on Github](https://github.com/SAP/data-attribute-recommendation-python-sdk)* [SDK documentation](https://data-attribute-recommendation-python-sdk.readthedocs.io/en/latest/)* [How to obtain support](https://github.com/SAP/data-att... | # If the following example gives you errors that the jq or curl commands cannot be found,
# you may be able to install them from conda by uncommenting one of the lines below:
#%conda install -q jq
#%conda install -q curl
%%bash -s "$model_name" # Pass the python model_name variable as the first argument to shell script... | _____no_output_____ | Apache-2.0 | exercises/ex1-DAR/teched2020-INT260_Data_Attribute_Recommendation.ipynb | SAP-samples/teched2020-INT260 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.