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 can configure the `anchorDateYear`,`anchorDateMonth` and `anchorDateDay` for the relatives dates. In the following example we will use as a relative date 2021/02/22, to make that possible we need to set up the `anchorDateYear` to 2020, the `anchorDateMonth` to 2 and the `anchorDateDay` to 27. I will show you the con...
date_normalizer = DateNormalizer().setInputCols('chunk_date').setOutputCol('date')\ .setAnchorDateDay(27)\ .setAnchorDateMonth(2)\ .setAnchorDateYear(2021) date_normaliced_df = date_normalizer.transform(chunks_df) dateNormalizedClean = date_normaliced_df.selectExpr("ner_chunk","date....
+------------+----------+--------+ |ner_chunk |dateresult|metadata| +------------+----------+--------+ |08/02/2018 |2018/08/02|true | |11/2018 |2018/11/DD|true | |11/01/2018 |2018/11/01|true | |12Mar2021 |2021/03/12|true | |Jan 30, 2018|2018/01/30|true | |13.04.1999 |1999/04/13|true | |3Apr...
Apache-2.0
tutorials/Certification_Trainings/Healthcare/25.Date_Normalizer.ipynb
Rock-ass/spark-nlp-workshop
import pandas as pd #data = pd.read_csv(filename, encoding= 'unicode_escape') df = pd.read_csv("/content/test _123.csv", encoding= 'unicode_escape') df.head() #del df["planType"] #del df["customField4"] #del df["customField5"] #del df["pdfName"] #del df["phoneNumber"] #del df["dropDate"] #df #Group by the coordinated...
_____no_output_____
MIT
Python_Project1.ipynb
gndede/python
Code to download The Guardian UK data and clean data for text analysis@Jorge de Leon This script allows you to download news articles that match your parameters from the Guardian newspaper, https://www.theguardian.com/us. Set-up
import os import re import glob import json import requests import pandas as pd from glob import glob from os import makedirs from textblob import TextBlob from os.path import join, exists from datetime import date, timedelta os.chdir("..") import nltk nltk.download('punkt') nltk.download('wordnet') nltk.downloa...
_____no_output_____
MIT
python/The Guardian Data ingestion and wrangling/The_Guardian_JPMorgan.ipynb
georgetown-analytics/Economic-Events
API and news articles requestsThis section contains the code that will be used to download articles from the Guardian website. the initial variables will be determined as user-defined parameters.
#Enter API and parameters - these parameters can be obtained by playing around with the Guardian API tool: # https://open-platform.theguardian.com/explore/ # Set up initial and end date start_date_global = date(2000, 1, 1) end_date_global = date(2020, 5, 17) query = "JPMorgan" term = ('stock') #Enter API key, endpo...
_____no_output_____
MIT
python/The Guardian Data ingestion and wrangling/The_Guardian_JPMorgan.ipynb
georgetown-analytics/Economic-Events
Text Analysis
#Drop empty columns theguardian_rawdata = theguardian_rawdata.iloc[:,0:12] #show types of media that was downloaded by type theguardian_rawdata['type'].unique() #filter only for articles theguardian_rawdata = theguardian_rawdata[theguardian_rawdata['type'].str.match('article',na=False)] #remove columns that do not cont...
_____no_output_____
MIT
python/The Guardian Data ingestion and wrangling/The_Guardian_JPMorgan.ipynb
georgetown-analytics/Economic-Events
Neuroon cross-validation------------------------Neuroon and PSG recordings were simultanously collected over the course of two nights. This analysis will show whether Neuroon is able to accurately classify sleep stages. The PSG classification will be a benchmark against which Neuroon performance will be tested. "The AA...
%matplotlib inline %load_ext autoreload %autoreload 2 import numpy as np import matplotlib.pyplot as plt from itertools import tee import pandas as pd import seaborn as sns from numpy.fft import fft, ifft, fft2, ifft2, fftshift from collections import OrderedDict from datetime import timedelta plt.rcParams['figure....
_____no_output_____
MIT
old scripts/Time_synchronization.ipynb
pawelngei/sleep_project
Hipnogram time-delay--------------------From the crosscorrelation of the eeg signals we can see the two devices are off by 2 minutes 41 seconds. Now we'll see if there is a point in time where the hipnograms are most simmilar. The measure of hipnogram simmilarity will be the sum of times when two devices classified the...
import parse_hipnogram as ph def get_hipnogram_intersection(neuroon_hipnogram, psg_hipnogram, time_shift): neuroon_hipnogram.index = neuroon_hipnogram.index + timedelta(seconds = int(time_shift)) combined = psg_hipnogram.join(neuroon_hipnogram, how = 'outer', lsuffix = '_psg', rsuffix = '_neuro') ...
_____no_output_____
MIT
old scripts/Time_synchronization.ipynb
pawelngei/sleep_project
@author : krishan subudhi create a list of 50 random numbers
import random arr = [random.randint(0,1000) for i in range(50)] arr[:10]
_____no_output_____
Apache-2.0
python_and_data_analysis/numpy-sample.ipynb
krishansubudhi/krishanAI
Calculate square root
import math %timeit [math.sqrt(a) for a in arr]
20.9 µs ± 177 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Apache-2.0
python_and_data_analysis/numpy-sample.ipynb
krishansubudhi/krishanAI
numpy 1. Faster1. Easy to use2. Memory effecient3. Rich in mathematical functions4. Easy matrix operations
import numpy as np numpy_arr = np.array(arr) numpy_arr[:10] %timeit np.sqrt(numpy_arr)
2.82 µs ± 196 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Apache-2.0
python_and_data_analysis/numpy-sample.ipynb
krishansubudhi/krishanAI
Matrix operations
matrix_2d = np.random.randint(0,100,(2,3)) matrix_2d matrix_2d.sum(axis = 0)
_____no_output_____
Apache-2.0
python_and_data_analysis/numpy-sample.ipynb
krishansubudhi/krishanAI
PI-ICR analysisCreated on 17 July 2019 for the ISOLTRAP experiment- V1.1 (24 June 2020): Maximum likelihood estimation was simplified based on SciPy PDF's and the CERN-ROOT6 minimizer via the iminuit package (→ great performance)- V1.2 (20 February 2021): Preparations for scientific publication and iminuit v2 update i...
!pip3 install --user pandas numpy matplotlib scipy configparser jupyter iminuit
_____no_output_____
MIT
pi-icr-analysis.ipynb
jonas-ka/pi-icr-analysis
Instead of the regular jupyter environment, one can also use CERN's SWAN service or Google Colab.
google_colab = False if google_colab: try: from google.colab import drive drive.mount('/content/drive') %cd /content/drive/My\ Drive/Colab/pi-icr/ except: %cd ~/cernbox/Documents/Colab/pi-icr/
_____no_output_____
MIT
pi-icr-analysis.ipynb
jonas-ka/pi-icr-analysis
Data filesSpecify, whether the analysis involves one or two states separated in pattern 2 by commenting out the not applicable case in lines 10 or 11. Then enter the file paths for all your data files without the `*.txt` extension. In the following, `ioi` represents the Ion of interest, and `ref` the reference ion.
%config InlineBackend.figure_format ='retina' import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import pickle, os # analysis = {'ioi_g': {},'ref': {}} analysis = {'ioi_g': {},'ioi_m': {},'ref': {}} files_ioi_g = ['data/ioi_ground/85Rb_c_000', 'data/ioi_gro...
_____no_output_____
MIT
pi-icr-analysis.ipynb
jonas-ka/pi-icr-analysis
Load pre-analyzed data from file or reconstruct raw dataAll files are loaded and reconstructed in one big dictionary of dictionaries. It contains besides the positions and timestamps also information about the measurement conditions (excitation frequencies, rounds etc). One can load a whole beamtime at once. Center fi...
from bin.reconstruction import PIICR piicr = PIICR() if os.path.isfile('data/data-save.p'): analysis = pickle.load(open('data/data-save.p','rb')) print('\nLoading finished!') else: for file in files_ioi_g: analysis['ioi_g'].update({file: piicr.prepare(file)}) if analysis['ioi_m'] != {}: ...
Loading finished!
MIT
pi-icr-analysis.ipynb
jonas-ka/pi-icr-analysis
Individual file selectionThe analysis dictionary contains all files. The analysis however is intended to be performed on a file-by-file basis. Please select the individual files here in the variable `file_name`.
# load P1, P2 and C data in panda dataframes for selected file # file_name = files_ioi_g[1] # file_name = files_ioi_m[1] # file_name = files_ref[1] file_name = files_ioi_g[3] print('Selected file:',file_name) if 'ground' in file_name: df_p1 = pd.DataFrame(analysis['ioi_g'][file_name]['p1'], columns=['event','x'...
Selected file: data/ioi_ground/85Rb_006
MIT
pi-icr-analysis.ipynb
jonas-ka/pi-icr-analysis
Manual space and time cutPlease perform a rough manual space cut for each file to improve results on the automatic space cutting tool. This is necessary if one deals with two states in pattern two or if there is a lot of background. This selection will be ellipsoidal. Additionally, please perform a rough time of fligh...
# manual_space_cut = [x_peak_pos, x_peak_spread, y_peak_pos, y_peak_spread] manual_space_cut = {'data/ioi_ground/85Rb_002': [150, 150, 100, 150], 'data/ioi_ground/85Rb_004': [150, 150, 100, 150], 'data/ioi_ground/85Rb_006': [150, 150, 100, 150], 'data/ref/133C...
_____no_output_____
MIT
pi-icr-analysis.ipynb
jonas-ka/pi-icr-analysis
Automatic time and space cuts based on Gaussian distributionThis section contains all cuts in time and space in different steps. 1. In the time domain contaminants are removed by fitting a gaussian distribution via maximum likelihood estimation to the largest peak in the ToF spectrum and cutting +/- 5 $\sigma$ (change...
%config InlineBackend.figure_format ='retina' import matplotlib as mpl from scipy.stats import norm from iminuit import Minuit # Utopia LaTeX font with greek letters mpl.rc('font', family='serif', serif='Linguistics Pro') mpl.rc('text', usetex=False) mpl.rc('mathtext', fontset='custom', rm='Linguistics Pro', ...
mean = 25.54630 +/- 0.01769 sig = 0.27570 +/- 0.01251 p1: data size: 248 -> time cut: 244 -> manual space cut: 239 -> automatic space cut: 235 -> z-class-cut: 235 mean = 25.55908 +/- 0.01934 sig = 0.32012 +/- 0.01367 p2: data size: 283 -> time cut: 281 -> manual space cut: 266 -> automatic space cut: 265 -> z-class-...
MIT
pi-icr-analysis.ipynb
jonas-ka/pi-icr-analysis
Spot fitting2D multivariate gaussian maximum likelihood estimations of the cleaned pattern 1, pattern 2 and center spot positions are performed SciPy PDF's and ROOT's minimizer. Displayed are all uncut data with a blue-transparent point. This allows displaying a density of points by the shade of blue without the need ...
%config InlineBackend.figure_format ='retina' # activate interactive matplotlib plot -> uncomment line below! # %matplotlib notebook import pickle, os from scipy.stats import multivariate_normal, linregress, pearsonr from scipy.optimize import minimize import numpy as np from iminuit import Minuit # open preanalyzed ...
'LinguisticsPro-Italic.otf' can not be subsetted into a Type 3 font. The entire font will be embedded in the output. 'LinguisticsPro-Regular.otf' can not be subsetted into a Type 3 font. The entire font will be embedded in the output.
MIT
pi-icr-analysis.ipynb
jonas-ka/pi-icr-analysis
--- !!! REPEAT CODE ABOVE FOR ALL INDIVIDUAL FILES !!!--- Save fit data to dataframe and *.csv fileContinue here after analyzing all files individually. The following command saves all necessary data and fit information in a `*.csv` file.
calc_df = pd.DataFrame() for key in analysis.keys(): for subkey in analysis[key].keys(): if '_c_' not in subkey: calc_df = calc_df.append(pd.DataFrame({'file': subkey, 'p1_x': analysis[key][subkey]['fit-p1']['meanx'][0], 'p1_y': analysis[ke...
_____no_output_____
MIT
pi-icr-analysis.ipynb
jonas-ka/pi-icr-analysis
Calculate $\nu_c$ from position fits[1]: https://doi.org/10.1007/s00340-013-5621-0[2]: https://doi.org/10.1103/PhysRevLett.110.082501[3]: https://doi.org/10.1007/s10751-019-1601-zCan be run independently from everything above by loading the `analysis-summary.csv` file! A detailed description of the $\nu_c$ calculation...
import pandas as pd import numpy as np # load fit-data file, datetime has to be converted calc_df = pd.read_csv('data/analysis-summary.csv', header=0, index_col=0) # calculate angle between the P1-vector (P1_x/y - C_x/y) and the P2-vector (P2_x/y - C_x/y) calc_df['p1p2_angle'] = np.arctan2(calc_df.p1_y - calc_df.c_y,...
_____no_output_____
MIT
pi-icr-analysis.ipynb
jonas-ka/pi-icr-analysis
Frequency-ratio calculation[1]: https://doi.org/10.1007/s00340-013-5621-0[2]: https://doi.org/10.1103/PhysRevLett.110.082501[3]: https://doi.org/10.1007/s10751-019-1601-zIn order to determine the frequency ratio between the ioi and the ref, simultaneous fits of all for the data set possible polynomial degrees are perf...
import pandas as pd import numpy as np from bin.freq_ratio import Freq_ratio freq = Freq_ratio() # load fit-data file calc_df = pd.read_csv('data/analysis-summary.csv', header=0, index_col=0) # save average time of measurement: t_start+(t_end-t_start)/2 calc_df.time_start = pd.to_datetime(calc_df.time_start) calc_df....
[-10, 685181.1403450029, 1] Poly-degree: 2 Red.Chi.Sq.: 0.6548141372439115 Corellation: 2.7799756249708774e-12 Ratio fit parameter: 0.6388872125439365 +/- 2.1557485311110636e-09 [1, -10, 685181.1403450029, 1] Poly-degree: 3 Red.Chi.Sq.: 0.7550362063128235
MIT
pi-icr-analysis.ipynb
jonas-ka/pi-icr-analysis
Frequency-ratio plotting
%config InlineBackend.figure_format ='retina' import matplotlib.pyplot as plt import matplotlib as mpl import pandas as pd import numpy as np mpl.rc('font', family='serif', serif='Linguistics Pro') # open source Utopia LaTeX font with greek letters mpl.rc('text', usetex=False) mpl.rc('mathtext', fontset='custom', ...
'LinguisticsPro-Bold.otf' can not be subsetted into a Type 3 font. The entire font will be embedded in the output. 'LinguisticsPro-Italic.otf' can not be subsetted into a Type 3 font. The entire font will be embedded in the output. 'LinguisticsPro-Regular.otf' can not be subsetted into a Type 3 font. The entire font wi...
MIT
pi-icr-analysis.ipynb
jonas-ka/pi-icr-analysis
Introdution to Jupyter Notebooks and Text Processing in PythonThis 'document' is a Jupyter notebook. It allows you to combine explanatory **text** and **code** that executes to produce results you can see on the same page. Notebook Basics Text cellsThe box this text is written in is called a *cell*. It is a *text cell...
# This is a comment in a code cell. Comments start with a # symbol. They are ignored and do not do anything. # This box is a code cell. When this cell is run, the code below will execute and produce a result 3 + 4
_____no_output_____
MIT
notebooks/1-intro-to-strings.ipynb
mchesterkadwell/bughunt-analysis
Simple String Manipulation in PythonThis section introduces some very basic things you can do in Python to create and manipulate *strings*. A string is a simple sequence of characters, like `flabbergast`. This introduction is limited to those things that may be useful to know in order to understand the *Bughunt!* data...
'Butterflies are important as pollinators.'
_____no_output_____
MIT
notebooks/1-intro-to-strings.ipynb
mchesterkadwell/bughunt-analysis
In order to do something useful with this string, other than print it out, we need to store in a *variable* by using the assignment operator `=` (equals sign). Whatever is on the right-hand side of the `=` is stored into a variable with the name on the left-hand side.
# my_variable is the variable on the left # 'manuscripts' is the string on the right that is stored in the variable my_variable my_variable = 'Butterflies are important as pollinators.'
_____no_output_____
MIT
notebooks/1-intro-to-strings.ipynb
mchesterkadwell/bughunt-analysis
Notice that nothing is printing to the screen. That's because the string is stored in the variable `my_variable`. In order to see what is inside the variable `my_variable` we can simply write `my_variable` in a code cell, run it, and the interpreter will print it out for us.
my_variable
_____no_output_____
MIT
notebooks/1-intro-to-strings.ipynb
mchesterkadwell/bughunt-analysis
Manipulating Bits of Strings Accessing Individual CharactersA strings is just a sequence (or list) of characters. You can access **individual characters** in a string by specifying which ones you want in square brackets. If you want the first character you specify `1`.
my_variable[1]
_____no_output_____
MIT
notebooks/1-intro-to-strings.ipynb
mchesterkadwell/bughunt-analysis
Hang on a minute! Why did it give us `u` instead of `B`?In programming, everything tends to be *zero indexed*, which means that things are counted from 0 rather than 1. Thus, in the example above, `1` gives us the *second* character in the string.If you want the first character in the string, you need to specify the in...
my_variable[0]
_____no_output_____
MIT
notebooks/1-intro-to-strings.ipynb
mchesterkadwell/bughunt-analysis
Accessing a Range of CharactersYou can also pick out a **range of characters** from within a string, by giving the *start index* followed by the *end index* with a semi-colon (`:`) in between.The example below gives us the character at index `0` all the way up to, *but not including*, the character at index `20`.
my_variable[0:20]
_____no_output_____
MIT
notebooks/1-intro-to-strings.ipynb
mchesterkadwell/bughunt-analysis
Changing Whole Strings with FunctionsPython has some built-in *functions* that allow you to change a whole string at once. You can change all characters to lowercase or uppercase:
my_variable.lower() my_variable.upper()
_____no_output_____
MIT
notebooks/1-intro-to-strings.ipynb
mchesterkadwell/bughunt-analysis
NB: These functions do not change the original string but create a new one. Our original string is still the same as it was before:
my_variable
_____no_output_____
MIT
notebooks/1-intro-to-strings.ipynb
mchesterkadwell/bughunt-analysis
Testing StringsYou can also test a string to see if it is passes some test, e.g. is the string all alphabetic characters only?
my_variable.isalpha()
_____no_output_____
MIT
notebooks/1-intro-to-strings.ipynb
mchesterkadwell/bughunt-analysis
Does the string have the letter `p` in it?
'p' in my_variable
_____no_output_____
MIT
notebooks/1-intro-to-strings.ipynb
mchesterkadwell/bughunt-analysis
Lists of StringsAnother important thing we can do with strings is creating a list of strings by listing them inside square brackets `[]`:
my_list = ['Butterflies are important as pollinators', 'Butterflies feed primarily on nectar from flowers', 'Butterflies are widely used in objects of art'] my_list
_____no_output_____
MIT
notebooks/1-intro-to-strings.ipynb
mchesterkadwell/bughunt-analysis
Manipulating Lists of StringsJust like with strings, we can access individual items inside a list by index number:
my_list[0]
_____no_output_____
MIT
notebooks/1-intro-to-strings.ipynb
mchesterkadwell/bughunt-analysis
And we can access a range of items inside a list by *slicing*:
my_list[0:2]
_____no_output_____
MIT
notebooks/1-intro-to-strings.ipynb
mchesterkadwell/bughunt-analysis
Advanced: Creating Lists of Strings with List ComprehensionsWe can create new lists in an elegant way by combining some of the things we have covered above. Here is an example where we have taken our original list `my_list` and created a new list `new_list` by going over each string in the list:
new_list = [string for string in my_list] new_list
_____no_output_____
MIT
notebooks/1-intro-to-strings.ipynb
mchesterkadwell/bughunt-analysis
Why do this? If we combine it with a test, we can have a list that only contains strings with the letter `p` in them:
new_list_p = [string for string in my_list if 'p' in string] new_list_p
_____no_output_____
MIT
notebooks/1-intro-to-strings.ipynb
mchesterkadwell/bughunt-analysis
This is a very powerful way to quickly create lists. We can even change all the strings to uppercase at the same time!
new_list_p_upper = [string.upper() for string in my_list if 'p' in string] new_list_p_upper
_____no_output_____
MIT
notebooks/1-intro-to-strings.ipynb
mchesterkadwell/bughunt-analysis
This notebook will illustrate how to access DeepLabCut(DLC) results for IBL sessions and how to create short videos with DLC labels printed onto, as well as wheel angle, starting by downloading data from the IBL flatiron server. It requires ibllib, a ONE account and the following script: https://github.com/int-brain-la...
run '/home/mic/Dropbox/scripts/IBL/DLC_labeled_video.py' one = ONE()
Connected to https://alyx.internationalbrainlab.org as michael.schartner
MIT
dlc/Example_DLC_access.ipynb
GaelleChapuis/iblapps
Let's first find IBL ephys sessions with DLC results:
eids= one.search(task_protocol='ephysChoiceworld', dataset_types=['camera.dlc'], details=False) len(eids)
_____no_output_____
MIT
dlc/Example_DLC_access.ipynb
GaelleChapuis/iblapps
For a particular session, we can create a short labeled video by calling the function Viewer, specifying the eid of the desired session, the video type (there's 'left', 'right' and 'body' videos), and a range of trials for which the video should be created. Most sesions have around 700 trials. In the following, this is...
eid = eids[6] Viewer(eid, 'left', [10,13], save_video=True, eye_zoom=False)
Connected to https://alyx.internationalbrainlab.org as michael.schartner Connected to https://alyx.internationalbrainlab.org as michael.schartner
MIT
dlc/Example_DLC_access.ipynb
GaelleChapuis/iblapps
As usual when downloading IBL data from flatiron, the dimensions are listed. Below is one frame of the video for illustration. One can see one point for each paw, two points for the edges of the tongue, one point for the nose and there are 4 points close together around the pupil edges. All points for which the DLC net...
one = ONE() dataset_types = ['camera.times','trials.intervals','camera.dlc'] video_type = 'left' # get paths to load in data D = one.load('3663d82b-f197-4e8b-b299-7b803a155b84',dataset_types=dataset_types, dclass_output=True) alf_path = Path(D.local_path[0]).parent.parent / 'alf' video_data = alf_path.parent / 'raw_vid...
_____no_output_____
MIT
dlc/Example_DLC_access.ipynb
GaelleChapuis/iblapps
There is also 'times' in this dictionary, the time stamps for each frame that we'll use to sync it with other events in the experiment. Let's get rid of it briefly to have only DLC points and set coordinates to nan when the likelihood is below 0.9.
Times = cam['times'] del cam['times'] points = np.unique(['_'.join(x.split('_')[:-1]) for x in cam.keys()]) cam['times'] = Times # A helper function to find closest time stamps def find_nearest(array, value): array = np.asarray(array) idx = (np.abs(array - value)).argmin() return idx
_____no_output_____
MIT
dlc/Example_DLC_access.ipynb
GaelleChapuis/iblapps
Let's pick say the 5th trial and find all DLC traces for it.
frame_start = find_nearest(cam['times'], trials['intervals'][4][0]) frame_stop = find_nearest(cam['times'], trials['intervals'][4][1]) XYs = {} for point in points: x = np.ma.masked_where( cam[point + '_likelihood'] < 0.9, cam[point + '_x']) x = x.filled(np.nan) y = np.ma.masked_where( cam[p...
_____no_output_____
MIT
dlc/Example_DLC_access.ipynb
GaelleChapuis/iblapps
Week 3 - Functions The real power in any programming language is the **Function**.A function is:* a little block of script (one line or many) that performs specific task or a series of tasks.* reusable and helps us make our code DRY.* triggered when something "invokes" or "calls" it.* ideally modular – it performs a n...
## Build a function called myFunction that adds 2 numbers together ## it should print "The total is (whatever the number is)!" ## build it here ## Call myFunction using 4 and 5 as the arguments ## Call myFunction using 10 and 2 as the arguments ## you might forget what arguments are needed for the function to work....
_____no_output_____
MIT
in-class/week-3-B-defined-functions-BLANKS.ipynb
jchapamalacara/fall21-students-practical-python
To use or not use functions?Let's compare the two options with a simple example:
## You have a list of numbers. mylist1 = [1, -5, 22, -44.2, 33, -45] ## Turn each number into an absolute number. ## a for loop works perfectly fine here. ## The problem is that your project keeps generating more lists. ## Each list of numbers has to be turned into absolute numbers mylist2 = [-56, -34, -75, -111, -22...
_____no_output_____
MIT
in-class/week-3-B-defined-functions-BLANKS.ipynb
jchapamalacara/fall21-students-practical-python
DRY Do you keep writing for loops for each list? No, that's a lot of repetition! DRY stands for "Don't Repeat Yourself"
## Instead we write a function that takes a list, ## converts each list item to an absolute number, ## and prints out the number ## Try swapping out different lists into the function:
_____no_output_____
MIT
in-class/week-3-B-defined-functions-BLANKS.ipynb
jchapamalacara/fall21-students-practical-python
Timesaver Imagine for a moment that your editor tells you that the calculation needs to be updated. Instead of needing the absolute number, you need the absolute number minus 5. Having used multiple for loops, you'd have to change each one. What if you miss one or two? Either way, it's a chore. With functions, you ju...
## So if an editor says to actually multiply the absolute number by 1_000_000, ## Try swapping out different lists into the function:
_____no_output_____
MIT
in-class/week-3-B-defined-functions-BLANKS.ipynb
jchapamalacara/fall21-students-practical-python
Return Statements So far we have only printed out values processed by a function. But we really want to retain the value the function creates. We can then pass that value to other parts of our calculations and code.
## Simple example ## A function that adds two numbers together and prints the value: ## call the function with the numbers 2 and 4 ## let's try to save it in a variable called myCalc ## Print myCalc. What does it hold?
_____no_output_____
MIT
in-class/week-3-B-defined-functions-BLANKS.ipynb
jchapamalacara/fall21-students-practical-python
The return Statement
## Tweak our function by adding return statement ## instead of printing a value we want to return a value(or values). ## call the function add_numbers_ret ## and store in variable called myCalc ## print myCalc ## What type is myCalc?
_____no_output_____
MIT
in-class/week-3-B-defined-functions-BLANKS.ipynb
jchapamalacara/fall21-students-practical-python
Return multiple values
## demo function name,age,country = getPerson("David", 35, "France")
_____no_output_____
MIT
in-class/week-3-B-defined-functions-BLANKS.ipynb
jchapamalacara/fall21-students-practical-python
Let's revise our earlier absolute values converter with a return statement Here is the earlier version:
## Here it is revised with a return statement ## Let's actually make that a list comprehension version of the function: ## Let's test it by storing the return value in variable x ## What type of data object is it?
_____no_output_____
MIT
in-class/week-3-B-defined-functions-BLANKS.ipynb
jchapamalacara/fall21-students-practical-python
Make a function more flexible and universal* Currently, we have a function that takes ONLY a list as an argument.* We'd have to write another one for a single number argument.
## try using return_absolutes_lc on a single number like -10 ## it will break
_____no_output_____
MIT
in-class/week-3-B-defined-functions-BLANKS.ipynb
jchapamalacara/fall21-students-practical-python
Universalize our absolute numbers function
## call the function make_abs ## try it on -10 ## Try it on mylist3 - it will break!
_____no_output_____
MIT
in-class/week-3-B-defined-functions-BLANKS.ipynb
jchapamalacara/fall21-students-practical-python
We can use the ```map()``` function to tackle this problem.```map()``` takes 2 arguments: a ```function``` and ```iterable like a list```.
## try it on make_abs and mylist3 ## save it into a list
_____no_output_____
MIT
in-class/week-3-B-defined-functions-BLANKS.ipynb
jchapamalacara/fall21-students-practical-python
```map()``` also works for multiple iterables remember our ```add_numbers_ret``` function.
## here it is again: def add_numbers_ret(number1, number2): return (number1 + number2) ## two lists a_even = [2, 4, 6, 8] a_odd = [1, 3, 5, 7, 9] ## note this has one more item in the list. ## run map on a_even and a_odd b = list(map(add_numbers_ret, a_even, a_odd)) b
_____no_output_____
MIT
in-class/week-3-B-defined-functions-BLANKS.ipynb
jchapamalacara/fall21-students-practical-python
Functions that call other funcions
## let's create a function that returns the square of a number ## what is 9 squared?
_____no_output_____
MIT
in-class/week-3-B-defined-functions-BLANKS.ipynb
jchapamalacara/fall21-students-practical-python
Making a point here with a simple exampleLet's say we want to add 2 numbers together and then square that result.Instead of writing one "complex" function, we can call on our modular functions.
## a function that calls our modular functions ## call make_point() on 2 and 5 make_point(2,5)
_____no_output_____
MIT
in-class/week-3-B-defined-functions-BLANKS.ipynb
jchapamalacara/fall21-students-practical-python
piston example with explicit Euler scheme
%matplotlib inline import matplotlib import matplotlib.pyplot as plt import matplotlib.animation as anim import numpy as np import sys sys.path.insert(0, './code') import ideal_gas
_____no_output_____
MIT
piston_animation_euler.ipynb
MarkusLohmayer/master-thesis-code
physical parameters
# length of cylinder l = 0.1 # radius of cylinder r = 0.05 # thickness of wall w = 0.006 # derived geometrical data r2 = 2 * r # diameter of cylinder w2 = w / 2 # halved thickness of wall l2 = l - w2 A = r**2 * np.pi # cross-sectional area def get_v_1(q): """first volume""" return A * (...
_____no_output_____
MIT
piston_animation_euler.ipynb
MarkusLohmayer/master-thesis-code
initial conditionsdetermine $n_1$, $n_2$, $s_1$, $s_2$
# wanted conditions v_1 = v_2 = get_v_1(l/2) θ_1 = 273.15 + 25.0 π_1 = 1.5 * 1e5 θ_2 = 273.15 + 20.0 π_2 = 1.0 * 1e5 from scipy.optimize import fsolve n_1 = fsolve(lambda n : ideal_gas.S_π(ideal_gas.U2(θ_1, n), v_1, n) - π_1, x0=2e22)[0] s_1 = ideal_gas.S(ideal_gas.U2(θ_1, n_1), v_1, n_1) # check temperature ideal_gas....
_____no_output_____
MIT
piston_animation_euler.ipynb
MarkusLohmayer/master-thesis-code
simulation
def set_state(data, i, x): q, p, s_1, s_2 = x data[i, 0] = q data[i, 1] = p data[i, 2] = v = m_inv * p data[i, 3] = v_1 = get_v_1(q) data[i, 4] = π_1 = ideal_gas.U_π(s_1, v_1, n_1) data[i, 5] = s_1 data[i, 6] = θ_1 = ideal_gas.U_θ(s_1, v_1, n_1) data[i, 7] = v_2 ...
_____no_output_____
MIT
piston_animation_euler.ipynb
MarkusLohmayer/master-thesis-code
설치하기
!pip install git+https://github.com/gbolmier/funk-svd from funk_svd.dataset import fetch_ml_ratings from funk_svd import SVD from sklearn.metrics import mean_absolute_error import pandas as pd ds_ratings = pd.read_csv("../ml-latest-small/ratings.csv") ds_movies = pd.read_csv("../ml-latest-small/movies.csv") # funk-svd ...
User: 1 TOP 100 accuracy: 0.27
MIT
notebooks/FunkSVD-lib.ipynb
HeegyuKim/RecSys-MovieLens100k
print("Number of records belonging to black individuals: {}".format(train_adult_black.shape[0])) sns.set(style="dark", rc={'figure.figsize':(11.7,8.27)}) sns.countplot(x="sex", palette="Paired", edgecolor=".6", data=train_adult_black) #In what concerns sex, we have an equal representation ...
_____no_output_____
MIT
blog/black-lives-matter/Race_bias_A_synthetic_data_approach.ipynb
ydataai/academy
LAB 5b: Deploy and predict with Keras model on Cloud AI Platform.**Learning Objectives**1. Setup up the environment1. Deploy trained Keras model to Cloud AI Platform1. Online predict from model on Cloud AI Platform1. Batch predict from model on Cloud AI Platform Introduction In this notebook, we'll deploying our Kera...
import os
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive2/structured/labs/5b_deploy_keras_ai_platform_babyweight.ipynb
Glairly/introduction_to_tensorflow
Lab Task 1: Set environment variables.Set environment variables so that we can use them throughout the entire lab. We will be using our project name for our bucket, so you only need to change your project and region.
%%bash PROJECT=$(gcloud config list project --format "value(core.project)") echo "Your current GCP Project Name is: "$PROJECT # Change these to try this notebook out PROJECT = "cloud-training-demos" # TODO: Replace with your PROJECT BUCKET = PROJECT # defaults to PROJECT REGION = "us-central1" # TODO: Replace with y...
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive2/structured/labs/5b_deploy_keras_ai_platform_babyweight.ipynb
Glairly/introduction_to_tensorflow
Check our trained model filesLet's check the directory structure of our outputs of our trained model in folder we exported the model to in our last [lab](../solutions/10_train_keras_ai_platform_babyweight.ipynb). We'll want to deploy the saved_model.pb within the timestamped directory as well as the variable values in...
%%bash gsutil ls gs://${BUCKET}/babyweight/trained_model %%bash MODEL_LOCATION=$(gsutil ls -ld -- gs://${BUCKET}/babyweight/trained_model/2* \ | tail -1) gsutil ls ${MODEL_LOCATION}
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive2/structured/labs/5b_deploy_keras_ai_platform_babyweight.ipynb
Glairly/introduction_to_tensorflow
Lab Task 2: Deploy trained model.Deploying the trained model to act as a REST web service is a simple gcloud call. Complete __TODO__ by providing location of saved_model.pb file to Cloud AI Platoform model deployment service. The deployment will take a few minutes.
%%bash MODEL_NAME="babyweight" MODEL_VERSION="ml_on_gcp" MODEL_LOCATION=# TODO: Add GCS path to saved_model.pb file. echo "Deleting and deploying $MODEL_NAME $MODEL_VERSION from $MODEL_LOCATION" # gcloud ai-platform versions delete ${MODEL_VERSION} --model ${MODEL_NAME} # gcloud ai-platform models delete ${MODEL_NAME} ...
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive2/structured/labs/5b_deploy_keras_ai_platform_babyweight.ipynb
Glairly/introduction_to_tensorflow
Lab Task 3: Use model to make online prediction.Complete __TODO__s for both the Python and gcloud Shell API methods of calling our deployed model on Cloud AI Platform for online prediction. Python APIWe can use the Python API to send a JSON request to the endpoint of the service to make it predict a baby's weight. Th...
from oauth2client.client import GoogleCredentials import requests import json MODEL_NAME = # TODO: Add model name MODEL_VERSION = # TODO: Add model version token = GoogleCredentials.get_application_default().get_access_token().access_token api = "https://ml.googleapis.com/v1/projects/{}/models/{}/versions/{}:predict"...
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive2/structured/labs/5b_deploy_keras_ai_platform_babyweight.ipynb
Glairly/introduction_to_tensorflow
The predictions for the four instances were: 5.33, 6.09, 2.50, and 5.86 pounds respectively when I ran it (your results might be different). gcloud shell APIInstead we could use the gcloud shell API. Create a newline delimited JSON file with one instance per line and submit using gcloud.
%%writefile inputs.json {"is_male": "True", "mother_age": 26.0, "plurality": "Single(1)", "gestation_weeks": 39} {"is_male": "False", "mother_age": 26.0, "plurality": "Single(1)", "gestation_weeks": 39}
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive2/structured/labs/5b_deploy_keras_ai_platform_babyweight.ipynb
Glairly/introduction_to_tensorflow
Now call `gcloud ai-platform predict` using the JSON we just created and point to our deployed `model` and `version`.
%%bash gcloud ai-platform predict \ --model=babyweight \ --json-instances=inputs.json \ --version=# TODO: Add model version
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive2/structured/labs/5b_deploy_keras_ai_platform_babyweight.ipynb
Glairly/introduction_to_tensorflow
Lab Task 4: Use model to make batch prediction.Batch prediction is commonly used when you have thousands to millions of predictions. It will create an actual Cloud AI Platform job for prediction. Complete __TODO__s so we can call our deployed model on Cloud AI Platform for batch prediction.
%%bash INPUT=gs://${BUCKET}/babyweight/batchpred/inputs.json OUTPUT=gs://${BUCKET}/babyweight/batchpred/outputs gsutil cp inputs.json $INPUT gsutil -m rm -rf $OUTPUT gcloud ai-platform jobs submit prediction babypred_$(date -u +%y%m%d_%H%M%S) \ --data-format=TEXT \ --region ${REGION} \ --input-paths=$INPUT...
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive2/structured/labs/5b_deploy_keras_ai_platform_babyweight.ipynb
Glairly/introduction_to_tensorflow
SummaryWe are given : * a positive integer $n$ which is the number of dimension of the space. * a positive integer $k$ which is the total number of discrete points we need to place inside that space. * each continuous point $x$ queried in that space that follows a probability density function $PDF$.And we are...
tree = Tree(2, 21) tree.plot() points = tree.get_points() plt.figure() for p in points: plt.plot(p[0], p[1], 'bo', label='Points') plt.plot([0, 0], [0, 1], 'g--', label='Space') plt.plot([0, 1], [0, 0], 'g--') plt.plot([1, 1], [0, 1], 'g--') plt.plot([1, 0], [1, 1], 'g--') plt.xticks(np.linspace(0, 1, 9)) plt.yt...
_____no_output_____
MIT
notebooks/my_approach.ipynb
jimkon/adaptive-discretization
XYZ Pro FeaturesThis notebook demonstrates some of the pro features for XYZ Hub API.XYZ paid features can be found here: [xyz pro features](https://www.here.xyz/xyz_pro/).XYZ plans can be found here: [xyz plans](https://developer.here.com/pricing). Virtual SpaceA virtual space is described by definition which referen...
# Make necessary imports. import os import json import warnings from xyzspaces.datasets import get_chicago_parks_data, get_countries_data from xyzspaces.exceptions import ApiError import xyzspaces
_____no_output_____
Apache-2.0
docs/notebooks/xyz_pro_features_examples.ipynb
fangkun202303x/heremapsn
Warning: Before running below cells please make sure you have XYZ Token to interact with xyzspaces. Please see README.md in notebooks folder for more info on XYZ_TOKEN
os.environ["XYZ_TOKEN"] = "MY-XYZ-TOKEN" # Replace your token here. xyz = xyzspaces.XYZ() # create two spaces which will act as upstream spaces for virtual space created later. title1 = "Testing xyzspaces" description1 = "Temporary space containing countries data." space1 = xyz.spaces.new(title=title1, description=de...
_____no_output_____
Apache-2.0
docs/notebooks/xyz_pro_features_examples.ipynb
fangkun202303x/heremapsn
GroupGroup means to combine the content of the specified spaces. All objects of each space will be part of the response when the virtual space is queried by the user. The information about which object came from which space can be found in the XYZ-namespace in the properties of each feature. When writing back these ob...
# Create a new virtual space by grouping two spaces created above. title = "Virtual Space for coutries and Chicago parks data" description = "Test group functionality of virtual space" upstream_spaces = [space_id1, space_id2] kwargs = {"virtualspace": dict(group=upstream_spaces)} vspace = xyz.spaces.virtual(title=ti...
_____no_output_____
Apache-2.0
docs/notebooks/xyz_pro_features_examples.ipynb
fangkun202303x/heremapsn
MergeMerge means that objects with the same ID will be merged together. If there are duplicate feature-IDs in the various data of the upstream spaces, the duplicates will be merged to build a single feature. The result will be a response that is guaranteed to have no features with duplicate IDs. The merge will happen ...
# create two spaces with duplicate data title1 = "Testing xyzspaces" description1 = "Temporary space containing Chicago parks data." space1 = xyz.spaces.new(title=title1, description=description1) with open("./data/chicago_parks.geo.json", encoding="utf-8-sig") as json_file: gj_chicago = json.load(json_file) # A...
_____no_output_____
Apache-2.0
docs/notebooks/xyz_pro_features_examples.ipynb
fangkun202303x/heremapsn
OverrideOverride means that objects with the same ID will be overridden completely. If there are duplicate feature-IDs in the various data of the upstream spaces, the duplicates will be overridden to result in a single feature. The result will be a response that is guaranteed to have no features with duplicate IDs. Th...
# create two spaces with duplicate data title1 = "Testing xyzspaces" description1 = "Temporary space containing Chicago parks data." space1 = xyz.spaces.new(title=title1, description=description1) with open("./data/chicago_parks.geo.json", encoding="utf-8-sig") as json_file: gj_chicago = json.load(json_file) # A...
_____no_output_____
Apache-2.0
docs/notebooks/xyz_pro_features_examples.ipynb
fangkun202303x/heremapsn
Applying clustering in space
# create two spaces which will act as upstream spaces for virtual space created later. title1 = "Testing xyzspaces" description1 = "Temporary space containing countries data." space1 = xyz.spaces.new(title=title1, description=description1) # Add some data to it space1 gj_countries = get_countries_data() space1.add_fe...
_____no_output_____
Apache-2.0
docs/notebooks/xyz_pro_features_examples.ipynb
fangkun202303x/heremapsn
Rule based TaggingRule based tagging makes tagging multiple features in space tagged to a particular tag, based in rules mentioned based on JSON-path expression. Users can update space with a map of rules where the key is the tag to be applied to all features matching the JSON-path expression being the value.If multip...
# Create a new space title = "Testing xyzspaces" description = "Temporary space containing Chicago parks data." space = xyz.spaces.new(title=title, description=description) # Add data to the space. with open("./data/chicago_parks.geo.json", encoding="utf-8-sig") as json_file: gj_chicago = json.load(json_file) _ = s...
_____no_output_____
Apache-2.0
docs/notebooks/xyz_pro_features_examples.ipynb
fangkun202303x/heremapsn
Activity LogThe Activity log will enable tracking of changes in your space.To activate it, just create a space with the listener added and enable_uuid set to True.More information on the activity log can be found [here](https://www.here.xyz/api/devguide/activitylogguide/).
title = "Activity-Log Test" description = "Activity-Log Test" listeners = { "id": "activity-log", "params": {"states": 5, "storageMode": "DIFF_ONLY", "writeInvalidatedAt": "true"}, "eventTypes": ["ModifySpaceEvent.request"], } space = xyz.spaces.new( title=title, description=description, enable_...
_____no_output_____
Apache-2.0
docs/notebooks/xyz_pro_features_examples.ipynb
fangkun202303x/heremapsn
Pyber Ride Sharing3 observations from the data:* Urban drivers typically drive more frequently yet charge on average (i.e., <30) less than rural drivers.* Roughly two-thirds of all rides occur in Urban cities, however, roughly 80% of all drivers work in Urban areas.* While less rides occur in rural cities, there are o...
import pandas as pd import matplotlib.pyplot as plt import numpy as np # Read in City Data csv file city_df = pd.read_csv('city_data.csv') # Read in Ride Data csv file ride_df = pd.read_csv('ride_data.csv') # Combine the 2 dataframes pyber_df = pd.merge(city_df, ride_df, on="city", how='left') pyber_df.head() # Find t...
_____no_output_____
MIT
Pyber.ipynb
bmodie/Unit_5_Pyber
Bubble Plot
## Bubble Plot Data all_urban_rides = urban_data.groupby('city')['Total Rides'].sum() avg_urban_fare = urban_data.groupby('city')['Average Fare'].mean() all_suburban_rides = suburban_data.groupby('city')['Total Rides'].sum() avg_suburban_fare = suburban_data.groupby('city')['Average Fare'].mean() all_rural_rides = ru...
_____no_output_____
MIT
Pyber.ipynb
bmodie/Unit_5_Pyber
Pie Charts Total Fares by City Type
## Find Total Fares By City Type urban_fare_total = urban_data['City Fare Total'].sum() suburban_fare_total = suburban_data['City Fare Total'].sum() rural_fare_total = rural_data['City Fare Total'].sum() # Create a Pie Chart to Express the Above Date driver_type = ["Urban", "Suburban", "Rural"] driver_count = [urban_...
_____no_output_____
MIT
Pyber.ipynb
bmodie/Unit_5_Pyber
Total Rides by City Type
## Find Total Rides By City Type urban_rides_count = urban_data['Total Rides'].sum() suburban_rides_count = suburban_data['Total Rides'].sum() rural_rides_count = rural_data['Total Rides'].sum() # Create a Pie Chart to Express the Above Date ride_type = ["Urban", "Suburban", "Rural"] ride_count = [urban_rides_count, ...
_____no_output_____
MIT
Pyber.ipynb
bmodie/Unit_5_Pyber
Total Drivers by City Type
## Find Total Drivers By City Type urban_driver_count = urban_data['Driver Count'].sum() suburban_driver_count = suburban_data['Driver Count'].sum() rural_driver_count = rural_data['Driver Count'].sum() # Create a Pie Chart to Express the Above Date driver_type = ["Urban", "Suburban", "Rural"] driver_count = [urban_d...
_____no_output_____
MIT
Pyber.ipynb
bmodie/Unit_5_Pyber
Average Ride Value Per Driver (by City Type)
# Identify the average fare for drivers in each city type urban_avg_driver_pay = urban_fare_total / urban_rides_count suburban_avg_driver_pay = suburban_fare_total / suburban_rides_count rural_avg_driver_pay = rural_fare_total / rural_rides_count # Create a Bar Chart to Express the Above Date driver_type = ["Urban", "...
_____no_output_____
MIT
Pyber.ipynb
bmodie/Unit_5_Pyber
Average Fare Distribution Across All Drivers (by City Type)
urban_fare_dist = urban_fare_total / urban_driver_count suburban_fare_dist = suburban_fare_total / suburban_driver_count rural_fare_dist = rural_fare_total / rural_driver_count # Create a Bar Chart to Express the Above Date driver_type = ["Urban", "Suburban", "Rural"] avg_fare_dist = [urban_fare_dist, suburban_fare_di...
_____no_output_____
MIT
Pyber.ipynb
bmodie/Unit_5_Pyber
torchserve.ipynbThis notebook contains code for the portions of the benchmark in [the benchmark notebook](./benchmark.ipynb) that use [TorchServe](https://github.com/pytorch/serve).
# Imports go here import json import os import requests import scipy.special import transformers # Fix silly warning messages about parallel tokenizers os.environ['TOKENIZERS_PARALLELISM'] = 'False' # Constants go here INTENT_MODEL_NAME = 'mrm8488/t5-base-finetuned-e2m-intent' SENTIMENT_MODEL_NAME = 'cardiffnlp/twit...
_____no_output_____
Apache-2.0
notebooks/benchmark/torchserve.ipynb
frreiss/zero-copy-model-loading
Model PackagingTorchServe requires models to be packaged up as model archive files. Documentation for this process (such as it is) is [here](https://github.com/pytorch/serve/blob/master/README.mdserve-a-model) and [here](https://github.com/pytorch/serve/blob/master/model-archiver/README.md). Intent ModelThe intent mo...
# First we need to dump the model into a local directory. intent_model = transformers.AutoModelForSeq2SeqLM.from_pretrained( INTENT_MODEL_NAME) intent_tokenizer = transformers.AutoTokenizer.from_pretrained('t5-base') intent_model.save_pretrained('torchserve/intent') intent_tokenizer.save_pretrained('torchserve/int...
_____no_output_____
Apache-2.0
notebooks/benchmark/torchserve.ipynb
frreiss/zero-copy-model-loading
Next we wrapped the model in a handler class, located at `./torchserve/handler_intent.py`, which needs to be in its own separate Python file in order for the `torch-model-archiver`utility to work.The following command turns this Python file, plus the data files created by the previous cell, into a model archive (`.mar`...
%%time !mkdir -p torchserve/model_store !torch-model-archiver --model-name intent --version 1.0 \ --serialized-file torchserve/intent/pytorch_model.bin \ --handler torchserve/handler_intent.py \ --extra-files "torchserve/intent/config.json,torchserve/intent/special_tokens_map.json,torchserve/intent/tokenizer_config....
CPU times: user 438 ms, sys: 116 ms, total: 553 ms Wall time: 54 s
Apache-2.0
notebooks/benchmark/torchserve.ipynb
frreiss/zero-copy-model-loading
Sentiment ModelThe sentiment model operates similarly to the intent model.
sentiment_tokenizer = transformers.AutoTokenizer.from_pretrained( SENTIMENT_MODEL_NAME) sentiment_model = ( transformers.AutoModelForSequenceClassification .from_pretrained(SENTIMENT_MODEL_NAME)) sentiment_model.save_pretrained('torchserve/sentiment') sentiment_tokenizer.save_pretrained('torchserve/sentime...
_____no_output_____
Apache-2.0
notebooks/benchmark/torchserve.ipynb
frreiss/zero-copy-model-loading
As with the intent model, we created a handler class (located at `torchserve/handler_sentiment.py`), thenpass that class and the serialized model from two cells agothrough the `torch-model-archiver` utility.
%%time !torch-model-archiver --model-name sentiment --version 1.0 \ --serialized-file torchserve/sentiment/pytorch_model.bin \ --handler torchserve/handler_sentiment.py \ --extra-files "torchserve/sentiment/config.json,torchserve/sentiment/special_tokens_map.json,torchserve/sentiment/tokenizer_config.json,torchserve...
CPU times: user 210 ms, sys: 114 ms, total: 324 ms Wall time: 24.2 s
Apache-2.0
notebooks/benchmark/torchserve.ipynb
frreiss/zero-copy-model-loading
Question Answering ModelThe QA model uses a `transformers` pipeline. We squeeze this model into the TorchServe APIs by telling the pipeline to serialize all of its parts to a single directory, then passing the parts that aren't `pytorch_model.bin` in as extra files. At runtime, our custom handler uses the model loadin...
qa_pipeline = transformers.pipeline('question-answering', model=QA_MODEL_NAME) qa_pipeline.save_pretrained('torchserve/qa')
_____no_output_____
Apache-2.0
notebooks/benchmark/torchserve.ipynb
frreiss/zero-copy-model-loading
As with the previous models, we wrote a class (located at `torchserve/handler_qa.py`), thenpass that wrapper class and the serialized model through the `torch-model-archiver` utility.
%%time !torch-model-archiver --model-name qa --version 1.0 \ --serialized-file torchserve/qa/pytorch_model.bin \ --handler torchserve/handler_qa.py \ --extra-files "torchserve/qa/config.json,torchserve/qa/merges.txt,torchserve/qa/special_tokens_map.json,torchserve/qa/tokenizer_config.json,torchserve/qa/tokenizer.jso...
_____no_output_____
Apache-2.0
notebooks/benchmark/torchserve.ipynb
frreiss/zero-copy-model-loading
Natural Language Generation ModelThe text generation model is roughly similar to the QA model, albeit with important differences in how the three stages of the pipeline operate. At least model loading is the same.
generate_pipeline = transformers.pipeline( 'text-generation', model=GENERATE_MODEL_NAME) generate_pipeline.save_pretrained('torchserve/generate') data = [GENERATE_INPUT, GENERATE_INPUT] pad_token_id = generate_pipeline.tokenizer.eos_token_id json_records = data # preprocess() takes a single input at a time, but...
_____no_output_____
Apache-2.0
notebooks/benchmark/torchserve.ipynb
frreiss/zero-copy-model-loading
Once again, we wrote a class (located at `torchserve/handler_generate.py`), thenpass that wrapper class and the serialized model through the `torch-model-archiver` utility.
%%time !torch-model-archiver --model-name generate --version 1.0 \ --serialized-file torchserve/generate/pytorch_model.bin \ --handler torchserve/handler_generate.py \ --extra-files "torchserve/generate/config.json,torchserve/generate/merges.txt,torchserve/generate/special_tokens_map.json,torchserve/generate/tokeniz...
CPU times: user 198 ms, sys: 96 ms, total: 294 ms Wall time: 24.5 s
Apache-2.0
notebooks/benchmark/torchserve.ipynb
frreiss/zero-copy-model-loading
TestingNow we can fire up TorchServe and test our models.For some reason, starting TorchServe needs to be done in a proper terminal window. Running the command from this notebook has no effect. The commands to run (from the root of the repository) are:```> conda activate ./env> cd notebooks/benchmark/torchserve> torc...
# Probe the management API to verify that TorchServe is running. requests.get('http://127.0.0.1:8081/models').json() port = 8080 intent_result = requests.put( f'http://127.0.0.1:{port}/predictions/intent_en', json.dumps(INTENT_INPUT)).json() print(f'Intent result: {intent_result}') sentiment_result = request...
_____no_output_____
Apache-2.0
notebooks/benchmark/torchserve.ipynb
frreiss/zero-copy-model-loading