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
Using Adam Optimizer
#with tf.variable_scope('Optimize'): optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-2).minimize(cost)
_____no_output_____
MIT
CNN-Keras-Tensorflow/q1-ck2840.ipynb
Chandra-S-Narain-Kappera/Image-Classification
Metrics
with tf.variable_scope('Metrics'): correct_prediction = tf.equal(y_pred_cls, y_true_cls) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) tf.summary.scalar('accuracy', accuracy)
_____no_output_____
MIT
CNN-Keras-Tensorflow/q1-ck2840.ipynb
Chandra-S-Narain-Kappera/Image-Classification
Tensorflow Session
session = tf.Session() session.run(tf.global_variables_initializer())
_____no_output_____
MIT
CNN-Keras-Tensorflow/q1-ck2840.ipynb
Chandra-S-Narain-Kappera/Image-Classification
Summaries
merged = tf.summary.merge_all() train_writer = tf.summary.FileWriter(log_dir + '/train', session.graph) test_writer = tf.summary.FileWriter(log_dir + '/test') print(X_train.shape) def one_hot(y, num_classes=10): """ Converts each label index in y to vector with one_hot encoding """ y_one_hot = np.zeros(...
_____no_output_____
MIT
CNN-Keras-Tensorflow/q1-ck2840.ipynb
Chandra-S-Narain-Kappera/Image-Classification
Training
train_batch_size = batch_size def print_status(epoch, feed_dict_train, feed_dict_validate, train_loss, val_loss, step): # Calculate the accuracy on the training-set. summary, acc = session.run([merged,accuracy], feed_dict=feed_dict_train) train_writer.add_summary(summary, step) summary, val_acc = sessi...
Accuracy on test set is: 71.399993%
MIT
CNN-Keras-Tensorflow/q1-ck2840.ipynb
Chandra-S-Narain-Kappera/Image-Classification
Write out the results
feed_dict_test= {x: X_test_format,y_true: Y_test_hot, phase: 0, keep_prob:1.0} y_pred = session.run(y_pred, feed_dict=feed_dict_test) save_predictions('ans1-ck2840.npy', y_pred) session.close()
_____no_output_____
MIT
CNN-Keras-Tensorflow/q1-ck2840.ipynb
Chandra-S-Narain-Kappera/Image-Classification
Evaluation von ParsingtechnikenDas Parsing von Textdateien ist ein wichtiger Mechanismus, welcher wärend Informationsbearbeitung einen hohen Stellenwert innehält. In order to be able to choose an adequate technique to be able to parse our custom DSL, we need to evaluate multiple of these techniques first.*The followin...
import matplotlib.pyplot as plt import pandas as pd import numpy as np RUNS = 20
_____no_output_____
Unlicense
.ipynb_checkpoints/ParsingTechniques-checkpoint.ipynb
jhkloss/libg3n_parsing_notebook
Measuring TechniqueTo measure the results we use an combination of the python performance timer functionality and an custom class. This custom class is going to measure the execution time of the different techniques. Thus the execution time is measured multiple times in a row to avoid false measurements due to system ...
import time class PerformanceTimer: timers = {} def __init__(self, name: str = "", iterations: int = 20): self.running = False self.start = None self.name = name self.elapsed = 0.0 self.measurements = {} self.successful_measurements = 0 self.iterations ...
_____no_output_____
Unlicense
.ipynb_checkpoints/ParsingTechniques-checkpoint.ipynb
jhkloss/libg3n_parsing_notebook
Manual Parsing
from parse_manual.parser import parse as parse_manual manual_timer = PerformanceTimer('Manual Parsing', RUNS) manual_timer.measure_function(parse_manual, './samples/sample.gen', './samples/sample-40.gen', './samples/sample-80.gen', './samples/sample-160.gen') manual_timer.print()
--------------Timer: Manual Parsing--------------- Finished: True Sample Sets: 4 Measurements: 80 Measured Times: {0: [2.3339580000083515, 0.5242499998985295, 0.39779200005796156, 0.38650000010420626, 0.3739999999652355, 0.4582500000651635, 0.4288749998977437, 0.3689580000809656, 0.3590409999105759, 0.34633400014172366...
Unlicense
.ipynb_checkpoints/ParsingTechniques-checkpoint.ipynb
jhkloss/libg3n_parsing_notebook
Function execution time development
plt.subplot(2, 2, 1) plt.plot(manual_timer.measurements[0]) plt.title('20 Datapoints') plt.xlim(1, RUNS) plt.xlabel('runs') plt.ylabel('time in ms') plt.subplot(2, 2, 2) plt.plot(manual_timer.measurements[1]) plt.title('40 Datapoints') plt.xlim(1, RUNS) plt.xlabel('runs') plt.ylabel('time in ms') plt.subplot(2, 2, 3)...
_____no_output_____
Unlicense
.ipynb_checkpoints/ParsingTechniques-checkpoint.ipynb
jhkloss/libg3n_parsing_notebook
Individual function execution time results
df = pd.DataFrame(manual_timer.measurements) df.columns = ['20 Datapoints', '40 Datapoints', '80 Datapoints', '160 Datapoints'] df
_____no_output_____
Unlicense
.ipynb_checkpoints/ParsingTechniques-checkpoint.ipynb
jhkloss/libg3n_parsing_notebook
Pyparsing
from parse_pyparsing.parser import parse as parse_pyparsing # Pyparsing pyparsing_timer = PerformanceTimer('Pyparsing', RUNS) pyparsing_timer.measure_function(parse_pyparsing, './samples/sample.gen', './samples/sample-40.gen', './samples/sample-80.gen', './samples/sample-160.gen') pypa...
-----------------Timer: Pyparsing----------------- Finished: True Sample Sets: 4 Measurements: 80 Measured Times: {0: [3.2524169998850994, 3.1476249998831918, 2.429042000130721, 2.4144580002030125, 2.373874999875625, 5.665041000156634, 3.501332999803708, 4.405624999890279, 2.4345419999463047, 2.9748330000529677, 3.7193...
Unlicense
.ipynb_checkpoints/ParsingTechniques-checkpoint.ipynb
jhkloss/libg3n_parsing_notebook
Function execution time development
plt.subplot(2, 2, 1) plt.plot(pyparsing_timer.measurements[0]) plt.title('20 Datapoints') plt.xlim(1, RUNS) plt.xlabel('runs') plt.ylabel('time in ms') plt.subplot(2, 2, 2) plt.plot(pyparsing_timer.measurements[1]) plt.title('40 Datapoints') plt.xlim(1, RUNS) plt.xlabel('runs') plt.ylabel('time in ms') plt.subplot(2,...
_____no_output_____
Unlicense
.ipynb_checkpoints/ParsingTechniques-checkpoint.ipynb
jhkloss/libg3n_parsing_notebook
Individual function execution time results
df = pd.DataFrame(pyparsing_timer.measurements) df.columns = ['20 Datapoints', '40 Datapoints', '80 Datapoints', '160 Datapoints'] df
_____no_output_____
Unlicense
.ipynb_checkpoints/ParsingTechniques-checkpoint.ipynb
jhkloss/libg3n_parsing_notebook
YAML Parsing
from parse_yaml.parser import parse as parse_yaml #YAML yaml_timer = PerformanceTimer('YAML Parsing', RUNS) yaml_timer.measure_function(parse_yaml, './samples/sample.yaml', './samples/sample-40.yaml', './samples/sample-80.yaml', './samples/sample-160.yaml') yaml_timer.print()
---------------Timer: YAML Parsing---------------- Finished: True Sample Sets: 4 Measurements: 80 Measured Times: {0: [10.130707999906008, 8.419750000030035, 8.157375000109823, 7.8233750000435975, 7.933374999993248, 7.832582999981241, 7.7690000000529835, 7.812834000105795, 8.685000000014043, 8.887166000022262, 8.725040...
Unlicense
.ipynb_checkpoints/ParsingTechniques-checkpoint.ipynb
jhkloss/libg3n_parsing_notebook
Function execution time development
plt.subplot(2, 2, 1) plt.plot(yaml_timer.measurements[0]) plt.title('20 Datapoints') plt.xlim(1, RUNS) plt.xlabel('runs') plt.ylabel('time in ms') plt.subplot(2, 2, 2) plt.plot(yaml_timer.measurements[1]) plt.title('40 Datapoints') plt.xlim(1, RUNS) plt.xlabel('runs') plt.ylabel('time in ms') plt.subplot(2, 2, 3) plt...
_____no_output_____
Unlicense
.ipynb_checkpoints/ParsingTechniques-checkpoint.ipynb
jhkloss/libg3n_parsing_notebook
Individual function execution time results
df = pd.DataFrame(yaml_timer.measurements) df.columns = ['20 Datapoints', '40 Datapoints', '80 Datapoints', '160 Datapoints'] df
_____no_output_____
Unlicense
.ipynb_checkpoints/ParsingTechniques-checkpoint.ipynb
jhkloss/libg3n_parsing_notebook
XML Parsing
from parse_xml.parser import parse as parse_xml #XML xml_timer = PerformanceTimer('XML Parsing', RUNS) xml_timer.measure_function(parse_xml, './samples/sample.xml', './samples/sample-40.xml', './samples/sample-80.xml', './samples/sample-160.xml') xml_timer.print()
----------------Timer: XML Parsing---------------- Finished: True Sample Sets: 4 Measurements: 80 Measured Times: {0: [1.24070800006848, 0.1318340000580065, 0.09770900010153127, 0.31420899995282525, 0.11433399981797265, 0.6731660000696138, 0.10866599996006698, 0.09591699995326053, 34.85795899996447, 0.1462080001601862,...
Unlicense
.ipynb_checkpoints/ParsingTechniques-checkpoint.ipynb
jhkloss/libg3n_parsing_notebook
Function execution time development
plt.subplot(2, 2, 1) plt.plot(xml_timer.measurements[0]) plt.title('20 Datapoints') plt.xlim(1, RUNS) plt.xlabel('runs') plt.ylabel('time in ms') plt.subplot(2, 2, 2) plt.plot(xml_timer.measurements[1]) plt.title('40 Datapoints') plt.xlim(1, RUNS) plt.xlabel('runs') plt.ylabel('time in ms') plt.subplot(2, 2, 3) plt.p...
_____no_output_____
Unlicense
.ipynb_checkpoints/ParsingTechniques-checkpoint.ipynb
jhkloss/libg3n_parsing_notebook
Individual function execution time results
df = pd.DataFrame(xml_timer.measurements) df.columns = ['20 Datapoints', '40 Datapoints', '80 Datapoints', '160 Datapoints'] df
_____no_output_____
Unlicense
.ipynb_checkpoints/ParsingTechniques-checkpoint.ipynb
jhkloss/libg3n_parsing_notebook
Comparison
manual_avg = manual_timer.average_time() pyparsing_avg = pyparsing_timer.average_time() yaml_avg = yaml_timer.average_time() xml_avg = xml_timer.average_time() # Define y-axis labels labels = ['Manual', 'Pyparsing', 'YAML', 'XML'] # Define y values y = np.arange(len(labels)) # Define label helper function def add_la...
_____no_output_____
Unlicense
.ipynb_checkpoints/ParsingTechniques-checkpoint.ipynb
jhkloss/libg3n_parsing_notebook
Use the *Machine Learning Workflow* to process & transform Pima Indian data to create a prediction model. This model must predict which people are likely to develop diabetes with 70% accuracy! Import Libraries
import pandas as pd import matplotlib.pyplot as plt import numpy as np #plot inline instead of seperate windows %matplotlib inline
_____no_output_____
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
Load and review data
df = pd.read_csv('./data/pima-data.csv') df.shape df.head() df.isnull().values.any() def plot_correlatedValues(df, size=11): corr = df.corr() fig, ax = plt.subplots(figsize=(size,size)) ax.matshow(corr) plt.xticks(range(len(corr.columns)),corr.columns) plt.yticks(range(len(corr.columns)),corr.colu...
_____no_output_____
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
change diabetes column values from True/False to 1/0
diabetes_map = {True:1, False:0} diabetes_map df['diabetes'] = df['diabetes'].map(diabetes_map) df.head()
_____no_output_____
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
check true/false ratio
num_true = len(df.loc[df['diabetes']==True]) num_false = len(df.loc[df['diabetes']==False] )
_____no_output_____
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
print(" of cases the diabetes is True:- {0}({1:2.2f}%)".format(num_true, (num_true /(num_true+num_false))*100 ))print(" of cases the diabetes is False:- {0}({1:2.2f}%)".format(num_false, (num_false /(num_true+num_false))*100 )) Splitting the data70% training : 30% testing
from sklearn.cross_validation import train_test_split feature_col_names = ['num_preg','glucose_conc', 'diastolic_bp','thickness','insulin','bmi','diab_pred','age'] predicted_class_name = ['diabetes'] X = df[feature_col_names].values y = df[predicted_class_name].values split_test_size = 0.30 X_train, X_test , y_train,...
69.921875(69.92%) in training set 30.078125(30.08%) in test set
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
Confirm the split of predict values was correctly done
print("Original True : {0} ({1:0.2f}%)".format(len(df.loc[df['diabetes'] == 1]), (len(df.loc[df['diabetes'] == 1])/len(df.index)) * 100.0)) print("Original False : {0} ({1:0.2f}%)".format(len(df.loc[df['diabetes'] == 0]), (len(df.loc[df['diabetes'] == 0])/len(df.index)) * 100.0)) print("") print("Training True : {0} ...
Original True : 268 (34.90%) Original False : 500 (65.10%) Training True : 188 (35.01%) Training False : 349 (64.99%) Test True : 80 (34.63%) Test False : 151 (65.37%)
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
rows have have unexpected 0 values?
print("# rows in dataframe {0}".format(len(df))) print("# rows missing glucose_conc: {0}".format(len(df.loc[df['glucose_conc'] == 0]))) print("# rows missing diastolic_bp: {0}".format(len(df.loc[df['diastolic_bp'] == 0]))) print("# rows missing thickness: {0}".format(len(df.loc[df['thickness'] == 0]))) print("# rows mi...
# rows in dataframe 768 # rows missing glucose_conc: 5 # rows missing diastolic_bp: 35 # rows missing thickness: 227 # rows missing insulin: 374 # rows missing bmi: 11 # rows missing diab_pred: 0 # rows missing age: 0
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
Impute missing values
from sklearn.preprocessing import Imputer fill_0 = Imputer(missing_values=0, strategy='mean', axis=0) X_train = fill_0.fit_transform(X_train) X_test = fill_0.fit_transform(X_test)
_____no_output_____
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
Use Naive Bayes algorithm to train models
from sklearn.naive_bayes import GaussianNB nb_model = GaussianNB() nb_model.fit(X_train, y_train.ravel())
_____no_output_____
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
Performance on Training Data
nb_predict_train = nb_model.predict(X_train) from sklearn import metrics print('Accuracy : {0:.4f}'.format(metrics.accuracy_score(y_train, nb_predict_train))) print()
Accuracy : 0.7542
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
Performance on Testing Data
nb_predict_test = nb_model.predict(X_test) print('Accuracy : {0:.4f}'.format(metrics.accuracy_score(y_test, nb_predict_test))) print()
Accuracy : 0.7359
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
Naive Bayes Metrics
print("Confusion Matrix") print("{0}".format(metrics.confusion_matrix(y_test, nb_predict_test))) print("") print("Classification Report") print(metrics.classification_report(y_test, nb_predict_test))
Confusion Matrix [[118 33] [ 28 52]] Classification Report precision recall f1-score support 0 0.81 0.78 0.79 151 1 0.61 0.65 0.63 80 avg / total 0.74 0.74 0.74 231
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
Random Forest
from sklearn.ensemble import RandomForestClassifier rf_model = RandomForestClassifier(random_state=42) rf_model.fit(X_train, y_train.ravel())
_____no_output_____
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
Prediction on Training Data
rf_predict_train = rf_model.predict(X_train) print('Accuracy : {0:.4f}'.format(metrics.accuracy_score(y_train, rf_predict_train))) print()
Accuracy : 0.9870
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
Prediction on Test Data
rf_predict_test = rf_model.predict(X_test) print('Accuracy : {0:.4f}'.format(metrics.accuracy_score(y_test, rf_predict_test))) print()
Accuracy : 0.7100
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
Random Forest Metrics
print("Confusion Matrix") print("{0}".format(metrics.confusion_matrix(y_test, rf_predict_test))) print("") print("Classification Report") print(metrics.classification_report(y_test, rf_predict_test))
Confusion Matrix [[121 30] [ 37 43]] Classification Report precision recall f1-score support 0 0.77 0.80 0.78 151 1 0.59 0.54 0.56 80 avg / total 0.70 0.71 0.71 231
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
Logistic Regression
from sklearn.linear_model import LogisticRegression lr_model = LogisticRegression(C=0.7, random_state=42) lr_model = lr_model.fit(X_train, y_train.ravel()) lr_predict_test = lr_model.predict(X_test) print('Accuracy : {0:.4f}'.format(metrics.accuracy_score(y_test, lr_predict_test))) print()
Accuracy : 0.7446
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
Logistic Regression Metrics
print("Confusion Matrix") print("{0}".format(metrics.confusion_matrix(y_test, lr_predict_test))) print("") print("Classification Report") print(metrics.classification_report(y_test, lr_predict_test))
Confusion Matrix [[128 23] [ 36 44]] Classification Report precision recall f1-score support 0 0.78 0.85 0.81 151 1 0.66 0.55 0.60 80 avg / total 0.74 0.74 0.74 231
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
Regularize
C_start = 0.1 C_end = 5 C_inc = 0.1 C_values, recall_scores = [], [] C_val = C_start best_recall_score = 0 while (C_val < C_end): C_values.append(C_val) lr_model_loop = LogisticRegression(C=C_val, random_state=42, solver='liblinear') lr_model_loop.fit(X_train, y_train.ravel()) lr_predict_loop_test = l...
1st max value of 0.613 occured at C=1.400
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
Logistic Regression with balanced weight class
C_start = 0.1 C_end = 5 C_inc = 0.1 C_values, recall_scores = [], [] C_val = C_start best_recall_score = 0 while (C_val < C_end): C_values.append(C_val) lr_model_loop = LogisticRegression(C=C_val, class_weight="balanced", random_state=42, solver='liblinear', max_iter=10000) lr_model_loop.fit(X_train, y_tr...
Accuracy : 0.7143
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
Metrics
print("Confusion Matrix") print("{0}".format(metrics.confusion_matrix(y_test, lr_predict_test))) print("") print("Classification Report") print(metrics.classification_report(y_test, lr_predict_test)) print(metrics.recall_score(y_test, lr_predict_test))
0.7375
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
Logistic Regression with Cross-Validation
from sklearn.linear_model import LogisticRegressionCV lr_model_cv = LogisticRegressionCV(n_jobs = -1 ,class_weight='balanced',Cs=3,cv=10,refit=False, random_state=42) lr_model_cv.fit(X_train, y_train.ravel()) lr_cv_predict_test = lr_model_cv.predict(X_test) print('Accuracy : {0:.4f}'.format(metrics.accuracy_score(y_...
Accuracy : 0.7013
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
Metrics
print("Confusion Matrix") print("{0}".format(metrics.confusion_matrix(y_test, lr_cv_predict_test))) print("") print("Classification Report") print(metrics.classification_report(y_test, lr_cv_predict_test))
Confusion Matrix [[108 43] [ 26 54]] Classification Report precision recall f1-score support 0 0.81 0.72 0.76 151 1 0.56 0.68 0.61 80 avg / total 0.72 0.70 0.71 231
MIT
code/ML-Pima-Indian-Diabetes-Prediction.ipynb
kimamo/Machine-Learning
send html
def get_smtp(): smtp = smtplib.SMTP('smtp.gmail.com', 587) smtp.ehlo() smtp.starttls() smtp.login('jaykim.asset@gmail.com', pickle.load( open('pw.pickle', 'rb'))) return smtp smtp = get_smtp() smtp msg = MIMEMultipart() #제목 msg['subject'] = 'HTML 전송 테스트' # 내용 part = MIMEText("Html 코드 보내기") msg.att...
_____no_output_____
MIT
2018_06_14_Inclass_Send_Email_SMTP_Google_Email.ipynb
jaykim-asset/datascience_review
Send File
smtp = get_smtp() msg = MIMEMultipart() msg['subject'] = 'Send file test' part = MIMEText('파일 전송 테스트') msg.attach(part) # file attach - pdf file_name = 'asdv.png' maintype, subtype = 'application', 'octet-steam' with open(file_name, 'rb') as fp: part = MIMEBase(maintype, subtype) part.set_payload(fp.read()) # ...
_____no_output_____
MIT
2018_06_14_Inclass_Send_Email_SMTP_Google_Email.ipynb
jaykim-asset/datascience_review
![JohnSnowLabs](https://nlp.johnsnowlabs.com/assets/images/logo.png)[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/streamlit_notebooks/healthcare/NER_LEGAL_DE.ipynb) **Detect legal entities in G...
import os import json from google.colab import files license_keys = files.upload() with open(list(license_keys.keys())[0]) as f: license_keys = json.load(f) sparknlp_version = license_keys["PUBLIC_VERSION"] jsl_version = license_keys["JSL_VERSION"] print ('SparkNLP Version:', sparknlp_version) print ('SparkNLP...
_____no_output_____
Apache-2.0
tutorials/streamlit_notebooks/healthcare/NER_LEGAL_DE.ipynb
hatrungduc/spark-nlp-workshop
Install dependencies
%%capture for k,v in license_keys.items(): %set_env $k=$v !wget https://raw.githubusercontent.com/JohnSnowLabs/spark-nlp-workshop/master/jsl_colab_setup.sh !bash jsl_colab_setup.sh # Install Spark NLP Display for visualization !pip install --ignore-installed spark-nlp-display
_____no_output_____
Apache-2.0
tutorials/streamlit_notebooks/healthcare/NER_LEGAL_DE.ipynb
hatrungduc/spark-nlp-workshop
Import dependencies into Python and start the Spark session
import pandas as pd from pyspark.ml import Pipeline from pyspark.sql import SparkSession import pyspark.sql.functions as F import sparknlp from sparknlp.annotator import * from sparknlp_jsl.annotator import * from sparknlp.base import * import sparknlp_jsl spark = sparknlp_jsl.start(license_keys['SECRET']) # manuall...
_____no_output_____
Apache-2.0
tutorials/streamlit_notebooks/healthcare/NER_LEGAL_DE.ipynb
hatrungduc/spark-nlp-workshop
2. Construct the pipelineFor more details: https://github.com/JohnSnowLabs/spark-nlp-modelspretrained-models---spark-nlp-for-healthcare
document_assembler = DocumentAssembler() \ .setInputCol('text')\ .setOutputCol('document') sentence_detector = SentenceDetector() \ .setInputCols(['document'])\ .setOutputCol('sentence') tokenizer = Tokenizer()\ .setInputCols(['sentence']) \ .setOutputCol('token') # German word embeddings wor...
w2v_cc_300d download started this may take some time. Approximate size to download 1.2 GB [OK!] ner_legal download started this may take some time. Approximate size to download 14.3 MB [OK!]
Apache-2.0
tutorials/streamlit_notebooks/healthcare/NER_LEGAL_DE.ipynb
hatrungduc/spark-nlp-workshop
3. Create example inputs
# Enter examples as strings in this array input_list = [ """Dementsprechend hat der Bundesgerichtshof mit Beschluss vom 24 August 2017 ( - III ZA 15/17 - ) das bei ihm von der Antragstellerin anhängig gemachte „ Prozesskostenhilfeprüfungsverfahre“ an das Bundesarbeitsgericht abgegeben. 2 Die Antragstellerin hat mit...
_____no_output_____
Apache-2.0
tutorials/streamlit_notebooks/healthcare/NER_LEGAL_DE.ipynb
hatrungduc/spark-nlp-workshop
4. Use the pipeline to create outputs
empty_df = spark.createDataFrame([['']]).toDF('text') pipeline_model = nlp_pipeline.fit(empty_df) df = spark.createDataFrame(pd.DataFrame({'text': input_list})) result = pipeline_model.transform(df)
_____no_output_____
Apache-2.0
tutorials/streamlit_notebooks/healthcare/NER_LEGAL_DE.ipynb
hatrungduc/spark-nlp-workshop
5. Visualize results Visualize outputs as data frame
from sparknlp_display import NerVisualizer NerVisualizer().display( result = result.collect()[0], label_col = 'ner_chunk', document_col = 'document' )
_____no_output_____
Apache-2.0
tutorials/streamlit_notebooks/healthcare/NER_LEGAL_DE.ipynb
hatrungduc/spark-nlp-workshop
Pivot table with dynamic plots for COAD
import pandas as pd import numpy as np from pivottablejs import pivot_ui # get data database = "../db/dbCOAD-DRD.csv" df = pd.read_csv(database) df.head() df.columns # use other order of columns df_repurposing = df[['AE', 'HGNC_symbol', 'DrugName', 'ProteinID', 'DrugCID', 'Drug']] df_repurposing #df.to_json(r'all.json'...
_____no_output_____
CC0-1.0
COAD-DRD/scripts/full_pivotTable.ipynb
muntisa/muntisa.github.io
Manually edit the resulted HTML by replacing this part:
<body> <script type="text/javascript"> $(function(){ var derivers = $.pivotUtilities.derivers; var renderers = $.extend($.pivotUtilities.renderers,$.pivotUtilities.plotly_renderers); if(window.location != window.parent.location) $("<a>", {target:"_bl...
_____no_output_____
CC0-1.0
COAD-DRD/scripts/full_pivotTable.ipynb
muntisa/muntisa.github.io
Data Wrangling with Python: Intro to PandasNote: Notebook adapted from [here](https://github.com/EricElmoznino/lighthouse_pandas_tutorial/blob/master/pandas_tutorial.ipynb) & [here](https://github.com/sedv8808/LighthouseLabs/tree/main/W02D2) & from LHL's [21 Day Data Challenge](https://data-challenge.lighthouselabs.ca...
#A dicitonary of lists example students = { 'student_id': [1, 2, 3, 4,5,6], 'name': ['Daenerys', 'Jon', 'Arya', 'Sansa', 'Eddard', 'Khal Drogo'], 'course_mark': [82, 100, 12, 76, 46, 20], 'species': ['cat', 'human', 'cat', 'human', 'human', 'human'] }
_____no_output_____
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
**What are some operations we might want to do on this data?**- 1.Select a subset of columns- 2.Filter out some rows based on an attribute- 3.Group by some attribute- 4.Compute some aggregate values within groups- 5.Save to a fileHow about we try out one of these to see how easy it is Try to return a table with the me...
# Return a table with the mean course mark per-species # Think about a SQL statment where we group by species with the average course mark species_sums = {} #Tables of Sums species_counts = {} #Count per Species for i in range(len(students['species'])): #iterating over the rows species = students['species'][i] #e...
_____no_output_____
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
- Did you like looking at is? Does this look fun to do?- Super Tiring. Pandas Version
# Pandas Version import pandas as pd # Can take in a dictionry of list to instatiate a DataFrame students = pd.DataFrame(students) students species_means = students[['species', 'course_mark']].groupby('species').mean() #species_means = students.groupby('species')['course_mark'].mean() species_means
_____no_output_____
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
Dissecting the above code!
#Step 1: Filter out the columns we want to keep students_filtered = students[['species','course_mark']] students_filtered # Step 2: Group by species column students_grouped_by_species = students_filtered.groupby('species') students_grouped_by_species #Step 3: Specify how to aggregate the course-mark column species_mea...
_____no_output_____
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
As shown, Pandas makes use of vectorized operations. - Rather than use for-loops, we specify the operation that will apply to the structure as a whole (i.e. all the rows)- By vectorizing, **the code becomes more concise and more readable**- Pandas is optimized for vectorized operations (parallel vs. serial computatio...
# One way to construct a Series series = pd.Series([82, 100, 12, 76, 46, 20]) series #We can specify some index when building a series. grades = pd.Series([82, 100, 12, 76, 46, 20], index = ['Daenerys', 'Jon', 'Arya', 'Sansa', 'Eddard', 'Khal Drogo'] ) grades grades['Daenerys'] grades[0] print(...
The values: [ 82 100 12 76 46 20] The indexes: Index(['Daenerys', 'Jon', 'Arya', 'Sansa', 'Eddard', 'Khal Drogo'], dtype='object')
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
**Note:** The underlying index is still 0, 1, 2, 3.... and we can still index on that:
grades[2]
_____no_output_____
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
Pandas DataFrames
# One way to construct a DataFrame df = pd.DataFrame({ 'name': ['Daenerys', 'Jon', 'Arya', 'Sansa'], 'course_mark': [82, 100, 12, 76], 'species': ['human', 'human', 'cat', 'human']}, index=[1412, 94, 9351, 14]) df
_____no_output_____
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
Reading a CSV fileWe'll use the function `read_csv()` to load the data into our notebook- The `read_csv()` function can read data from a locally saved file or from a URL- We'll store the data as a variable `df_pokemon`
df_pokemon = pd.read_csv('pokemon.csv') df_pokemon
_____no_output_____
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
**What do we see here?**- Each row of the table is an observation, containing data of a single pokemon
df_pokemon.shape
_____no_output_____
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
For large DataFrames, it's often useful to display just the first few or last few rows:
#pd.options.display.max_rows = 15 df_pokemon.head(10) df_pokemon.tail(10) #df_pokemon.head?
_____no_output_____
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
> **Pro tip:**> - To display the documentation for this method within Jupyter notebook, you can run the command `df_pokemon.head?` or press `Shift-Tab` within the parentheses of `df_pokemon.head()`> - To see other methods available for the DataFrame, type `df_pokemon.` followed by `Tab` for auto-complete options Data...
#Getting the Columns df_pokemon.columns list_of_column = ['#', 'Name', 'Type 1', 'Type 2', 'Total', 'HP', 'Attack', 'Defense', 'Sp. Atk', 'Sp. Def', 'Speed', 'Generation', 'Legendary'] #Getting Summary Statistics df_pokemon.describe() df_pokemon[["Total","Attack"]].describe() df_pokemon list_columns = ['Name', ...
_____no_output_____
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
The .loc() vs .iloc() methodTo select rows and columns at the same time, we use the syntax `.loc[, ]`:
#Notice the square brackets on loc and the colon df_pokemon.loc[10:20, ['Name']] #Taking a slice of index values # Getting more than one columns df_pokemon.loc[10:14, ['Name',"Legendary",'Attack']] #we can also feed in a list for the rows df_pokemon.loc[[10,14,24,58,238], ['Name',"Legendary",'Attack']] df_pokemon.head...
_____no_output_____
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
Modifying a Column or Creating a new column Give a little description
df_pokemon.head(3) df2 = df_pokemon.copy() #hard copy df2['Total_Attack'] = df2['Attack'] + df2['Sp. Atk'] df2.head(3) df2['Total'] = df2['Total'] * 2 df2['filler'] = True #Modify an orginal #Modify Data Frame with .loc() method df2.loc[1, 'Name'] = 'Andrew'
_____no_output_____
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
Sort_values() & value_counts()1. ***df.sort_values()***2. ***df.value_counts()***The ***pandas.sort_values()*** allows us to reorder our dataframe in an ascending or descending order given a column for pandas to work from. This is similar to the excel sort function.```pythonimport pandas as pddf = pd.read_csv('random....
df2.head(10) another_variable = df2.sort_values(by = 'Total_Attack', ascending = False).head(5) df2.sort_values(by = ['Attack','Defense'], ascending = [True,False]).head(15).to_csv('modified.csv') #Value_Counts #pd.options.display.max_rows = 30 df2['Type 1'].value_counts(ascending = True) df2['Type 1'].value_counts().s...
_____no_output_____
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
How to Query or Filter Data with Conditions?- We can extract specific data from our dataframe based on a specific condition. We will be using the syntax below. Pandas will return a subset of the dataframe based on the given condition. ```pythondf[]```Conditions follow the generic boolean logic in Python. Below is a ch...
#Step 1: Create a filter #the_filter = df_pokemon['Total'] >= 300 the_filter = (df_pokemon['Total'] >= 300) & (df_pokemon['Legendary'] == True) #Step 2: Apply Filter #df_pokemon[the_filter] df_pokemon[(df_pokemon['Total'] >= 300) & (df_pokemon['Legendary'] == True)] #Finding Only Legendary Pokemons
_____no_output_____
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
Grouping and Aggregation Grouping and aggregation can be used to calculate statistics on groups in the data.**Common Aggregation Functions**- mean()- median()- sum()- count()
df = df_pokemon.copy() df.head(2) df[['Type 1','Attack', 'Defense']].groupby('Type 1', as_index = False).mean()
_____no_output_____
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
- By default, `groupby()` assigns the variable that we're grouping on (in this case `Type 1`) to the index of the output data- If we use the keyword argument `as_index=False`, the grouping variable is instead assigned to a regular column - This can be useful in some situations, such as data visualization functions whi...
df[['Type 1','Attack', 'Defense','Legendary']].groupby(['Legendary','Type 1'], as_index = False).mean() #pd.options.display.max_rows = 50
_____no_output_____
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
We can use the `agg` method to compute multiple aggregated statistics on our data, for example minimum and maximum country populations in each region:
df[['Attack','Type 1']].groupby('Type 1').agg(['min','max','mean'])
_____no_output_____
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
We can also use `agg` to compute different statistics for different columns:
agg_dict = { 'Attack': "mean", 'Defense': ['min','max'] } new_df = df[['Attack','Defense','Type 1']].groupby('Type 1').agg(agg_dict) new_df.reset_index()
_____no_output_____
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
Challenge 1 (10 minutes)Let's play around with Pandas on a more intricate dataset: a dataset on wines!**Challenge 14 from the 21 Day Data Challenge** Dot's neighbour said that he only likes wine from Stellenbosch, Bordeaux, and the Okanagan Valley, and that the sulfates can't be that high. The problem is, Dot can't re...
#Write your Code Below import pandas as pd df = pd.read_csv('winequality-red_2.csv') df = df.drop(columns = ['Unnamed: 0']) df.head() #Solutions #Q1 df['region'].value_counts() #Q2 filter_sulhpates = df['sulphates'] <= 0.6 filtered_df = df[filter_sulhpates] filter_quality = filtered_df['price'] < 20 filtered_...
<ipython-input-121-7543189bff1f>:3: UserWarning: Boolean Series key will be reindexed to match DataFrame index. filtered_df = filtered_df[filter_region]
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
Challenge 2 (25 minutes)**Challenge 21 from the 21DDC (Adapted)**Dot wants to play retro video games with all their new friends! Help them figure out which games would be best.Questions: 1. What is the top 5 best selling games released before the year 2000. - **Note**: Use Global_Sales 2. Create a new ...
df = pd.read_csv('video_games.csv') df.head(5) #Solution Q1 best_selling_2000_filter = df["Year_of_Release"] < 2000 best_selling_2000 = df[best_selling_2000_filter] best_selling_2000.head(5) #Solution Q2 #Step 1: Fill in missing values with the median #Columns with missing values Critic_Count and User_Count df['Crit...
_____no_output_____
MIT
w2/w2-Day_2/W2D2-Pandas-21-09-21/.ipynb_checkpoints/Intro_to_Pandas_Student_COPY-filled-checkpoint.ipynb
bmskarate/lighthouseMain
Mask R-CNN DemoA quick intro to using the pre-trained model to detect and segment objects.
import os import sys import random import math import numpy as np import skimage.io import matplotlib import matplotlib.pyplot as plt # Root directory of the project ROOT_DIR = os.path.abspath("../") # Import Mask RCNN sys.path.append(ROOT_DIR) # To find local version of the library from mrcnn import utils import mr...
C:\Users\zlv\Anaconda3\envs\test\lib\site-packages\tensorflow\python\framework\dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) C:\Users\zlv\Ana...
MIT
samples/demo.ipynb
MirandaLv/Mask_RCNN
ConfigurationsWe'll be using a model trained on the MS-COCO dataset. The configurations of this model are in the ```CocoConfig``` class in ```coco.py```.For inferencing, modify the configurations a bit to fit the task. To do so, sub-class the ```CocoConfig``` class and override the attributes you need to change.
class InferenceConfig(coco.CocoConfig): # Set batch size to 1 since we'll be running inference on # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU GPU_COUNT = 1 IMAGES_PER_GPU = 1 config = InferenceConfig() config.display()
Configurations: BACKBONE resnet101 BACKBONE_STRIDES [4, 8, 16, 32, 64] BATCH_SIZE 1 BBOX_STD_DEV [0.1 0.1 0.2 0.2] COMPUTE_BACKBONE_SHAPE None DETECTION_MAX_INSTANCES 100 DETECTION_MIN_CONFIDENCE 0.7 DETECTION_NMS_THRESHOLD ...
MIT
samples/demo.ipynb
MirandaLv/Mask_RCNN
Create Model and Load Trained Weights
# Create model object in inference mode. model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config) # Load weights trained on MS-COCO model.load_weights(COCO_MODEL_PATH, by_name=True)
WARNING:tensorflow:From C:\Users\zlv\Anaconda3\envs\test\lib\site-packages\tensorflow\python\framework\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Colocations handled automatically by placer. WARNING:tensor...
MIT
samples/demo.ipynb
MirandaLv/Mask_RCNN
Class NamesThe model classifies objects and returns class IDs, which are integer value that identify each class. Some datasets assign integer values to their classes and some don't. For example, in the MS-COCO dataset, the 'person' class is 1 and 'teddy bear' is 88. The IDs are often sequential, but not always. The CO...
# COCO Class names # Index of the class in the list is its ID. For example, to get ID of # the teddy bear class, use: class_names.index('teddy bear') class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant',...
_____no_output_____
MIT
samples/demo.ipynb
MirandaLv/Mask_RCNN
Run Object Detection
# Load a random image from the images folder file_names = next(os.walk(IMAGE_DIR))[2] image = skimage.io.imread(os.path.join(IMAGE_DIR, random.choice(file_names))) # Run detection results = model.detect([image], verbose=1) # Visualize results r = results[0] visualize.display_instances(image, r['rois'], r['masks'], r[...
_____no_output_____
MIT
samples/demo.ipynb
MirandaLv/Mask_RCNN
BFS
# import packages import numpy as np import numpy.linalg as la np.set_printoptions(suppress=True) import itertools A = np.array([[1.,1,1,0], [2.,1,0,1]]) b = np.array([40,60]) bv = [0,1] bs = la.solve(A[:,bv], b) print(f'bv is {bv} and bs is {bs}')
_____no_output_____
MIT
src/bfs.ipynb
songqsh/MA2210
Creating a Sentiment Analysis Web App Using PyTorch and SageMaker_Deep Learning Nanodegree Program | Deployment_---Now that we have a basic understanding of how SageMaker works we will try to use it to construct a complete project from end to end. Our goal will be to have a simple web page which a user can use to ente...
%mkdir ../data !wget -O ../data/aclImdb_v1.tar.gz http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz !tar -zxf ../data/aclImdb_v1.tar.gz -C ../data
mkdir: cannot create directory ‘../data’: File exists --2019-10-30 08:54:14-- http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz Resolving ai.stanford.edu (ai.stanford.edu)... 171.64.68.10 Connecting to ai.stanford.edu (ai.stanford.edu)|171.64.68.10|:80... connected. HTTP request sent, awaiting response......
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
Step 2: Preparing and Processing the dataAlso, as in the XGBoost notebook, we will be doing some initial data processing. The first few steps are the same as in the XGBoost example. To begin with, we will read in each of the reviews and combine them into a single input structure. Then, we will split the dataset into a...
import os import glob def read_imdb_data(data_dir='../data/aclImdb'): data = {} labels = {} for data_type in ['train', 'test']: data[data_type] = {} labels[data_type] = {} for sentiment in ['pos', 'neg']: data[data_type][sentiment] = [] labels[da...
IMDB reviews: train = 12500 pos / 12500 neg, test = 12500 pos / 12500 neg
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
Now that we've read the raw training and testing data from the downloaded dataset, we will combine the positive and negative reviews and shuffle the resulting records.
from sklearn.utils import shuffle def prepare_imdb_data(data, labels): """Prepare training and test sets from IMDb movie reviews.""" #Combine positive and negative reviews and labels data_train = data['train']['pos'] + data['train']['neg'] data_test = data['test']['pos'] + data['test']['neg'] l...
IMDb reviews (combined): train = 25000, test = 25000
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
Now that we have our training and testing sets unified and prepared, we should do a quick check and see an example of the data our model will be trained on. This is generally a good idea as it allows you to see how each of the further processing steps affects the reviews and it also ensures that the data has been loade...
print(train_X[100]) print(train_y[100])
I am very disappointed with "K-911." The original "good" quality of "K-9" doesn't exist any more. This is more like a sitcom! Some of casts from original movie returned and got some of my memory back. The captain of Dooley now loves to hit him like a scene from old comedy show. That was crazy. What's the deal with the ...
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
The first step in processing the reviews is to make sure that any html tags that appear should be removed. In addition we wish to tokenize our input, that way words such as *entertained* and *entertaining* are considered the same with regard to sentiment analysis.
import nltk from nltk.corpus import stopwords from nltk.stem.porter import * import re from bs4 import BeautifulSoup def review_to_words(review): nltk.download("stopwords", quiet=True) stemmer = PorterStemmer() text = BeautifulSoup(review, "html.parser").get_text() # Remove HTML tags text = re.sub...
_____no_output_____
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
The `review_to_words` method defined above uses `BeautifulSoup` to remove any html tags that appear and uses the `nltk` package to tokenize the reviews. As a check to ensure we know how everything is working, try applying `review_to_words` to one of the reviews in the training set.
# TODO: Apply review_to_words to a review (train_X[100] or any other review) review_to_words(train_X[100])
_____no_output_____
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
**Question:** Above we mentioned that `review_to_words` method removes html formatting and allows us to tokenize the words found in a review, for example, converting *entertained* and *entertaining* into *entertain* so that they are treated as though they are the same word. What else, if anything, does this method do t...
import pickle cache_dir = os.path.join("../cache", "sentiment_analysis") # where to store cache files os.makedirs(cache_dir, exist_ok=True) # ensure cache directory exists def preprocess_data(data_train, data_test, labels_train, labels_test, cache_dir=cache_dir, cache_file="preprocessed_data.pkl")...
Read preprocessed data from cache file: preprocessed_data.pkl
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
Transform the dataIn the XGBoost notebook we transformed the data from its word representation to a bag-of-words feature representation. For the model we are going to construct in this notebook we will construct a feature representation which is very similar. To start, we will represent each word as an integer. Of cou...
import numpy as np from collections import Counter,OrderedDict import operator def build_dict(data, vocab_size = 5000): """Construct and return a dictionary mapping each of the most frequently appearing words to a unique integer.""" # TODO: Determine how often each word appears in `data`. Note that `data` ...
_____no_output_____
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
**Question:** What are the five most frequently appearing (tokenized) words in the training set? Does it makes sense that these words appear frequently in the training set? **Answer:** [movi,film,one,like,time] are the most frequently apprearing words in the training set. This makes sense as the reviews are about movie...
# TODO: Use this space to determine the five most frequently appearing words in the training set. temp_data = np.concatenate(train_X,axis=0) word_counter = Counter(temp_data) word_count = dict(word_counter) sorted(word_count.items(), key=lambda x: x[1], reverse=True)[0:5]
_____no_output_____
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
Save `word_dict`Later on when we construct an endpoint which processes a submitted review we will need to make use of the `word_dict` which we have created. As such, we will save it to a file now for future use.
data_dir = '../data/pytorch' # The folder we will use for storing data if not os.path.exists(data_dir): # Make sure that the folder exists os.makedirs(data_dir) with open(os.path.join(data_dir, 'word_dict.pkl'), "wb") as f: pickle.dump(word_dict, f)
_____no_output_____
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
Transform the reviewsNow that we have our word dictionary which allows us to transform the words appearing in the reviews into integers, it is time to make use of it and convert our reviews to their integer sequence representation, making sure to pad or truncate to a fixed length, which in our case is `500`.
def convert_and_pad(word_dict, sentence, pad=500): NOWORD = 0 # We will use 0 to represent the 'no word' category INFREQ = 1 # and we use 1 to represent the infrequent words, i.e., words not appearing in word_dict working_sentence = [NOWORD] * pad for word_index, word in enumerate(sentence[:pa...
_____no_output_____
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
As a quick check to make sure that things are working as intended, check to see what one of the reviews in the training set looks like after having been processeed. Does this look reasonable? What is the length of a review in the training set?
# Use this cell to examine one of the processed reviews to make sure everything is working as intended. train_X[0]
_____no_output_____
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
**Question:** In the cells above we use the `preprocess_data` and `convert_and_pad_data` methods to process both the training and testing set. Why or why not might this be a problem? **Answer:** Since the word dictionary of the most frequently used words is built based on the training data, it's considered a form of le...
import pandas as pd pd.concat([pd.DataFrame(train_y), pd.DataFrame(train_X_len), pd.DataFrame(train_X)], axis=1) \ .to_csv(os.path.join(data_dir, 'train.csv'), header=False, index=False)
_____no_output_____
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
Uploading the training dataNext, we need to upload the training data to the SageMaker default S3 bucket so that we can provide access to it while training our model.
import sagemaker sagemaker_session = sagemaker.Session() bucket = sagemaker_session.default_bucket() prefix = 'sagemaker/sentiment_rnn' role = sagemaker.get_execution_role() input_data = sagemaker_session.upload_data(path=data_dir, bucket=bucket, key_prefix=prefix)
_____no_output_____
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
**NOTE:** The cell above uploads the entire contents of our data directory. This includes the `word_dict.pkl` file. This is fortunate as we will need this later on when we create an endpoint that accepts an arbitrary review. For now, we will just take note of the fact that it resides in the data directory (and so also ...
!pygmentize train/model.py
import torch.nn as nn class LSTMClassifier(nn.Module): """  This is the simple RNN model we will be using to perform Sentiment Analysis.  """ ...
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
The important takeaway from the implementation provided is that there are three parameters that we may wish to tweak to improve the performance of our model. These are the embedding dimension, the hidden dimension and the size of the vocabulary. We will likely want to make these parameters configurable in the training ...
import torch import torch.utils.data # Read in only the first 250 rows train_sample = pd.read_csv(os.path.join(data_dir, 'train.csv'), header=None, names=None, nrows=250) # Turn the input pandas dataframe into tensors train_sample_y = torch.from_numpy(train_sample[[0]].values).float().squeeze() train_sample_X = torch....
_____no_output_____
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
(TODO) Writing the training methodNext we need to write the training code itself. This should be very similar to training methods that you have written before to train PyTorch models. We will leave any difficult aspects such as model saving / loading and parameter loading until a little later.
def train(model, train_loader, epochs, optimizer, loss_fn, device): for epoch in range(1, epochs + 1): model.train() total_loss = 0 for batch in train_loader: batch_X, batch_y = batch batch_X = batch_X.to(device) batch_y = batch_y.to(...
_____no_output_____
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
Supposing we have the training method above, we will test that it is working by writing a bit of code in the notebook that executes our training method on the small sample training set that we loaded earlier. The reason for doing this in the notebook is so that we have an opportunity to fix any errors that arise early ...
import torch.optim as optim from train.model import LSTMClassifier device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = LSTMClassifier(32, 100, 5000).to(device) optimizer = optim.Adam(model.parameters()) loss_fn = torch.nn.BCELoss() train(model, train_sample_dl, 5, optimizer, loss_fn, device)
Epoch: 1, BCELoss: 0.6868077039718627 Epoch: 2, BCELoss: 0.6752514839172363 Epoch: 3, BCELoss: 0.664816963672638 Epoch: 4, BCELoss: 0.6535287261009216 Epoch: 5, BCELoss: 0.6402966618537903
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project