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
RecordID (a unique integer for each ICU stay)Age (years)Gender (0: female, or 1: male)Height (cm)ICUType (1: Coronary Care Unit, 2: Cardiac Surgery Recovery Unit, 3: Medical ICU, or 4: Surgical ICU)Weight (kg) Variables Description ALB Albumin (g/dL) ALP Alkaline phosphatase (IU/L) ALT Alanine transaminase (IU/L) AST A...
# Open file with open('./training_set_a/132539.txt') as inputfile: results = list(csv.reader(inputfile)) # Open file in list of list results = pd.DataFrame(results[1:],columns=results[0]) # Convert list of list to DataFrame results.Value = results.Value.astype(float) # Change Value t...
_____no_output_____
CC-BY-3.0
__Project Files/.ipynb_checkpoints/Data Cleaning_merge all data together_backup-checkpoint.ipynb
joannasys/Predictions-of-ICU-Mortality
EDA 1. Check if the data is unbalanced
# Open outcomes file with open('./training_outcomes_a.txt') as outcomefile: # Open file in list of list outcome = list(csv.reader(outcomefile)) outcome = pd.DataFrame(outcome[1:],columns=outcome[0]) # Convert list of list to DataFrame outcome = outcome.astype(float,'ignore') # Change value...
percentage of 0 in dataset: 86.15 % percentage of 1 in dataset: 13.85 %
CC-BY-3.0
__Project Files/.ipynb_checkpoints/Data Cleaning_merge all data together_backup-checkpoint.ipynb
joannasys/Predictions-of-ICU-Mortality
2. Create outcomes table in database
outcome.head(5) pd.to_sql()
_____no_output_____
CC-BY-3.0
__Project Files/.ipynb_checkpoints/Data Cleaning_merge all data together_backup-checkpoint.ipynb
joannasys/Predictions-of-ICU-Mortality
Copyright 2018 The TensorFlow Authors.Licensed under the Apache License, Version 2.0 (the "License"). Neural Machine Translation with Attention Run in Google Colab View source on GitHub This notebook trains a sequence to sequence (seq2seq) model for Spanish to English translation using [tf.keras](https://www.tenso...
from __future__ import absolute_import, division, print_function # Import TensorFlow >= 1.9 and enable eager execution import tensorflow as tf tf.enable_eager_execution() import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split import unicodedata import re import numpy as np import os im...
_____no_output_____
Apache-2.0
notebooks/eager/nmt_w_attention.ipynb
cnodadiaz/tf-workshop
Download and prepare the datasetWe'll use a language dataset provided by http://www.manythings.org/anki/. This dataset contains language translation pairs in the format:```May I borrow this book? ¿Puedo tomar prestado este libro?```There are a variety of languages available, but we'll use the English-Spanish dataset. ...
# Download the file path_to_zip = tf.keras.utils.get_file( 'spa-eng.zip', origin='http://download.tensorflow.org/data/spa-eng.zip', extract=True) path_to_file = os.path.dirname(path_to_zip)+"/spa-eng/spa.txt" # Converts the unicode file to ascii def unicode_to_ascii(s): return ''.join(c for c in unicodeda...
_____no_output_____
Apache-2.0
notebooks/eager/nmt_w_attention.ipynb
cnodadiaz/tf-workshop
Limit the size of the dataset to experiment faster (optional)Training on the complete dataset of >100,000 sentences will take a long time. To train faster, we can limit the size of the dataset to 30,000 sentences (of course, translation quality degrades with less data):
# Try experimenting with the size of that dataset num_examples = 30000 input_tensor, target_tensor, inp_lang, targ_lang, max_length_inp, max_length_targ = load_dataset(path_to_file, num_examples) # Creating training and validation sets using an 80-20 split input_tensor_train, input_tensor_val, target_tensor_train, targ...
_____no_output_____
Apache-2.0
notebooks/eager/nmt_w_attention.ipynb
cnodadiaz/tf-workshop
Create a tf.data dataset
BUFFER_SIZE = len(input_tensor_train) BATCH_SIZE = 64 N_BATCH = BUFFER_SIZE//BATCH_SIZE embedding_dim = 256 units = 1024 vocab_inp_size = len(inp_lang.word2idx) vocab_tar_size = len(targ_lang.word2idx) dataset = tf.data.Dataset.from_tensor_slices((input_tensor_train, target_tensor_train)).shuffle(BUFFER_SIZE) dataset ...
_____no_output_____
Apache-2.0
notebooks/eager/nmt_w_attention.ipynb
cnodadiaz/tf-workshop
Write the encoder and decoder modelHere, we'll implement an encoder-decoder model with attention which you can read about in the TensorFlow [Neural Machine Translation (seq2seq) tutorial](https://www.tensorflow.org/tutorials/seq2seq). This example uses a more recent set of APIs. This notebook implements the [attention...
def gru(units): # If you have a GPU, we recommend using CuDNNGRU(provides a 3x speedup than GRU) # the code automatically does that. if tf.test.is_gpu_available(): return tf.keras.layers.CuDNNGRU(units, return_sequences=True, return_sta...
_____no_output_____
Apache-2.0
notebooks/eager/nmt_w_attention.ipynb
cnodadiaz/tf-workshop
Define the optimizer and the loss function
optimizer = tf.train.AdamOptimizer() def loss_function(real, pred): mask = 1 - np.equal(real, 0) loss_ = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=real, logits=pred) * mask return tf.reduce_mean(loss_)
_____no_output_____
Apache-2.0
notebooks/eager/nmt_w_attention.ipynb
cnodadiaz/tf-workshop
Training1. Pass the *input* through the *encoder* which return *encoder output* and the *encoder hidden state*.2. The encoder output, encoder hidden state and the decoder input (which is the *start token*) is passed to the decoder.3. The decoder returns the *predictions* and the *decoder hidden state*.4. The decoder h...
EPOCHS = 10 for epoch in range(EPOCHS): start = time.time() hidden = encoder.initialize_hidden_state() total_loss = 0 for (batch, (inp, targ)) in enumerate(dataset): loss = 0 with tf.GradientTape() as tape: enc_output, enc_hidden = encoder(inp, hidden) ...
_____no_output_____
Apache-2.0
notebooks/eager/nmt_w_attention.ipynb
cnodadiaz/tf-workshop
Translate* The evaluate function is similar to the training loop, except we don't use *teacher forcing* here. The input to the decoder at each time step is its previous predictions along with the hidden state and the encoder output.* Stop predicting when the model predicts the *end token*.* And store the *attention we...
def evaluate(sentence, encoder, decoder, inp_lang, targ_lang, max_length_inp, max_length_targ): attention_plot = np.zeros((max_length_targ, max_length_inp)) sentence = preprocess_sentence(sentence) inputs = [inp_lang.word2idx[i] for i in sentence.split(' ')] inputs = tf.keras.preprocessing.sequenc...
_____no_output_____
Apache-2.0
notebooks/eager/nmt_w_attention.ipynb
cnodadiaz/tf-workshop
Job parameters
BUCKET="tanmcrae-greengrass-blog" bucket_region = s3.head_bucket(Bucket=BUCKET)['ResponseMetadata']['HTTPHeaders']['x-amz-bucket-region'] assert bucket_region == region, "Your S3 bucket {} and this notebook need to be in the same region.".format(BUCKET) MANIFEST = "blue_box_large_job.json" JOB_NAME = "blue-box-large-jo...
_____no_output_____
MIT-0
data-prep/04_create_ground_truth_job.ipynb
jonslo/amazon-sagemaker-aws-greengrass-custom-object-detection-model
specifying categories
CLASS_NAME = "storage box" CLASS_LIST = [CLASS_NAME] print("Label space is {}".format(CLASS_LIST)) json_body = { 'labels': [{'label': label} for label in CLASS_LIST] } with open('class_labels.json', 'w') as f: json.dump(json_body, f) LABEL_KEY = "ground-truth/{}/class_labels.json".format(EXP_NAME) s3.upload_f...
Label space is ['storage box'] uploaded s3://tanmcrae-greengrass-blog/ground-truth/blue-box/class_labels.json
MIT-0
data-prep/04_create_ground_truth_job.ipynb
jonslo/amazon-sagemaker-aws-greengrass-custom-object-detection-model
Create the instruction template
def make_template(test_template=False, save_fname='instructions.template'): template = r"""<script src="https://assets.crowd.aws/crowd-html-elements.js"></script> <crowd-form> <crowd-bounding-box name="boundingBox" src="{{ task.input.taskObject | grant_read_access }}" header="Draw bounding box for th...
_____no_output_____
MIT-0
data-prep/04_create_ground_truth_job.ipynb
jonslo/amazon-sagemaker-aws-greengrass-custom-object-detection-model
Create job
task_description = 'Dear Annotator, please draw a box around the yellow or blue storage box in the picture. Thank you!' task_keywords = ['image', 'object', 'detection', CLASS_NAME] task_title = 'Draw a box around storage box in the picture' print("task_title: {}".format(task_title)) print("JOB_NAME: {}".format(JOB_NAM...
_____no_output_____
MIT-0
data-prep/04_create_ground_truth_job.ipynb
jonslo/amazon-sagemaker-aws-greengrass-custom-object-detection-model
look at output manifest
job_name = 'yellow-box-small-job-public' OUTPUT_MANIFEST = 's3://{}/ground-truth-output/{}/manifests/output/output.manifest'.format(BUCKET, job_name) output_file = job_name+'.output.manifest' !aws s3 cp {OUTPUT_MANIFEST} {output_file} with open(output_file, 'r') as f: output = [json.loads(line.strip()) for line in...
_____no_output_____
MIT-0
data-prep/04_create_ground_truth_job.ipynb
jonslo/amazon-sagemaker-aws-greengrass-custom-object-detection-model
synchro.io> IO classes to read files in the different format Asari lab is acquiring from: hdf5, rhd, raw, npy, all adapted from the SpykingCircus project by Pierre Yger and Olivier Marre https://spyking-circus.readthedocs.io/en/latest/
#export import numpy as np import re, sys, os, logging, struct import h5py from colorama import Fore logger = logging.getLogger(__name__) def atoi(text): return int(text) if text.isdigit() else text def natural_keys(text): ''' alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com...
Converted 00_core.ipynb. Converted 01_utils.ipynb. Converted 02_processing.ipynb. Converted 03_modelling.ipynb. Converted 04_plotting.ipynb. Converted 05_database.ipynb. Converted 06_eyetrack.ipynb. Converted 10_synchro.io.ipynb. Converted 11_synchro.extracting.ipynb. Converted 12_synchro.processing.ipynb. Converted 13...
Apache-2.0
10_synchro.io.ipynb
wiessall/theonerig
Visit the NASA mars news site
# Visit the Mars news site url = 'https://redplanetscience.com/' browser.visit(url) # Optional delay for loading the page browser.is_element_present_by_css('div.list_text', wait_time=1) # Convert the browser html to a soup object html = browser.html news_soup = soup(html, 'html.parser') slide_elem = news_soup.select_...
_____no_output_____
ADSL
Mission_to_Mars-Starter.ipynb
ptlhrs7/Web-Scraping-and-Mongo-Homework
JPL Space Images Featured Image
# Visit URL url = 'https://spaceimages-mars.com' browser.visit(url) # Find and click the full image button full_image_link = browser.find_by_tag('button')[1] full_image_link.click() # Parse the resulting html with soup html = browser.html img_soup = soup(html, 'html.parser') #print(news_soup.prettify()) img_url_rel = i...
_____no_output_____
ADSL
Mission_to_Mars-Starter.ipynb
ptlhrs7/Web-Scraping-and-Mongo-Homework
Mars Facts
# Use `pd.read_html` to pull the data from the Mars-Earth Comparison section # hint use index 0 to find the table df = pd.read_html("https://galaxyfacts-mars.com/")[0] df.head() df.columns = ['Description', 'Mars', 'Earth'] df df.set_index('Description', inplace=True) df.to_html()
_____no_output_____
ADSL
Mission_to_Mars-Starter.ipynb
ptlhrs7/Web-Scraping-and-Mongo-Homework
Hemispheres
url = 'https://marshemispheres.com/' browser.visit(url) # Create a list to hold the images and titles. hemisphere_image_urls = [] # Get a list of all of the hemispheres links = browser.find_by_css('a.product-item img') # Next, loop through those links, click the link, find the sample anchor, return the href for i ...
_____no_output_____
ADSL
Mission_to_Mars-Starter.ipynb
ptlhrs7/Web-Scraping-and-Mongo-Homework
FactRuEval example (Cased model), MutiHeadAttention
%reload_ext autoreload %autoreload 2 %matplotlib inline import warnings import sys sys.path.append("../") warnings.filterwarnings("ignore") import os data_path = "/home/lis/ner/ulmfit/data/factrueval/" train_path = os.path.join(data_path, "train_with_pos.csv") valid_path = os.path.join(data_path, "valid_with_pos.c...
_____no_output_____
MIT
examples/factrueval.ipynb
sloth2012/ner-bert
1. Create dataloaders
from modules import BertNerData as NerData data = NerData.create(train_path, valid_path, vocab_file)
_____no_output_____
MIT
examples/factrueval.ipynb
sloth2012/ner-bert
For factrueval we use the following sample of labels:
print(data.label2idx)
{'<pad>': 0, '[CLS]': 1, '[SEP]': 2, 'B_O': 3, 'I_O': 4, 'B_ORG': 5, 'I_ORG': 6, 'B_LOC': 7, 'I_LOC': 8, 'B_PER': 9, 'I_PER': 10}
MIT
examples/factrueval.ipynb
sloth2012/ner-bert
2. Create modelFor creating pytorch model we need to create `NerModel` object.
from modules.models.bert_models import BertBiLSTMAttnCRF model = BertBiLSTMAttnCRF.create(len(data.label2idx), bert_config_file, init_checkpoint_pt, enc_hidden_dim=256) model.decoder model.get_n_trainable_params()
_____no_output_____
MIT
examples/factrueval.ipynb
sloth2012/ner-bert
3. Create learnerFor training our pytorch model we need to create `NerLearner` object.
from modules import NerLearner num_epochs = 100 learner = NerLearner(model, data, best_model_path="/datadrive/models/factrueval/exp_final_attn_cased1.cpt", lr=0.001, clip=1.0, sup_labels=data.id2label[5:], t_total=num_epochs * len(data.train_dl))
_____no_output_____
MIT
examples/factrueval.ipynb
sloth2012/ner-bert
4. Learn your NER modelCall `learner.fit`
learner.fit(num_epochs, target_metric='f1')
_____no_output_____
MIT
examples/factrueval.ipynb
sloth2012/ner-bert
5. EvaluateCreate new data loader from existing path.
from modules.data.bert_data import get_bert_data_loader_for_predict dl = get_bert_data_loader_for_predict(data_path + "valid.csv", learner) learner.load_model() preds = learner.predict(dl)
_____no_output_____
MIT
examples/factrueval.ipynb
sloth2012/ner-bert
IOB precision
from modules.train.train import validate_step print(validate_step(learner.data.valid_dl, learner.model, learner.data.id2label, learner.sup_labels))
_____no_output_____
MIT
examples/factrueval.ipynb
sloth2012/ner-bert
Tokens report
from sklearn_crfsuite.metrics import flat_classification_report from modules.utils.utils import bert_labels2tokens pred_tokens, pred_labels = bert_labels2tokens(dl, preds) true_tokens, true_labels = bert_labels2tokens(dl, [x.labels for x in dl.dataset]) assert pred_tokens == true_tokens tokens_report = flat_classificat...
_____no_output_____
MIT
examples/factrueval.ipynb
sloth2012/ner-bert
Span precision
from modules.utils.utils import voting_choicer print(get_bert_span_report(dl, preds, fn=voting_choicer))
precision recall f1-score support ORG 0.809 0.834 0.821 259 LOC 0.851 0.859 0.855 192 PER 0.936 0.936 0.936 188 micro avg 0.858 0.872 0.865 639 macro avg 0.865 0.877 0.871 ...
MIT
examples/factrueval.ipynb
sloth2012/ner-bert
6. Get mean and stdv on 10 runs
from modules.utils.plot_metrics import * num_runs = 10 best_reports = [] try: for i in range(num_runs): model = BertBiLSTMAttnCRF.create(len(data.label2idx), bert_config_file, init_checkpoint_pt, enc_hidden_dim=256) best_model_path = "/datadrive/models/factrueval/exp_{}_attn_cased.cpt".format(i) ...
_____no_output_____
MIT
examples/factrueval.ipynb
sloth2012/ner-bert
f1 Mean and std
np.mean([get_mean_max_metric([r]) for r in best_reports]), np.round(np.std([get_mean_max_metric([r]) for r in best_reports]), 3)
_____no_output_____
MIT
examples/factrueval.ipynb
sloth2012/ner-bert
Best
get_mean_max_metric(best_reports)
_____no_output_____
MIT
examples/factrueval.ipynb
sloth2012/ner-bert
precision Mean and std
np.mean([get_mean_max_metric([r], "prec") for r in best_reports]), np.round(np.std([get_mean_max_metric([r], "prec") for r in best_reports]), 3)
_____no_output_____
MIT
examples/factrueval.ipynb
sloth2012/ner-bert
Best
get_mean_max_metric(best_reports, "prec")
_____no_output_____
MIT
examples/factrueval.ipynb
sloth2012/ner-bert
NLP_Session_2_AmazonReviews_Example Amazon Review Polarity Dataset DOWNLOAD DATA FROM HEREhttps://www.kaggle.com/kritanjalijain/amazon-reviews/download Extract the train and test CSV files to your google drive location and configure that in the code OVERVIEWContains 34,686,770 Amazon reviews from 6,643,669 users on 2,...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import tarfile import seaborn as sns import matplotlib.style as style import matplotlib as mpl import re import string import itertools import collections from wordcloud import WordCloud import nltk from nltk.util import ngrams from nltk.corpus im...
_____no_output_____
MIT
AmazonReviews_Example/NLP_Session_2_AmazonReviews_Example.ipynb
drshyamsundaram/nlp
Setting up NLP Libraries and corpus
nltk.download('stopwords') nltk.download('punkt') nltk.download('averaged_perceptron_tagger')
[nltk_data] Downloading package stopwords to /root/nltk_data... [nltk_data] Package stopwords is already up-to-date! [nltk_data] Downloading package punkt to /root/nltk_data... [nltk_data] Package punkt is already up-to-date! [nltk_data] Downloading package averaged_perceptron_tagger to [nltk_data] /root/nltk_d...
MIT
AmazonReviews_Example/NLP_Session_2_AmazonReviews_Example.ipynb
drshyamsundaram/nlp
Mounting the data source
from google.colab import drive drive.mount('/content/drive',force_remount=True)
Mounted at /content/drive
MIT
AmazonReviews_Example/NLP_Session_2_AmazonReviews_Example.ipynb
drshyamsundaram/nlp
Configuring the input, output and process folders
# Model Input and output folders # Setup in Google drive # '/content/drive/MyDrive/yourlocation/input/' model_input_folder='/content/drive/MyDrive/yourlocation/input/' model_output_folder='/content/drive/MyDrive/yourlocation/output/' input_train_file=model_input_folder+'train.csv' input_test_file=model_input_folder+'te...
_____no_output_____
MIT
AmazonReviews_Example/NLP_Session_2_AmazonReviews_Example.ipynb
drshyamsundaram/nlp
Loading the training dataset
# check out what the data looks like before you get started # look at the training data set train_df = pd.read_csv(input_train_file, header=None) print(train_df.head()) train_df.shape
_____no_output_____
MIT
AmazonReviews_Example/NLP_Session_2_AmazonReviews_Example.ipynb
drshyamsundaram/nlp
Reducing the size of the dataframe for demonstration purposes
# Reducing the size of the dataframe train_df=train_df.loc[1:10000] for col in train_df.columns: print(col) #checking a null values train_df.isnull().sum() #droping null vlaues train_df.dropna() train_df.isnull().count()
_____no_output_____
MIT
AmazonReviews_Example/NLP_Session_2_AmazonReviews_Example.ipynb
drshyamsundaram/nlp
Quick look at the dataset loaded
train_df.info() train_df.drop([0],axis=1,inplace=True) for col in train_df.columns: print(col) train_df.drop([1],axis=1,inplace=True) train_df.shape train_df.sample(5) # Checking for Null Values train_df[train_df[2].isnull()]
_____no_output_____
MIT
AmazonReviews_Example/NLP_Session_2_AmazonReviews_Example.ipynb
drshyamsundaram/nlp
Obtaining the review lengths
train = train_df.copy() train[2].apply(str) train["review_length"] = train[2].apply(lambda w : len(re.findall(r'\w+', w)))
_____no_output_____
MIT
AmazonReviews_Example/NLP_Session_2_AmazonReviews_Example.ipynb
drshyamsundaram/nlp
Getting some statistics around the review length
train['review_length'].describe()
_____no_output_____
MIT
AmazonReviews_Example/NLP_Session_2_AmazonReviews_Example.ipynb
drshyamsundaram/nlp
Doing some graphical plots
sns.boxplot(data = train , x="review_length") plt.xlabel('Number of Words') plt.title('Review Length, Including Stop Words') plt.show() sns.distplot(train['review_length'], kde = False) plt.xlabel('Distribution of Review Length') plt.title('Review Length, Including Stop Words') plt.show()
/usr/local/lib/python3.7/dist-packages/seaborn/distributions.py:2619: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms). war...
MIT
AmazonReviews_Example/NLP_Session_2_AmazonReviews_Example.ipynb
drshyamsundaram/nlp
If we want to do better we must pre-process data like1. Converting to lower case2. Removing punctuation3. Removing Numbers4. Removing trailing spaces5. Removing extra whitespaces
train_clean = train.copy() stop_words = stopwords.words("english")
_____no_output_____
MIT
AmazonReviews_Example/NLP_Session_2_AmazonReviews_Example.ipynb
drshyamsundaram/nlp
Function to clean text
# Function for cleaning text def clean(s): s = s.lower() #Converting to lower case s = re.sub(r'[^\w\s]', ' ', s) #Removing punctuation s = re.sub(r'[\d+]', ' ', s) #Removing Numbers s = s.strip() #Removing trailing spaces s = re.sub(' +', ' ', s) #Remo...
_____no_output_____
MIT
AmazonReviews_Example/NLP_Session_2_AmazonReviews_Example.ipynb
drshyamsundaram/nlp
1. Removal of STOP WORDS
# Removal of Stop Words train_clean["Reviews"] = train_clean["Reviews"].apply(lambda x: " ".join(x for x in x.split() if x not in stop_words)) import pandas as pd reviews = pd.Series(train_clean["Reviews"].tolist()).astype(str) plt.figure(figsize = (9, 9)) rev_wcloud_all = WordCloud(width = 900, height = 900, colormap ...
_____no_output_____
MIT
AmazonReviews_Example/NLP_Session_2_AmazonReviews_Example.ipynb
drshyamsundaram/nlp
Detailed NLP Analysis
tokenizer = RegexpTokenizer(r'\w+') train_clean["review_token"] = train_clean["Reviews"].apply(lambda x: tokenizer.tokenize(x)) # Sentiment analysis train_clean["sentiment_polarity"] = train_clean["Reviews"].apply(lambda x: TextBlob(x).sentiment.polarity) train_clean["sentiment_subjectivity"] = train_clean["Reviews"].a...
_____no_output_____
MIT
AmazonReviews_Example/NLP_Session_2_AmazonReviews_Example.ipynb
drshyamsundaram/nlp
![JohnSnowLabs](https://nlp.johnsnowlabs.com/assets/images/logo.png) 2. Text Preprocessing with Spark NLP **Note** Read this article if you want to understand the basic concepts in Spark NLP.https://towardsdatascience.com/introduction-to-spark-nlp-foundations-and-basic-components-part-i-c83b7629ed59 1. Annotators and...
import sparknlp spark = sparknlp.start() print("Spark NLP version", sparknlp.version()) print("Apache Spark version:", spark.version)
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/databricks_notebooks/2.4/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb
hatrungduc/spark-nlp-workshop
Create Spark Dataframe
text = 'Peter Parker is a nice guy and lives in New York' spark_df = spark.createDataFrame([[text]]).toDF("text") spark_df.show(truncate=False) # if you want to create a spark datafarme from a list of strings from pyspark.sql.types import StringType text_list = ['Peter Parker is a nice guy and lives in New York.', 'B...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/databricks_notebooks/2.4/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb
hatrungduc/spark-nlp-workshop
Transformers what are we going to do if our DataFrame doesn’t have columns in those type? Here comes transformers. In Spark NLP, we have five different transformers that are mainly used for getting the data in or transform the data from one AnnotatorType to another. Here is the list of transformers:`DocumentAssembler`...
from sparknlp.base import * documentAssembler = DocumentAssembler()\ .setInputCol("text")\ .setOutputCol("document")\ .setCleanupMode("shrink") doc_df = documentAssembler.transform(spark_df) doc_df.show(truncate=30)
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/databricks_notebooks/2.4/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb
hatrungduc/spark-nlp-workshop
At first, we define DocumentAssembler with desired parameters and then transform the data frame with it. The most important point to pay attention to here is that you need to use a String or String[Array] type column in .setInputCol(). So it doesn’t have to be named as text. You just use the column name as it is.
doc_df.printSchema() doc_df.select('document.result','document.begin','document.end').show(truncate=False)
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/databricks_notebooks/2.4/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb
hatrungduc/spark-nlp-workshop
The new column is in an array of struct type and has the parameters shown above. The annotators and transformers all come with universal metadata that would be filled down the road depending on the annotators being used. Unless you want to append other Spark NLP annotators to DocumentAssembler(), you don’t need to know...
doc_df.select("document.result").take(1)
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/databricks_notebooks/2.4/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb
hatrungduc/spark-nlp-workshop
If we would like to flatten the document column, we can do as follows.
import pyspark.sql.functions as F doc_df.withColumn( "tmp", F.explode("document"))\ .select("tmp.*")\ .show(truncate=False)
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/databricks_notebooks/2.4/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb
hatrungduc/spark-nlp-workshop
3. Sentence Detector Finds sentence bounds in raw text. `setCustomBounds(string)`: Custom sentence separator text`setUseCustomOnly(bool)`: Use only custom bounds without considering those of Pragmatic Segmenter. Defaults to false. Needs customBounds.`setUseAbbreviations(bool)`: Whether to consider abbreviation strateg...
from sparknlp.annotator import * # we feed the document column coming from Document Assembler sentenceDetector = SentenceDetector().\ setInputCols(['document']).\ setOutputCol('sentences') sent_df = sentenceDetector.transform(doc_df) sent_df.show(truncate=False) sent_df.select('sentences').take(3) text ='The patien...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/databricks_notebooks/2.4/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb
hatrungduc/spark-nlp-workshop
Tokenizer Identifies tokens with tokenization open standards. It is an **Annotator Approach, so it requires .fit()**.A few rules will help customizing it if defaults do not fit user needs.setExceptions(StringArray): List of tokens to not alter at all. Allows composite tokens like two worded tokens that the user may no...
tokenizer = Tokenizer() \ .setInputCols(["document"]) \ .setOutputCol("token") text = 'Peter Parker (Spiderman) is a nice guy and lives in New York but has no e-mail!' spark_df = spark.createDataFrame([[text]]).toDF("text") doc_df = documentAssembler.transform(spark_df) token_df = tokenizer.fit(doc_df).trans...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/databricks_notebooks/2.4/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb
hatrungduc/spark-nlp-workshop
Stacking Spark NLP Annotators in Spark ML Pipeline Spark NLP provides an easy API to integrate with Spark ML Pipelines and all the Spark NLP annotators and transformers can be used within Spark ML Pipelines. So, it’s better to explain Pipeline concept through Spark ML official documentation.What is a Pipeline anyway? ...
from pyspark.ml import Pipeline documentAssembler = DocumentAssembler()\ .setInputCol("text")\ .setOutputCol("document") sentenceDetector = SentenceDetector().\ setInputCols(['document']).\ setOutputCol('sentences') tokenizer = Tokenizer() \ .setInputCols(["sentences"]) \ .setOutputCol("token") nlpPipeline ...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/databricks_notebooks/2.4/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb
hatrungduc/spark-nlp-workshop
Normalizer Removes all dirty characters from text following a regex pattern and transforms words based on a provided dictionary`setCleanupPatterns(patterns)`: Regular expressions list for normalization, defaults [^A-Za-z]`setLowercase(value)`: lowercase tokens, default false`setSlangDictionary(path)`: txt file with de...
import string string.punctuation from sparknlp.annotator import * from sparknlp.base import * documentAssembler = DocumentAssembler()\ .setInputCol("text")\ .setOutputCol("document") tokenizer = Tokenizer() \ .setInputCols(["document"]) \ .setOutputCol("token") normalizer = Normalizer() \ .setInputCols([...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/databricks_notebooks/2.4/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb
hatrungduc/spark-nlp-workshop
Stopwords Cleaner This annotator excludes from a sequence of strings (e.g. the output of a Tokenizer, Normalizer, Lemmatizer, and Stemmer) and drops all the stop words from the input sequences. Functions:`setStopWords`: The words to be filtered out. Array[String]`setCaseSensitive`: Whether to do a case sensitive compa...
stopwords_cleaner = StopWordsCleaner()\ .setInputCols("token")\ .setOutputCol("cleanTokens")\ .setCaseSensitive(False)\ #.setStopWords(["no", "without"]) (e.g. read a list of words from a txt) stopwords_cleaner.getStopWords() documentAssembler = DocumentAssembler()\ .setInputCol("text")\ .setOu...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/databricks_notebooks/2.4/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb
hatrungduc/spark-nlp-workshop
Token Assembler
documentAssembler = DocumentAssembler()\ .setInputCol("text")\ .setOutputCol("document") sentenceDetector = SentenceDetector().\ setInputCols(['document']).\ setOutputCol('sentences') tokenizer = Tokenizer() \ .setInputCols(["sentences"]) \ .setOutputCol("token") normalizer = Normalizer() \ .setI...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/databricks_notebooks/2.4/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb
hatrungduc/spark-nlp-workshop
Stemmer Returns hard-stems out of words with the objective of retrieving the meaningful part of the word
stemmer = Stemmer() \ .setInputCols(["token"]) \ .setOutputCol("stem") documentAssembler = DocumentAssembler()\ .setInputCol("text")\ .setOutputCol("document") tokenizer = Tokenizer() \ .setInputCols(["document"]) \ .setOutputCol("token") nlpPipeline = Pipeline(stages=[ documentAssembler, tokenizer...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/databricks_notebooks/2.4/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb
hatrungduc/spark-nlp-workshop
Lemmatizer Retrieves lemmas out of words with the objective of returning a base dictionary word
!wget https://raw.githubusercontent.com/mahavivo/vocabulary/master/lemmas/AntBNC_lemmas_ver_001.txt -P /FileStore/ lemmatizer = Lemmatizer() \ .setInputCols(["token"]) \ .setOutputCol("lemma") \ .setDictionary("/FileStore/AntBNC_lemmas_ver_001.txt", value_delimiter ="\t", key_delimiter = "->") documentAssem...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/databricks_notebooks/2.4/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb
hatrungduc/spark-nlp-workshop
NGram Generator NGramGenerator annotator takes as input a sequence of strings (e.g. the output of a `Tokenizer`, `Normalizer`, `Stemmer`, `Lemmatizer`, and `StopWordsCleaner`). The parameter n is used to determine the number of terms in each n-gram. The output will consist of a sequence of n-grams where each n-gram is...
ngrams_cum = NGramGenerator() \ .setInputCols(["token"]) \ .setOutputCol("ngrams") \ .setN(3) \ .setEnableCumulative(True)\ .setDelimiter("_") # Default is space # .setN(3) means, take bigrams and trigrams. nlpPipeline = Pipeline(stages=[ documentAssemb...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/databricks_notebooks/2.4/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb
hatrungduc/spark-nlp-workshop
TextMatcher Annotator to match entire phrases (by token) provided in a file against a DocumentFunctions:setEntities(path, format, options): Provides a file with phrases to match. Default: Looks up path in configuration.path: a path to a file that contains the entities in the specified format.readAs: the format of the ...
# first method for doing this, second option below import urllib.request with urllib.request.urlopen('https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/resources/en/pubmed/pubmed-sample.csv') as f: content = f.read().decode('utf-8') dbutils.fs.put("/dbfs/tmp/pubmed/pubmed-sample.csv", content) %sh TMP=/...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/databricks_notebooks/2.4/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb
hatrungduc/spark-nlp-workshop
RegexMatcher
rules = ''' renal\s\w+, started with 'renal' cardiac\s\w+, started with 'cardiac' \w*ly\b, ending with 'ly' \S*\d+\S*, match any word that contains numbers (\d+).?(\d*)\s*(mg|ml|g), match medication metrics ''' dbutils.fs.put("dbfs:/tmp/pubmed/regex_rules.txt", rules) import os documentAssembler = DocumentAssembler()...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/databricks_notebooks/2.4/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb
hatrungduc/spark-nlp-workshop
Text Cleaning with UDF
text = '<h1 style="color: #5e9ca0;">Have a great <span style="color: #2b2301;">birth</span> day!</h1>' text_df = spark.createDataFrame([[text]]).toDF("text") import re from pyspark.sql.functions import udf from pyspark.sql.types import StringType, IntegerType clean_text = lambda s: re.sub(r'<[^>]*>', '', s) text_d...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/databricks_notebooks/2.4/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb
hatrungduc/spark-nlp-workshop
Finisher ***Finisher:*** Once we have our NLP pipeline ready to go, we might want to use our annotation results somewhere else where it is easy to use. The Finisher outputs annotation(s) values into a string.If we just want the desired output column in the final dataframe, we can use Finisher to drop previous stages i...
finisher = Finisher() \ .setInputCols(["regex_matches"]) \ .setIncludeMetadata(False) # set to False to remove metadata nlpPipeline = Pipeline(stages=[ documentAssembler, regex_matcher, finisher ]) empty_df = spark.createDataFrame([['']]).toDF("text") pipelineModel = nlpPipeline.fit(empty_df) match_df ...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/databricks_notebooks/2.4/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb
hatrungduc/spark-nlp-workshop
LightPipeline LightPipelines are Spark NLP specific Pipelines, equivalent to Spark ML Pipeline, but meant to deal with smaller amounts of data. They’re useful working with small datasets, debugging results, or when running either training or prediction from an API that serves one-off requests.Spark NLP LightPipelines ...
documentAssembler = DocumentAssembler()\ .setInputCol("text")\ .setOutputCol("document") tokenizer = Tokenizer() \ .setInputCols(["document"]) \ .setOutputCol("token") stemmer = Stemmer() \ .setInputCols(["token"]) \ .setOutputCol("stem") nlpPipeline = Pipeline(stages=[ documentAssembler, tokenize...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/databricks_notebooks/2.4/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb
hatrungduc/spark-nlp-workshop
How to deliver JavaScript to the IPython Notebook ViewerAt first glance there appear to be at least four mechanismsfor adding JavaScript code to an IPython notebook: * A notebook cell marked `%%javascript`* A Markdown cell with a `` inside* An `HTML()` display with a `` inside* A `JavaScript()` display with code in...
%%javascript console.log('Log message from the %%javascript cell')
_____no_output_____
MIT
Javascript-integration.ipynb
Grant-Steinfeld/astronomy-notebooks
*(Markdown cell with a `` inside.)*console.log('Log message from the Markdown cell')
from IPython.display import HTML HTML('<script>console.log("Log message from an HTML display")</script>') from IPython.display import Javascript Javascript('console.log("Log message from a Javascript display")')
_____no_output_____
MIT
Javascript-integration.ipynb
Grant-Steinfeld/astronomy-notebooks
Playing around with NLTKSome material has been taken/adapted from the [NLTK book](http://www.nltk.org/book/)* Exploring NLTK books (Text instance)* Exploring NLTK corpora* Exploring NLTK Treebank* Exploring the WordNet corpusFor the linguistics concepts used here, refer to [the specific notebook](../nlp/concepts/lingu...
## List of all the books and sents imported texts() sents() # Choose the book to play with and some wordsText book = text2 word = 'love' word2 = 'him' words = ['love', 'kiss', 'marriage', 'sense', 'children', 'house', 'hate'] # Print first 100 token in book (book is an instance of nltk.text.Text, which behaves like a...
All genres in Brown corpus: ['adventure', 'belles_lettres', 'editorial', 'fiction', 'government', 'hobbies', 'humor', 'learned', 'lore', 'mystery', 'news', 'religion', 'reviews', 'romance', 'science_fiction']
MIT
toolbox/python/nltk.ipynb
martinapugliese/tales-science-data-notebooks
Treebank* Parsed sentences
# The Treebank corpus in NLTK contains 10% of the original Penn Treebank corpus treebank.words() treebank.parsed_sents()
_____no_output_____
MIT
toolbox/python/nltk.ipynb
martinapugliese/tales-science-data-notebooks
WordNet* Hypernyms and Hyponyms
wn = wordnet sss = wn.synsets('dog') s1 = sss[0] print(s1, s1.definition()) print(s1.hypernyms(), s1.hyponyms())
Synset('dog.n.01') a member of the genus Canis (probably descended from the common wolf) that has been domesticated by man since prehistoric times; occurs in many breeds [Synset('canine.n.02'), Synset('domestic_animal.n.01')] [Synset('basenji.n.01'), Synset('corgi.n.01'), Synset('cur.n.01'), Synset('dalmatian.n.02'), S...
MIT
toolbox/python/nltk.ipynb
martinapugliese/tales-science-data-notebooks
Text manipulation* Tokenizing* POS tagging* Stemming/lemmatizing
# tagged sentences from Brown corpus brown_tagged_sents = brown.tagged_sents(categories='news') # Separate tagged sents into train and test train_sents = brown_tagged_sents[:int(len(brown_tagged_sents) * 0.8)] test_sents = brown_tagged_sents[int(len(brown_tagged_sents) * 0.8):] # Tokenising # NOTE: obvs the easiest se...
mice: mouse
MIT
toolbox/python/nltk.ipynb
martinapugliese/tales-science-data-notebooks
Playing with frequency distributions
# Setting some sentences sentences = ['I go to school', 'I will go to the cinema', 'I like strawberries', 'I read books'] # FreqDist on the word length on some chosen sentences and on the last letter of words split_sentences = [sentence.split() for sentence in sentences] all_words = [] for sent in split_sentences: ...
_____no_output_____
MIT
toolbox/python/nltk.ipynb
martinapugliese/tales-science-data-notebooks
SLU15 - Hyperparameter tunning: Examples notebook--- 1 Load and the prepare the data
import pandas as pd from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier cancer_data = load_breast_cancer() X = pd.DataFrame(cancer_data["data"], columns=cancer_data["feature_names"]) y = cancer_data.target X_train, X_test...
_____no_output_____
MIT
S01 - Bootcamp and Binary Classification/SLU15 - Hyperparameter Tuning/Examples notebook.ipynb
FarhadManiCodes/batch5-students
2 Grid search
from sklearn.model_selection import GridSearchCV parameters = {'max_depth': range(1, 10), 'max_features': range(1, X.shape[1])} grid_search = GridSearchCV(estimator, parameters, cv=5, scoring="roc_auc") grid_search.fit(X_train, y_train) y_pred = grid_search.predict(X_test)
_____no_output_____
MIT
S01 - Bootcamp and Binary Classification/SLU15 - Hyperparameter Tuning/Examples notebook.ipynb
FarhadManiCodes/batch5-students
2 Random search
from scipy.stats import randint from sklearn.model_selection import RandomizedSearchCV parameters_dist = {"max_depth": randint(1, 100), "max_features": randint(1, X.shape[1]), "class_weight": ["balanced", None]} random_search = RandomizedSearchCV(estimator, parameters_dist, cv=5,...
_____no_output_____
MIT
S01 - Bootcamp and Binary Classification/SLU15 - Hyperparameter Tuning/Examples notebook.ipynb
FarhadManiCodes/batch5-students
The analysis of the equality of rights between gender using the Human Freedom Index author: Ottillia Ni Project Report 2 (EM212: Applied Data Science) Content:IntroductionDatasheetExploratory Data Anaylsis Introduction Throughout the world, people strive for freedom. Freedom is a means of human progression and grow...
import matplotlib.pyplot as plt import pandas as pd import numpy as np import seaborn as sns import pdb import matplotlib.pyplot as plt
_____no_output_____
BSD-3-Clause
ottilliani/project2_ottilliani.ipynb
pezLyfe/applied_ds
Importing DatasetTo begin, I will be using python to analyize my data. (This data of the Human Freedom Index is downloaded off Kaggle.)
# read Human Freedom Index data hfi = pd.read_csv('https://tufts.box.com/shared/static/7iwsgxhffhfs87v209scqihq57pnmev0.csv') hfi.head()
_____no_output_____
BSD-3-Clause
ottilliani/project2_ottilliani.ipynb
pezLyfe/applied_ds
Cleaning Data Given that I am focusing specifically on the equality between female and male, I want to clean my data so that the variables printed give me the information relavent to my work. In addition, to make understanding the data easier, I will also rename various columns to be more comprehensive of what each v...
select_cols = ["year","countries","region","pf_ss_women","pf_ss_women_fgm", "pf_ss_women_missing","pf_ss_women_inheritance","pf_ss_women_inheritance_widows","pf_ss_women_inheritance_daughters","pf_movement_women","pf_identity_legal","pf_identity_parental","pf_identity_parental_marriage","pf_identity_parental_divorce","...
_____no_output_____
BSD-3-Clause
ottilliani/project2_ottilliani.ipynb
pezLyfe/applied_ds
Printing the data types objects makes it immediately evident that the data is mostly in forms of numbers, thus indicating much of the data has already been cleaned.
#Let us determine the percent of data missing per variable. #f, ax = plt.subplots(figsize=(50,20)) #((hfi.isnull().sum()/len(hfi)) * 100).plot(kind='bar') #plt.xticks(rotation=45, horizontalalignment='right') #plt.title('Percent Missing by Variable') # a simple scatterplot #hfi.plot.scatter('pf_score', 'ef_score') #h...
_____no_output_____
BSD-3-Clause
ottilliani/project2_ottilliani.ipynb
pezLyfe/applied_ds
To start off we can first lay out the number of countries represented by region through this bar plot from 2008-2016.
#hfi.region.value_counts().plot(kind='bar') #plt.xticks() #hfi[''].value_counts().plot(kind='bar') #filter to only focus on 2016 data filter1 = hfi_select1.year == 2016 hfi2016 = hfi_select1[filter1] hfi2016.sample(5) #filter to only focuus on 2016 data filter1 = hfi_select1.year == 2016 filter2 = hfi_select1.region =...
_____no_output_____
BSD-3-Clause
ottilliani/project2_ottilliani.ipynb
pezLyfe/applied_ds
Diving into gender equality, let us understand observe the equality of parental rights between males and females in various regions around the world.
#hfi2016Af.plot.scatter('pf_ss_women', 'pf_movement_women') #sub['mean'] = sub['density'].mean() #plt.plot(sub['name'], sub['density'], 'ro') #plt.plot(sub['name'], sub['mean'], linestyle = '--') #plt.xticks(fontsize = 8, rotation = 'vertical') hfi2016.region.value_counts().plot(kind='bar') plt.xticks() sns.heatmap(hf...
_____no_output_____
BSD-3-Clause
ottilliani/project2_ottilliani.ipynb
pezLyfe/applied_ds
According to the Human Freedom Report, "Parental rights refers to the extent to which women have equal rights based in law and custom regarding “legal guardianship of a child during a marriage and custody rights over a child after divorce.”" That being said, we can divide the rights parental rights in regards to legal ...
sns.heatmap(hfi_select1.groupby(['year', 'region'])['Parental_rights_marriage'].mean().unstack(), annot=True, cbar=False, fmt='.0f', cmap='RdBu_r')
_____no_output_____
BSD-3-Clause
ottilliani/project2_ottilliani.ipynb
pezLyfe/applied_ds
The same analysis can also be done with parental rights after divorces. The trend appears to be similar to that of parental rights during marriages, but what is most surprising is found in the Middle East & North Africa catagory. The ranking drops from a 5 to a 2 between 2012 and 2013 indicating a setback with progre...
sns.heatmap(hfi_select1.groupby(['year', 'region'])['Parental_rights_after_divorce'].mean().unstack(), annot=True, cbar=False, fmt='.0f', cmap='RdBu_r')
_____no_output_____
BSD-3-Clause
ottilliani/project2_ottilliani.ipynb
pezLyfe/applied_ds
Question: Which regions have the greatest amount of freedom in regards to same sex marriage?
sns.heatmap( hfi_select1.groupby(['year', 'region'])['Same_sex-relationship'].mean().unstack(), annot=True, cbar=False, fmt='.0f', cmap='RdBu_r')
_____no_output_____
BSD-3-Clause
ottilliani/project2_ottilliani.ipynb
pezLyfe/applied_ds
From this heat map, we can see that the regions struggle with equality
sns.heatmap(hfi_select1.groupby(['year', 'region'])['Same_sex_males'].mean().unstack(), annot=True, cbar=False, fmt='.0f', cmap='RdBu_r') sns.heatmap(hfi_select1.groupby(['year', 'region'])['Same_sex_female'].mean().unstack(), annot=True, cbar=False, fmt='.0f', cmap='RdBu_r')
_____no_output_____
BSD-3-Clause
ottilliani/project2_ottilliani.ipynb
pezLyfe/applied_ds
Merging Data
# read women purchasing power from https://ourworldindata.org/economic-inequality-by-gender ge = pd.read_csv('https://tufts.box.com/shared/static/ikc9nsb0red47dv5ldc0rcsv5rml681l.csv') ge.head() #ge.dtypes mergedata = hfi_select1.merge(ge, left_on=["year", "countries"], right_on=["Year", "Entity"], suffixes=(False, Fal...
_____no_output_____
BSD-3-Clause
ottilliani/project2_ottilliani.ipynb
pezLyfe/applied_ds
By merging these two datasets, we can also compare how women in various countries are given the opportunity to participate in purchase descision within their marriages.
#mergedata.dtypes
_____no_output_____
BSD-3-Clause
ottilliani/project2_ottilliani.ipynb
pezLyfe/applied_ds
supervised learning - Scikit.learn
#hfi2016.plot.scatter('Inheritance_Rights', 'Parental_rights') f, ax = plt.subplots(figsize=(6.5,6.5)) sns.boxplot(x="Inheritance_Rights", y="Parental_rights", data=hfi2016, fliersize=0.5, linewidth=0.75, ax=ax) #ax.set_title('axes title') ax.set_xlabel('Women Inheritance') ax.set_ylabel('Parental Rights') #filter to ...
_____no_output_____
BSD-3-Clause
ottilliani/project2_ottilliani.ipynb
pezLyfe/applied_ds
第5章 ロジスティック回帰とROC曲線:学習モデルの評価方法 「05-roc_curve」の解説 ITエンジニアための機械学習理論入門「第5章 ロジスティック回帰とROC曲線:学習モデルの評価方法」で使用しているサンプルコード「05-roc_curve.py」の解説です。※ 解説用にコードの内容は少し変更しています。 はじめに必要なモジュールをインポートしておきます。関数 multivariate_normal は、多次元の正規分布に従う乱数を生成するために利用します。
import numpy as np import matplotlib.pyplot as plt import pandas as pd from pandas import Series, DataFrame from numpy.random import multivariate_normal
_____no_output_____
Apache-2.0
05-roc_curve.ipynb
RXV06021/test_ml4se_colab
トレーニング用データを生成する関数を用意します。平面上の○☓の2種類のデータについて、それぞれの「個数、中心座標、分散」を引数で指定します。
def prepare_dataset(n1, mu1, variance1, n2, mu2, variance2): df1 = DataFrame(multivariate_normal(mu1, np.eye(2)*variance1 ,n1), columns=['x','y']) df1['type'] = 1 df2 = DataFrame(multivariate_normal(mu2, np.eye(2)*variance2, n2), columns=['x','y']) df2['type'] = -...
_____no_output_____
Apache-2.0
05-roc_curve.ipynb
RXV06021/test_ml4se_colab
ロジスティック回帰で分割線を決定する関数を用意します。ここでは、得られた結果を用いて、トレーニングセットの各データに対して確率の値を付与したデータフレームも返却するようにしています。
# ロジスティック回帰 def run_logistic(train_set): pd.options.mode.chained_assignment = None w = np.array([[0],[0.1],[0.1]]) phi = train_set[['x','y']] phi['bias'] = 1 phi = phi.as_matrix(columns=['bias','x','y']) t = (train_set[['type']] + 1)*0.5 # type = 1, -1 を type = 1, 0 に変換 t = t.as_matrix() ...
_____no_output_____
Apache-2.0
05-roc_curve.ipynb
RXV06021/test_ml4se_colab
結果をグラフ、および、ROC曲線として表示する関数を用意します。
# 結果の表示 def show_result(subplot, train_set, w0, w1, w2, err_rate): train_set1 = train_set[train_set['type']==1] train_set2 = train_set[train_set['type']==-1] ymin, ymax = train_set.y.min()-5, train_set.y.max()+10 xmin, xmax = train_set.x.min()-5, train_set.x.max()+10 subplot.set_ylim([ymin-1, ymax+...
_____no_output_____
Apache-2.0
05-roc_curve.ipynb
RXV06021/test_ml4se_colab
比較的分散が小さくて、分類が容易なトレーニングセットを用意します。
train_set = prepare_dataset(80, [9,9], 50, 200, [-3,-3], 50)
_____no_output_____
Apache-2.0
05-roc_curve.ipynb
RXV06021/test_ml4se_colab
ロジスティック回帰を適用した結果を表示します。
w0, w1, w2, err_rate, result = run_logistic(train_set) fig = plt.figure(figsize=(6, 12)) subplot = fig.add_subplot(2,1,1) show_result(subplot, train_set, w0, w1, w2, err_rate) subplot = fig.add_subplot(2,1,2) draw_roc(subplot, result)
_____no_output_____
Apache-2.0
05-roc_curve.ipynb
RXV06021/test_ml4se_colab
分散が大きくて、分類が困難なトレーニングセットを用意します。
train_set = prepare_dataset(80, [9,9], 150, 200, [-3,-3], 150)
_____no_output_____
Apache-2.0
05-roc_curve.ipynb
RXV06021/test_ml4se_colab