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
Note that it is possible to nest multiple timeouts.
with ExpectTimeout(5): with ExpectTimeout(3): long_running_test() long_running_test()
Start 0 seconds have passed 1 seconds have passed
MIT
docs/notebooks/ExpectError.ipynb
bjrnmath/debuggingbook
That's it, folks – enjoy! SynopsisThe `ExpectError` class allows you to catch and report exceptions, yet resume execution. This is useful in notebooks, as they would normally interrupt execution as soon as an exception is raised. Its typical usage is in conjunction with a `with` clause:
with ExpectError(): x = 1 / 0
Traceback (most recent call last): File "<ipython-input-1-264328004f25>", line 2, in <module> x = 1 / 0 ZeroDivisionError: division by zero (expected)
MIT
docs/notebooks/ExpectError.ipynb
bjrnmath/debuggingbook
The `ExpectTimeout` class allows you to interrupt execution after the specified time. This is useful for interrupting code that might otherwise run forever.
with ExpectTimeout(5): long_running_test()
Start 0 seconds have passed 1 seconds have passed 2 seconds have passed 3 seconds have passed
MIT
docs/notebooks/ExpectError.ipynb
bjrnmath/debuggingbook
Export JSON to TXT + CSVThe WE1S workflows use JSON format internally for manipulating data. However, you may wish to export JSON data from a project to plain text files with a CSV metadata file for use with other external tools.This notebook uses JSON project data to export a collection of plain txt files &mdash; one...
# Python imports from pathlib import Path from IPython.display import display, HTML # Get path to project_dir current_dir = %pwd project_dir = str(Path(current_dir).parent.parent) json_dir = project_dir + '/project_data/json' config_path = project_dir + '/config/config.py...
_____no_output_____
MIT
src/templates/v0.1.9/modules/export/json_to_txt_csv.ipynb
whatevery1says/we1s-templates
ConfigurationThe default configuration assumes:1. There are JSON files in `project_data/json`.2. Each JSON has the required fields `pub_date`, `title`, `author`.3. Each JSON file has either: - a `content` field, or - a `bag_of_words` field created using the `import` module tokenizer (see the "Export Features Table...
limit = 10 # limit files exported -- 0 = unlimited. txt_dir = project_dir + '/project_data/txt' metafile = project_dir + '/project_data/txt/metadata.csv' zipfile = project_dir + '/project_data/txt/txt.zip' # The listed fields will be checked in order. # The first one encountered will be the export content. # Docum...
_____no_output_____
MIT
src/templates/v0.1.9/modules/export/json_to_txt_csv.ipynb
whatevery1says/we1s-templates
ExportStart the export.
# Optionally, clear the cache if clear_cache: clear_txt(txt_dir, metafile=metafile, zipfile=zipfile) # Perform the export json_to_txt_csv(json_dir=json_dir, txt_dir=txt_dir, txt_content_fields=txt_content_fields, csv_export_fields=csv_export_fields, ...
_____no_output_____
MIT
src/templates/v0.1.9/modules/export/json_to_txt_csv.ipynb
whatevery1says/we1s-templates
Export Features TablesIf your data contains features tables (lists of lists containing linguistic features), use the cell below to export features tables as CSV files for each document in your JSON folder. Set the `save_path` to a directory where you wish to save the CSV files. If you are using WE1S public data, this ...
# Configuration save_path = '' # Run the export export_features_tables(save_path, json_dir)
_____no_output_____
MIT
src/templates/v0.1.9/modules/export/json_to_txt_csv.ipynb
whatevery1says/we1s-templates
import ipynb into other ipynb> 路過的神器,import ipynb form other ipynb[Source](https://stackoverflow.com/questions/20186344/importing-an-ipynb-file-from-another-ipynb-file)
# import ipynb.fs.full.try1 as try1 # try1.good()
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
本 ipynb 的目標> 做 feature extracion 的 function Referance1. 品妤學姊碩論2. 清彥學長碩論3. 杰勳學長碩論4. This paper (science report, 2019)```A Machine Learning Approach forthe Identification of a Biomarker ofHuman Pain using fNIRS > Raul Fernandez Rojas1,9, Xu Huang1 & Keng-Liang Ou2,3,4,5,6,7,8```5. bbox --> annotation的bbox可以不用指定位置
import os import glob import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # 老樣子,導到適合的資料夾 print(os.getcwd()) # path = 'C:\\Users\\BOIL_PO\\Desktop\\VFT(2)\\VFT' # os.chdir(path) all_csv = glob.glob('Filtered//*.csv') all_csv[:5]
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
Time_Host 設成 index的原因:1. 可用loc切,即用index_name,可以準確地切30秒,不然用iloc還要算筆數舉例:`iloc` 取30秒,必須算 30秒有多少筆 `.iloc[:筆]``loc` 取30秒,打`[:30]`他會自己取 < 30的 index
check_df = pd.read_csv(all_csv[5], index_col= 'Unnamed: 0').drop(columns= ['Time_Arduino', 'easingdata']) # print(check_df.dtypes) check_df = check_df.set_index('Time_Host') check_df.head() # 讀了誰 cols = check_df.columns print(check_df.columns) # 畫圖確認 stage1 = 30 stage2 = 90 stage3 = 160 text_size = 25 plt.figure(figs...
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
濾波請用for> 一定要用for,不然是文組>> 用 for i in range(len(AA)) 還好,但若是後面沒用到`**位置**`資訊,都是 AA[i],那不是文組,但你寫的是C>> Python 的 for 是神>> for str 可以出字母,for list 可以出元素,for model 可以出layer,還有好用的list comprehension `[x**3 for i in range(10) if x%2 == 0]` Feature Extraction (From Lowpass filter) 清彥1. 階段起始斜率 (8s) $\checkmark$ * Task * Reco...
# 就重寫,沒意義 exam_df = pd.read_csv(all_csv[0], index_col= 'Unnamed: 0').drop(columns= ['Time_Arduino', 'easingdata']) # print(exam_df.dtypes) exam_df = exam_df.set_index('Time_Host') exam_df.head()
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
階段起始斜率 2*6= 120. 定義 階段開始前"八秒",單位 `?/S`1. return list2. 30~38 -> Task 3. 90~98 -> Recovery----
def stage_begin_slope(dataframe, plot= False, figsize= (10, 6), use_col= 0): #============================ # Parameter: # dataframe: input dataframe # plot : whether to plot # figsize: plt.figure(figsize= figsize) # Return: # Tuple: # Tuple[0] : List of slope ...
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
畫全部 channel
# for i in range(6): # stage_begin_slope(exam_df, plot= True, use_col= i)
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
階段平均 3*6 = 181. 0~30 -> Rest2. 30~90 -> Task3. 90~ 160 -> Recovery
def stage_mean(dataframe, plot= False, figsize= (10, 6), use_col= 0): #============================ # Parameter: # dataframe: input dataframe # plot : whether to plot # figsize: plt.figure(figsize= figsize) # Return: # Tuple: # Tuple[0] : List of mean # ...
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
畫全部 channel
# for i in range(6): # stage_mean(exam_df, plot= True, use_col=i)
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
階段平均的差 -> 2*6 = 12 * Task mean – Rest mean * Task mean – Recovery mean 活化值 -> 1*6 * Recovery mean – Rest mean
def stage_mean_diff(dataframe, plot= False, figsize= (10, 6), use_col= 0): #============================ # Parameter: # dataframe: input dataframe # plot : whether to plot # figsize: plt.figure(figsize= figsize) # Return: # Tuple: # Tuple[0] : List of mean dif...
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
畫畫看 channel
stage_mean_diff(exam_df, plot= True, use_col= 4)
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
階段峰值 1*6 = 6 * Task
def stage_acivation(dataframe, plot= False, figsize= (10, 6), use_col= 0): #============================ # Parameter: # dataframe: input dataframe # plot : whether to plot # figsize: plt.figure(figsize= figsize) # Return: # Tuple: # Tuple[0] : List of 峰值 #...
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
畫全部 channel
# for i in range(6): # stage_acivation(exam_df, plot= True, use_col= i)
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
階段標準差 * 三個 標準差不能歸一化
def stage_std(dataframe, plot= False, figsize= (10, 6), use_col= 0): #============================ # Parameter: # dataframe: input dataframe # plot : whether to plot # figsize: plt.figure(figsize= figsize) # Return: # Tuple: # Tuple[0] : List of std # ...
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
畫全部 channel
# for i in range(6): # stage_std(exam_df, plot= True, use_col= i)
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
階段起始斜率 的差 * Task - Recovery
def stage_begin_slope_diff(dataframe): #============================ # Parameter: # dataframe: input dataframe # plot : whether to plot # figsize: plt.figure(figsize= figsize) # Return: # Tuple: # Tuple[0] : List of slope diff # Tuple[1] : List of ...
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
Stage skewness -> use scipy * 三個階段> 資料分布靠左"正">> 資料分布靠右"負" [好用圖中圖](https://www.itread01.com/p/518289.html)
def stage_skew(dataframe, plot= False, figsize= (10, 6), use_col= 0): from scipy.stats import skew #============================ # Parameter: # dataframe: input dataframe # plot : whether to plot # figsize: plt.figure(figsize= figsize) # Return: # Tuple: # ...
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
畫全部 channel
# for i in range(6): # a = stage_skew(exam_df, plot= True, use_col= i)
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
Stage kurtosis 峰度(尖度) * 三個
def stage_kurtosis(dataframe): from scipy.stats import kurtosis #============================ # Parameter: # dataframe: input dataframe # plot : whether to plot # figsize: plt.figure(figsize= figsize) # Return: # Tuple: # Tuple[0] : List of kurtosis #...
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
AUC -> use sklearn * 三個1. 看了很多,好比說scipy.integrate, numpy.trap2. 還是 sklearn的好用,(這邊其他的也可以試試不強制)
def stage_auc(dataframe, plot= False, figsize= (10, 6), use_col= 0): from sklearn.metrics import auc #============================ # Parameter: # dataframe: input dataframe # plot : whether to plot # figsize: plt.figure(figsize= figsize) # Return: # Tuple: # ...
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
畫全部 channel
# for i in range(6): # stage_auc(exam_df, plot=True, use_col= i)
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
FFT1. 取樣頻率要是頻率的兩倍![p](data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxQTExYTExMWFhYYGBkWGRYYFxgWFhkXFx4bGxkWGBYZHikhGRsmHxgZIjIjJiosLy8vGCA1OjUtOSkuLywBCgoKDg0OHBAQGy4nHycuNzQsMS40LjkwMDA5Li4vLi4sOS4uLi4sOS4uLC4xLDAsLi4uLC4uLC4uLy4sLy4uLv/AABEIAJQBVAMBIgACEQEDEQH/xAAbAAACAwEBAQAAAAAAAAAAAAAABAEDBQIGB//EAE...
# 第一行 y = exam_df.iloc[:, 0].values
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
stack overflow -> numpy
# stack overflow import numpy as np sample_rate = 24 N = np.array(y).shape[-1] # 從 0 ~ 12Hz 取 N/個 fft_window = np.fft.fft(y) freq = np.fft.fftfreq(N, d=1/24) # 為啥要平方?? fft_ps = np.abs(fft_window)**2 fft_window.shape, freq.shape, freq.max(), freq.min() plt.plot(freq)
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
0.12Hz (cut down frequency)之後decay很快,看起來合理
import matplotlib.pyplot as plt fig = plt.figure(figsize=(14, 7)) plt.plot(freq, 2.0/N *np.abs(fft_window), label= 'FFT') # plt.plot(freq, np.log10(fft_ps)) plt.ylim(0, 0.08) plt.xlim(0.005, 0.4) plt.vlines(0.12, 0, 100, colors= 'r', linestyles= '--', label= 'Cut down Freq (low pass)', ) plt.xlabel("Frequency") plt.y...
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
ML Fundamentals -> scipy
from scipy.fft import fft def get_fft_values(y_values, T, N, f_s): f_values = np.linspace(0.0, 1.0/(2.0*T), N//2) fft_values_ = fft(y_values) # 歸一化嗎?? fft_values = 2.0/N * np.abs(fft_values_[0:N//2]) return f_values, fft_values f_s = 24 T = 1/f_s N = np.array(y).shape[-1] f_values, fft_values =...
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
找峰值 -> scipy > 下面網站有很多方法[1. 好用網站](https://www.delftstack.com/zh-tw/howto/python/find-peaks-in-python/)
import numpy as np from scipy.signal import argrelextrema peaks = argrelextrema(fft_values, np.greater) print(peaks) f_values[5], fft_values[5] for ind in peaks[0]: print(f_values[ind], fft_values[ind]) peaks[0] plt.figure(figsize= (14, 7)) plt.plot(f_values, fft_values, linestyle='-', color='blue') plt.xlabel('...
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
FFT * 一張圖 3 個峰值,共有六種血氧(3channel * 含氧/缺氧) * 一個峰值會有兩數值,一個是 amp,一個是 峰值的頻率
def FFT(dataframe, f_s = 24, plot= False): from scipy.fft import fft import numpy as np from scipy.signal import argrelextrema #============================ # Parameter: # dataframe: input dataframe # plot : whether to plot # figsize: plt.figure(figsize= figsize) # Ret...
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
顛倒ndarray -> 帥`fft_values[real_ind][::-1]` Numpy 神技
test= np.arange(1, 10) test test[::-1] test[::-2] test[::-3] test[::1] test[::2] test[::3]
_____no_output_____
MIT
fNIRS signal analysis/Randonstate/Extraction.ipynb
JulianLee310514065/Complete-Project
Danger zone. This notebook is just here to be convenient for development
%matplotlib ipympl import ipywidgets as widgets import matplotlib.pyplot as plt import numpy as np %load_ext autoreload %autoreload 2 from mpl_interactions import * plt.close() fig, ax = plt.subplots() zoom_factory(ax) ph = panhandler(fig) N = 50 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.rand(N) a...
_____no_output_____
BSD-3-Clause
docs/examples/devlop/devlop-scatter.ipynb
samwelborn/mpl-interactions
EDA: Named Entity RecognitionNamed entity recognition is the process of identifing particular elements from text, such as names, places, quantities, percentages, times/dates, etc. Identifying and quantifying what the general content types an article contains seems like a good predictor of what type of article it is. W...
import articledata import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import operator data = pd.read_pickle('/Users/teresaborcuch/capstone_project/notebooks/pickled_data.pkl')
_____no_output_____
MIT
notebooks/ner_blog_post.ipynb
teresaborcuch/teresaborcuch.github.io
Counting Named EntitiesHere is my count_entities function. The idea is to count the total mentions of a person or a place in an article's body or title and save them as columns in my existing data structure.
def count_entities(data = None, title = True): # set up tagger os.environ['CLASSPATH'] = "/Users/teresaborcuch/stanford-ner-2013-11-12/stanford-ner.jar" os.environ['STANFORD_MODELS'] = '/Users/teresaborcuch/stanford-ner-2013-11-12/classifiers' st = StanfordNERTagger('english.all.3class.distsim.crf.ser.g...
_____no_output_____
MIT
notebooks/ner_blog_post.ipynb
teresaborcuch/teresaborcuch.github.io
These graphs indicate that person and place counts from article are both strongly right skewed. It might be more interesting to compare mean person and place counts among different sections.
data.pivot_table( index = ['condensed_section'], values = ['total_persons_title', 'total_places_title']).sort_values('total_persons_title', ascending = False)
_____no_output_____
MIT
notebooks/ner_blog_post.ipynb
teresaborcuch/teresaborcuch.github.io
From this pivot table, it seems there are a few distinctions to be made between different sections. Entertainment and sports contain more person mentions on average than any other sections, and world news contains more places in the title than other sections. Finding Common Named EntitiesNow, I'll try to see which peo...
def evaluate_entities(data = None, section = None, source = None): section_mask = (data['condensed_section'] == section) source_mask = (data['source'] == source) if section and source: masked_data = data[section_mask & source_mask] elif section: masked_data = data[section_mask] el...
_____no_output_____
MIT
notebooks/ner_blog_post.ipynb
teresaborcuch/teresaborcuch.github.io
Commonly Mentioned People in World News and Entertainment
world_persons, world_places = articledata.evaluate_entities(data = data, section = 'world', source = None) # get top 20 people from world news article bodies sorted_wp = sorted(world_persons.items(), key=operator.itemgetter(1)) sorted_wp.reverse() sorted_wp[:20]
_____no_output_____
MIT
notebooks/ner_blog_post.ipynb
teresaborcuch/teresaborcuch.github.io
Perhaps as expected, Trump is the most commonly mentioned person in world news, with 1,237 mentions in 467 articles, with Obama and Putin coming in second and third. It's interesting to note that most of these names are political figures, but since the tagger only receives unigrams, partial names and first names are me...
entertainment_persons, entertainment_places = articledata.evaluate_entities(data = data, section = 'entertainment', source = None) sorted_ep = sorted(entertainment_persons.items(), key=operator.itemgetter(1)) sorted_ep.reverse() sorted_ep[:20]
_____no_output_____
MIT
notebooks/ner_blog_post.ipynb
teresaborcuch/teresaborcuch.github.io
Now, I'll compare the top 20 people mentioned in entertainment articles. Trump still takes the number one spot, but interestingly, he's followed by a string of first names. NLTK provides a corpus of male and female-tagged first names, so counting the number of informal mentions or even the ratio of men to women might b...
# get top 20 places from world news article bodies sorted_wp = sorted(world_places.items(), key=operator.itemgetter(1)) sorted_wp.reverse() sorted_wp[:20] # get top 20 places from entertainment article bodies sorted_ep = sorted(entertainment_places.items(), key=operator.itemgetter(1)) sorted_ep.reverse() sorted_ep[:20]
_____no_output_____
MIT
notebooks/ner_blog_post.ipynb
teresaborcuch/teresaborcuch.github.io
Analysis of Red Wine Quality Index 1. Reading the data and importing the libraries 2. EDA 3. Correlation Matrix 4. Modeling - Linear Model - Weighted KNN - Random Forest - Conditional Inference Random Forest - Decision Tree Model 5. Modeling Results Table 6. Conclusion 1. Reading the data and i...
library(tidyverse) library(grid) library(gridExtra) library(e1071) library(caret) df1 <- read.csv("C:/Users/kausha2/Documents/Data Analytics/DataSets/winequality/winequality/winequality-red.csv", sep = ";") head(df1) summary(df1$quality)
_____no_output_____
Apache-2.0
Red Wine Quality Analysis.ipynb
RagsX137/Red-Wine-Quality-Analysis
Creating a new variable --> WineAttribute : Good (1) or bad (0) for binary classification
df1$wine_attribute <- ifelse(df1$quality > 5, 1, 0 ) head(df1)
_____no_output_____
Apache-2.0
Red Wine Quality Analysis.ipynb
RagsX137/Red-Wine-Quality-Analysis
2. EDA How is the wine quality distributed?
qplot(df1$quality, geom="histogram", binwidth = 1)
_____no_output_____
Apache-2.0
Red Wine Quality Analysis.ipynb
RagsX137/Red-Wine-Quality-Analysis
- The dataset is dominated by values 5 and 6. There are less wines with a quality of 4 and 7 whereas there are hardly any wines that have values less 3 and 8- there are two options : either split the quality variable into 3 parts by quantiles : top 20, middle 60 and bottom 20 or split based on the mean i.e. Good wines ...
p1 <- qplot(df1$pH, geom="histogram", binwidth = 0.05) p2 <- qplot(df1$alcohol, geom="histogram",binwidth = 0.099) p3 <- qplot(df1$volatile.acidity, geom="histogram",binwidth = 0.05) p4 <- qplot(df1$citric.acid, geom="histogram",binwidth = 0.05) grid.arrange(p1,p2,p3,p4, ncol=2, nrow=2)
_____no_output_____
Apache-2.0
Red Wine Quality Analysis.ipynb
RagsX137/Red-Wine-Quality-Analysis
- We see that pH looks normally distributed - Volatile acidity, Alcohol and citric acid have a positive skew shape but dont seem to follow a particular distribution
p1 <- qplot(df1$residual.sugar, geom="histogram", binwidth = 0.1) p2 <- qplot(df1$chlorides, geom="histogram",binwidth = 0.01) p3 <- qplot(df1$density, geom="histogram",binwidth = 0.001) p4 <- qplot(df1$free.sulfur.dioxide, geom="histogram",binwidth = 1) grid.arrange(p1,p2,p3,p4, ncol=2, nrow=2)
_____no_output_____
Apache-2.0
Red Wine Quality Analysis.ipynb
RagsX137/Red-Wine-Quality-Analysis
- Density seems to follow a normal distribution. - Residual sugar and chlorides seem to follow a normal distribution initially but flatten out later- Free sulfur dioxide content seems to have a positive skew shaped distribution
p1 <- qplot(df1$pH, geom="density") p2 <- qplot(df1$alcohol, geom="density") p3 <- qplot(df1$volatile.acidity, geom="density") p4 <- qplot(df1$citric.acid, geom="density") grid.arrange(p1,p2,p3,p4, ncol=2, nrow=2) p1 <- qplot(df1$residual.sugar, geom="density") p2 <- qplot(df1$chlorides, geom="density") p3 <- qplo...
_____no_output_____
Apache-2.0
Red Wine Quality Analysis.ipynb
RagsX137/Red-Wine-Quality-Analysis
- The kernel density plots seem to agree with the histograms and our conclusions
p1 <- ggplot(df1, aes(x="pH", y=pH)) + stat_boxplot(geom ='errorbar') + geom_boxplot() p2 <- ggplot(df1, aes(x="alcohol", y=alcohol)) + stat_boxplot(geom ='errorbar') + geom_boxplot() p3 <- ggplot(df1, aes(x="volatile.acidity", y=volatile.acidity)) + stat_boxplot(geom ='errorbar') + geom_boxplot() p4 <- ggplot(df1, aes...
_____no_output_____
Apache-2.0
Red Wine Quality Analysis.ipynb
RagsX137/Red-Wine-Quality-Analysis
- pH and acidity seem to have a lot of outliers.- The pH of an acidic substance is usally below 5 but for wines it seems to concentrate in the area between 2.7 and 4.0.- The alcohol content is between 8.4 to 15 but there seem to be many outliers. The Age of the wine also affects its alcohol content. This could explain ...
#data(attitude) df2 <- df1 df2$wine_attribute <- NULL library(ggplot2) library(reshape2) #(cor(df1) ) # correlation matrix cormat <- cor(df2) melted_cormat <- melt(cor(df2)) #ggplot(data = melted_cormat, aes(x=Var1, y=Var2, fill=value)) + # geom_tile() # Get lower triangle of the correlation matrix get_lower_t...
Warning message: "package 'reshape2' was built under R version 3.3.2" Attaching package: 'reshape2' The following object is masked from 'package:tidyr': smiths
Apache-2.0
Red Wine Quality Analysis.ipynb
RagsX137/Red-Wine-Quality-Analysis
- The values in Red are positively correlated while those in Blue are negatively correlated. The density of the color determines the strength of correlation.- Quality has a negative correlation with volatile acidity, and total sulfur dioxide content. While it has a positive correlation with alcohol content and citric a...
p1 <- ggplot(df1, aes(x= volatile.acidity, y= quality)) + geom_point() + geom_smooth(method=lm) p2 <- ggplot(df1, aes(x= total.sulfur.dioxide, y= quality)) + geom_point() + geom_smooth(method=lm) p3 <- ggplot(df1, aes(x= alcohol, y= quality)) + geom_point() + geom_smooth(method=lm) p4 <- ggplot(df1, aes(x= citric.acid,...
_____no_output_____
Apache-2.0
Red Wine Quality Analysis.ipynb
RagsX137/Red-Wine-Quality-Analysis
This confirms our analysis from the correlation matrix 4. Modeling We'll be using a 10-fold cross validationWe perform the 10 fold CV on the learning dataset and try to predict the valid dataset
# Train Test Split m <- dim(df1)[1] # Select the rows of iris val <- sample(1:m, size = round(m/3), replace = FALSE, prob = rep(1/m, m)) df1.learn <- df1[-val,] # train df1.valid <- df1[val,] # test # 10 Fold CV library(caret) # define training control train_control <- trainControl(method="cv", number=10) #trC...
_____no_output_____
Apache-2.0
Red Wine Quality Analysis.ipynb
RagsX137/Red-Wine-Quality-Analysis
The linear model : trying to predict wine quality from the variables
head(df1,1) model1 <- lm(as.numeric(quality)~ 0 + volatile.acidity + chlorides + log(free.sulfur.dioxide) + log(total.sulfur.dioxide) + density + pH + sulphates + alcohol, data = df1) summary(model1) df1.valid$prediction <- predict(model1,df1.valid) df1.valid$prediction_lm <- round(df1.valid$prediction) x...
_____no_output_____
Apache-2.0
Red Wine Quality Analysis.ipynb
RagsX137/Red-Wine-Quality-Analysis
From the above graph we see that this is not what we intended. Therefore we move on to classification models Weighted KNNUsing multiple K, distance metrics and kernels
require(kknn) model2 <- kknn( factor(wine_attribute) ~ fixed.acidity + volatile.acidity + citric.acid + residual.sugar + chlorides + free.sulfur.dioxide + total.sulfur.dioxide + density + pH + sulphates + alcohol, df1.learn, df1.valid) x <- confusionMatrix(df1.valid$wine_attribute, m...
Call: train.kknn(formula = factor(wine_attribute) ~ fixed.acidity + volatile.acidity + citric.acid + residual.sugar + chlorides + free.sulfur.dioxide + total.sulfur.dioxide + density + pH + sulphates + alcohol, data = df1.learn, kmax = 15, distance = 5, kernel = c("triangular", "epanechnikov", "biweigh...
Apache-2.0
Red Wine Quality Analysis.ipynb
RagsX137/Red-Wine-Quality-Analysis
Weighted KKNN gave us decent results. Lets see if we can improve on it. Tree Models Random Forest
library(randomForest) model5 <- randomForest(as.factor(wine_attribute) ~ fixed.acidity + volatile.acidity + citric.acid + residual.sugar + chlorides + free.sulfur.dioxide + total.sulfur.dioxide + density + pH + sulphates + alcohol, df1.learn,trControl = train_control, importance=TRUE,...
_____no_output_____
Apache-2.0
Red Wine Quality Analysis.ipynb
RagsX137/Red-Wine-Quality-Analysis
Ensembling Random Forest with the Conditional Inference Tree
library(party) model5x <- cforest(as.factor(wine_attribute) ~ fixed.acidity + volatile.acidity + citric.acid + residual.sugar + chlorides + free.sulfur.dioxide + total.sulfur.dioxide + density + pH + sulphates + alcohol, df1.learn, controls=cforest_unbiased(ntree=2000, mtry=3)) df1.v...
_____no_output_____
Apache-2.0
Red Wine Quality Analysis.ipynb
RagsX137/Red-Wine-Quality-Analysis
Decision Trees using Rpart
library(rattle) library(rpart.plot) library(RColorBrewer) library(rpart) rpart.grid <- expand.grid(.cp=0.2) model6 <- train(as.factor(wine_attribute) ~ fixed.acidity + volatile.acidity + citric.acid + residual.sugar + chlorides + free.sulfur.dioxide + total.sulfur.dioxide + density + pH ...
_____no_output_____
Apache-2.0
Red Wine Quality Analysis.ipynb
RagsX137/Red-Wine-Quality-Analysis
5. Modeling Results Table
Model_Name <- c("Linear Model", "Simple_KKNN","KKNN_dist1","KKNN_dist2", "RandomForest", "Conditional Forest", "Decision Tree") Overall_Accuracy <- c(acc_lm*100, acc_kknn1*100, acc_kknn2*100, acc_kknn3*100, acc_rf*100, acc_cf*100, acc_dt*100) final <- data.frame(Model_Name,Overall_Accuracy) final$Overall_Accuracy <- ...
_____no_output_____
Apache-2.0
Red Wine Quality Analysis.ipynb
RagsX137/Red-Wine-Quality-Analysis
Optimal treatment for varied lengths of time horizons
cs = c(3.6,3.2) options(repr.plot.width=cs[1],repr.plot.height=cs[2]) cln_nms = c("T","time","sigma","resistance","size") read.table(file="../figures/draft/Fig7X-trjs_optimal.csv",header=FALSE,sep=",",col.names=cln_nms) %>% as.data.frame -> df_optimal print("Optimal") df_optimal %>% tail(1) %>% .$size sz = 1.5;...
_____no_output_____
MIT
scripts/.ipynb_checkpoints/E. Figures 6 and 7 [R]-checkpoint.ipynb
aakhmetz/AkhmKim2019Scripts
Another figure for solution of the optimal control problem
cs = c(4.2,2.75) options(repr.plot.width=cs[1],repr.plot.height=cs[2]) cln_nms = c("trajectory","time","sigma","resistance","size") read.table(file="../figures/draft/Fig6-trjs_optimal-final.csv",header=TRUE,sep=",",col.names=cln_nms) %>% as.data.frame %>% mutate(time=time/30,resistance=100*resistance) -> df # cl...
_____no_output_____
MIT
scripts/.ipynb_checkpoints/E. Figures 6 and 7 [R]-checkpoint.ipynb
aakhmetz/AkhmKim2019Scripts
Accessing Items 1. Write a program to retrieve the keys/values of dictionary **Use the dictionary**dictionary2 = {0:3, 'x':5, 1:2}
dictionary2 = {0:3, 'x':5, 1:2} dictionary2
_____no_output_____
MIT
Arvind/08 - Accessing Items.ipynb
Arvind-collab/Data-Science
2. Write a program to get the value for 'Age' from the dictionary **Use the dictionary**dictionary3 = {'Weight': 67, 'BMI': 25, 'Age': 27, 'Profession': 'CA'}
dictionary3 = {'Weight': 67, 'BMI': 25, 'Age': 27, 'Profession': 'CA'} dictionary3['Age']
_____no_output_____
MIT
Arvind/08 - Accessing Items.ipynb
Arvind-collab/Data-Science
![ebooks.jpg](attachment:ebooks.jpg) Kindle eBook Recommendation System: Data PreparationAuthors: Daniel Burdeno --- Contents- Overview- Business Understanding - Data Understanding - Data Preparation - Imports and Functions - Meta Data - Review Data - CSV Files Overview > This project aims ...
import pandas as pd import numpy as np import matplotlib as plt import warnings # Show plots in notebook %matplotlib inline warnings.filterwarnings('ignore') # Set matplotlib style to match other notebook graphics plt.style.use('fast') # Function that takes a list and returns the third value, used in a .apply below to...
_____no_output_____
MIT
DataPrepFinal.ipynb
danielburdeno/Kindle-eBook-Recommendations
Load Data > As stated in the Data Understanding section, we have two seperate JSON files to load in. One containing individual user reviews and the other containing book meta data. The meta data will need to be heavily cleaned to extract relevant information for this project. These large initial data files were loaded...
# Meta data load-in, file stored as compressed JSON, each line is a JSON entry hence the lines=True arguement path = 'C:\\Users\\danie\\Documents\\Flatiron\\Projects\\Capstone\\Rawdata\\meta_Kindle_Store.gz' df_meta = pd.read_json(path, compression='gzip', lines=True) # Review data load-in, file stored as compressed JS...
_____no_output_____
MIT
DataPrepFinal.ipynb
danielburdeno/Kindle-eBook-Recommendations
Meta Data
df_meta.info() df_meta.head()
_____no_output_____
MIT
DataPrepFinal.ipynb
danielburdeno/Kindle-eBook-Recommendations
> Taking a look at the .info() and .head() of the meta data shows a plethora of cleaning that needs to occur. There are a multitude of unusable columns with blank information including tech1, tech2, fit, description, rank, main_cat, price, and image columns. Within the category column (a list) and the details column (a...
# Taking a look at what is within the category columns, it contains lists df_meta['category'].value_counts() # Using a dual nested lambda function and .apply I can subset the dataframe to only contain categories that denote eBooks df_meta = df_meta.loc[ lambda df: df.category.apply( lambda l: 'Kindle eBooks...
_____no_output_____
MIT
DataPrepFinal.ipynb
danielburdeno/Kindle-eBook-Recommendations
> After running the clean function on my meta data I noticed that there was still blank entries for things like title and I should check for null values. However a lot of these were just blank entries not actually denoated as NaN so I had to parse through the dataframe and replace any blank entry with NaN in order to a...
# Converting blank entries to NaN using regex expression and looking at nulls df_meta = df_meta.replace(r'^\s*$', np.nan, regex=True) df_meta.isna().sum() # Dropping nulls and using groupby to sort by genre so I can fill in any print_length nulls based on mean genre value df_meta['print_length'] = df_meta.groupby(['gen...
_____no_output_____
MIT
DataPrepFinal.ipynb
danielburdeno/Kindle-eBook-Recommendations
Review Data
df_rev.info() df_rev.head() # I thought style would contain genre but it did not, entries will be subsetted using the meta data, so ignore column df_rev['style'].value_counts()
_____no_output_____
MIT
DataPrepFinal.ipynb
danielburdeno/Kindle-eBook-Recommendations
> Taking a look at the review data shows some cleaning that needs to occur as well, including dropping unneeded columns and exploring several others. The overall column denotes the rating that a user gave to the item (critical information). Verified is either True or False, and looking it up it designates if a reviewer...
# Matching reviewed products with products with meta data df_rev = df_rev[df_rev['asin'].isin(asin_list)] df_rev.verified.value_counts() # Dropping any rows that were not verified indexNames = df_rev[df_rev['verified'] == False].index df_rev.drop(indexNames , inplace=True) # Dropping unused columns df_rev_use = df_rev....
<class 'pandas.core.frame.DataFrame'> Int64Index: 1398682 entries, 2754 to 2222982 Data columns (total 4 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 overall 1398682 non-null int64 1 reviewerID 1398682 non-null object 2 asin 1398682 non-null ob...
MIT
DataPrepFinal.ipynb
danielburdeno/Kindle-eBook-Recommendations
CSV Files > For ease of use in further notebooks the cleaned and compiled dataframes were saved to individual csv files within the data folder. These files can be saved locally and were not pushed to github due to size constraints. The meta data files were saved and pushed to github inorder for heroku/streamlit to hav...
# Save cleaned review dataframe to csv for use in other notebook, this set includes reviewers with less than 5 reviews df_rev_use.to_csv('Data/df_rev_all.csv') # Subsetting review data to only include reviewers with 5 or more reviews df_rev5 = df_rev_use[df_rev_use['reviewerID'].map(df_rev_use['reviewerID'].value_count...
_____no_output_____
MIT
DataPrepFinal.ipynb
danielburdeno/Kindle-eBook-Recommendations
> In order to conduct natural language processing and produce content based on review text I needed to aggregate review text based on individual books. I used the unique product number, 'asin', to groupby and then join review text for each book into a new data dataframe below. This dataframe will be used to produce a d...
# Groupby using 'asin' and custom aggregate to join all review text df_books_rev = df_rev_use.groupby(['asin'], as_index = False).agg({'reviewText': ' '.join}) df_books_rev.to_csv('Data/df_books_rev.csv') df_books_rev.head() df_books_rev.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 94211 entries, 0 to 94210 Data columns (total 2 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 asin 94211 non-null object 1 reviewText 94211 non-null object dtypes: object(2) memory usage: 1.4+ MB
MIT
DataPrepFinal.ipynb
danielburdeno/Kindle-eBook-Recommendations
URL: http://bokeh.pydata.org/en/latest/docs/gallery/unemployment.htmlMost examples work across multiple plotting backends, this example is also available for:* [Matplotlib - US unemployment example](../matplotlib/us_unemployment.ipynb)
import pandas as pd import holoviews as hv from holoviews import opts hv.extension('bokeh')
_____no_output_____
BSD-3-Clause
examples/gallery/demos/bokeh/us_unemployment.ipynb
ppwadhwa/holoviews
Defining data
from bokeh.sampledata.unemployment1948 import data data = pd.melt(data.drop('Annual', 1), id_vars='Year', var_name='Month', value_name='Unemployment') heatmap = hv.HeatMap(data, label="US Unemployment (1948 - 2013)")
_____no_output_____
BSD-3-Clause
examples/gallery/demos/bokeh/us_unemployment.ipynb
ppwadhwa/holoviews
Plot
colors = ["#75968f", "#a5bab7", "#c9d9d3", "#e2e2e2", "#dfccce", "#ddb7b1", "#cc7878", "#933b41", "#550b1d"] heatmap.opts( opts.HeatMap(width=900, height=400, xrotation=45, xaxis='top', labelled=[], tools=['hover'], cmap=colors))
_____no_output_____
BSD-3-Clause
examples/gallery/demos/bokeh/us_unemployment.ipynb
ppwadhwa/holoviews
TensorFlow 2 Complete Project Workflow in Amazon SageMaker Data Preprocessing -> Training -> Automatic Model Tuning -> Deployment 1. [Introduction](Introduction)2. [SageMaker Processing for dataset transformation](SageMakerProcessing)5. [SageMaker hosted training](SageMakerHostedTraining)6. [Automatic Model Tuning]...
import boto3 import os import sagemaker import tensorflow as tf sess = sagemaker.session.Session() bucket = sess.default_bucket() region = boto3.Session().region_name data_dir = os.path.join(os.getcwd(), 'data') os.makedirs(data_dir, exist_ok=True) train_dir = os.path.join(os.getcwd(), 'data/train') os.makedirs(tra...
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
SageMaker Processing for dataset transformation Next, we'll import the dataset and transform it with SageMaker Processing, which can be used to process terabytes of data in a SageMaker-managed cluster separate from the instance running your notebook server. In a typical SageMaker workflow, notebooks are only used for ...
import numpy as np from tensorflow.python.keras.datasets import boston_housing from sklearn.preprocessing import StandardScaler (x_train, y_train), (x_test, y_test) = boston_housing.load_data() np.save(os.path.join(raw_dir, 'x_train.npy'), x_train) np.save(os.path.join(raw_dir, 'x_test.npy'), x_test) np.save(os.path....
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
Next, simply supply an ordinary Python data preprocessing script as shown below. For this example, we're using a SageMaker prebuilt Scikit-learn framework container, which includes many common functions for processing data. There are few limitations on what kinds of code and operations you can run, and only a minimal...
%%writefile preprocessing.py import glob import numpy as np import os from sklearn.preprocessing import StandardScaler if __name__=='__main__': input_files = glob.glob('{}/*.npy'.format('/opt/ml/processing/input')) print('\nINPUT FILE LIST: \n{}\n'.format(input_files)) scaler = StandardScaler() f...
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
Before starting the SageMaker Processing job, we instantiate a `SKLearnProcessor` object. This object allows you to specify the instance type to use in the job, as well as how many instances. Although the Boston Housing dataset is quite small, we'll use two instances to showcase how easy it is to spin up a cluster fo...
from sagemaker import get_execution_role from sagemaker.sklearn.processing import SKLearnProcessor sklearn_processor1 = SKLearnProcessor(framework_version='0.23-1', role=get_execution_role(), instance_type='ml.m5.xlarge', ...
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
We're now ready to run the Processing job. To enable distributing the data files equally among the instances, we specify the `ShardedByS3Key` distribution type in the `ProcessingInput` object. This ensures that if we have `n` instances, each instance will receive `1/n` files from the specified S3 bucket. It may take...
from sagemaker.processing import ProcessingInput, ProcessingOutput from time import gmtime, strftime processing_job_name = "tf-2-workflow-{}".format(strftime("%d-%H-%M-%S", gmtime())) output_destination = 's3://{}/{}/data'.format(bucket, s3_prefix) sklearn_processor1.run(code='preprocessing.py', ...
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
In the log output of the SageMaker Processing job above, you should be able to see logs in two different colors for the two different instances, and that each instance received different files. Without the `ShardedByS3Key` distribution type, each instance would have received a copy of **all** files. By spreading the ...
x_train_in_s3 = '{}/train/x_train.npy'.format(output_destination) y_train_in_s3 = '{}/train/y_train.npy'.format(output_destination) x_test_in_s3 = '{}/test/x_test.npy'.format(output_destination) y_test_in_s3 = '{}/test/y_test.npy'.format(output_destination) !aws s3 cp {x_train_in_s3} ./data/train/x_train.npy !aws s3 c...
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
SageMaker hosted training Now that we've prepared a dataset, we can move on to SageMaker's model training functionality. With SageMaker hosted training the actual training itself occurs not on the notebook instance, but on a separate cluster of machines managed by SageMaker. Before starting hosted training, the data ...
s3_prefix = 'tf-2-workflow' traindata_s3_prefix = '{}/data/train'.format(s3_prefix) testdata_s3_prefix = '{}/data/test'.format(s3_prefix) train_s3 = sess.upload_data(path='./data/train/', key_prefix=traindata_s3_prefix) test_s3 = sess.upload_data(path='./data/test/', key_prefix=testdata_s3_prefix) inputs = {'train':t...
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
We're now ready to set up an Estimator object for hosted training. We simply call `fit` to start the actual hosted training.
from sagemaker.tensorflow import TensorFlow train_instance_type = 'ml.c5.xlarge' hyperparameters = {'epochs': 30, 'batch_size': 128, 'learning_rate': 0.01} hosted_estimator = TensorFlow( source_dir='tf-2-workflow-smpipelines', entry_point='train.py', ...
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
After starting the hosted training job with the `fit` method call below, you should observe the valication loss converge with each epoch. Can we do better? We'll look into a way to do so in the **Automatic Model Tuning** section below. In the meantime, the hosted training job should take about 3 minutes to complete.
hosted_estimator.fit(inputs)
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
The training job produces a model saved in S3 that we can retrieve. This is an example of the modularity of SageMaker: having trained the model in SageMaker, you can now take the model out of SageMaker and run it anywhere else. Alternatively, you can deploy the model into a production-ready environment using SageMake...
!aws s3 cp {hosted_estimator.model_data} ./model/model.tar.gz
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
The unzipped archive should include the assets required by TensorFlow Serving to load the model and serve it, including a .pb file:
!tar -xvzf ./model/model.tar.gz -C ./model
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
Automatic Model Tuning So far we have simply run one Hosted Training job without any real attempt to tune hyperparameters to produce a better model. Selecting the right hyperparameter values to train your model can be difficult, and typically is very time consuming if done manually. The right combination of hyperpara...
from sagemaker.tuner import IntegerParameter, CategoricalParameter, ContinuousParameter, HyperparameterTuner hyperparameter_ranges = { 'learning_rate': ContinuousParameter(0.001, 0.2, scaling_type="Logarithmic"), 'epochs': IntegerParameter(10, 50), 'batch_size': IntegerParameter(64, 256), } metric_definitions =...
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
Next we specify a HyperparameterTuner object that takes the above definitions as parameters. Each tuning job must be given a budget: a maximum number of training jobs. A tuning job will complete after that many training jobs have been executed. We also can specify how much parallelism to employ, in this case five j...
tuner = HyperparameterTuner(hosted_estimator, objective_metric_name, hyperparameter_ranges, metric_definitions, max_jobs=15, max_parallel_jobs=5, object...
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
After the tuning job is finished, we can use the `HyperparameterTuningJobAnalytics` object from the SageMaker Python SDK to list the top 5 tuning jobs with the best performance. Although the results vary from tuning job to tuning job, the best validation loss from the tuning job (under the FinalObjectiveValue column) l...
tuner_metrics = sagemaker.HyperparameterTuningJobAnalytics(tuning_job_name) tuner_metrics.dataframe().sort_values(['FinalObjectiveValue'], ascending=True).head(5)
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
The total training time and training jobs status can be checked with the following lines of code. Because automatic early stopping is by default off, all the training jobs should be completed normally. For an example of a more in-depth analysis of a tuning job, see the SageMaker official sample [HPO_Analyze_TuningJob_...
total_time = tuner_metrics.dataframe()['TrainingElapsedTimeSeconds'].sum() / 3600 print("The total training time is {:.2f} hours".format(total_time)) tuner_metrics.dataframe()['TrainingJobStatus'].value_counts()
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
SageMaker hosted endpoint Assuming the best model from the tuning job is better than the model produced by the individual hosted training job above, we could now easily deploy that model to production. A convenient option is to use a SageMaker hosted endpoint, which serves real time predictions from the trained mode...
tuning_predictor = tuner.deploy(initial_instance_count=1, instance_type='ml.m5.xlarge')
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
We can compare the predictions generated by this endpoint with the actual target values:
results = tuning_predictor.predict(x_test[:10])['predictions'] flat_list = [float('%.1f'%(item)) for sublist in results for item in sublist] print('predictions: \t{}'.format(np.array(flat_list))) print('target values: \t{}'.format(y_test[:10].round(decimals=1)))
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
To avoid billing charges from stray resources, you can delete the prediction endpoint to release its associated instance(s).
sess.delete_endpoint(tuning_predictor.endpoint_name)
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
Workflow Automation with SageMaker Pipelines In the previous parts of this notebook, we prototyped various steps of a TensorFlow project within the notebook itself, with some steps being run on external SageMaker resources (hosted training, model tuning, hosted endpoints). Notebooks are great for prototyping, but gen...
from sagemaker.workflow.parameters import ( ParameterInteger, ParameterString, ) # raw input data input_data = ParameterString(name="InputData", default_value=raw_s3) # processing step parameters processing_instance_type = ParameterString(name="ProcessingInstanceType", default_value="ml.m5.xlarge") processing...
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
Processing Step The first step in the pipeline will preprocess the data to prepare it for training. We create a `SKLearnProcessor` object similar to the one above, but now parameterized so we can separately track and change the job configuration as needed, for example to increase the instance type size and count to ac...
from sagemaker.sklearn.processing import SKLearnProcessor role = sagemaker.get_execution_role() framework_version = "0.23-1" sklearn_processor = SKLearnProcessor( framework_version=framework_version, instance_type=processing_instance_type, instance_count=processing_instance_count, base_job_name="tf-2-...
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
Training and Model Creation Steps The following code sets up a pipeline step for a training job. We start by specifying which SageMaker prebuilt TensorFlow 2 training container to use for the job.
from sagemaker.tensorflow import TensorFlow from sagemaker.inputs import TrainingInput from sagemaker.workflow.steps import TrainingStep from sagemaker.workflow.step_collections import RegisterModel tensorflow_version = '2.3.1' python_version = 'py37' image_uri_train = sagemaker.image_uris.retrieve( ...
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
Next, we specify an `Estimator` object, and define a `TrainingStep` to insert the training job in the pipeline with inputs from the previous SageMaker Processing step.
import time model_path = f"s3://{bucket}/TF2WorkflowTrain" training_parameters = {'epochs': 44, 'batch_size': 128, 'learning_rate': 0.0125, 'for_pipeline': 'true'} estimator = TensorFlow( image_uri=image_uri_train, source_dir='tf-2-workflow-smpipelines', entry_point='train.py', instance_type=training_...
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
As another step, we create a SageMaker `Model` object to wrap the model artifact, and associate it with a separate SageMaker prebuilt TensorFlow Serving inference container to potentially use later.
from sagemaker.model import Model from sagemaker.inputs import CreateModelInput from sagemaker.workflow.steps import CreateModelStep image_uri_inference = sagemaker.image_uris.retrieve( framework="tensorflow", region=region, ...
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
Batch Scoring Step The final step in this pipeline is offline, batch scoring (inference/prediction). The inputs to this step will be the model we trained earlier, and the test data. A simple, ordinary Python script is all we need to do the actual batch inference.
%%writefile batch-score.py import os import subprocess import sys import numpy as np import pathlib import tarfile def install(package): subprocess.check_call([sys.executable, "-m", "pip", "install", package]) if __name__ == "__main__": install('tensorflow==2.3.1') model_path = f"/opt/ml/processing/...
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
In regard to the SageMaker features we could use to perform batch scoring, we have several choices, including SageMaker Processing and SageMaker Batch Transform. We'll use SageMaker Processing here.
batch_scorer = SKLearnProcessor( framework_version=framework_version, instance_type=batch_instance_type, instance_count=batch_instance_count, base_job_name="tf-2-workflow-batch", sagemaker_session=sess, ...
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
Creating and executing the pipeline With all of the pipeline steps now defined, we can define the pipeline itself as a `Pipeline` object comprising a series of those steps. Parallel and conditional steps also are possible.
from sagemaker.workflow.pipeline import Pipeline pipeline_name = f"TF2Workflow" pipeline = Pipeline( name=pipeline_name, parameters=[input_data, processing_instance_type, processing_instance_count, training_instance_type, training_instance_cou...
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop