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
> **Quantas vezes um produto foi parcelado**
#juntar tabela items(product_id) com a tabela payments(payment_installments) em order_id most_products_installments = pd.merge(left=items, right= payments, on='order_id') products_by_installments = most_products_installments.groupby(['product_id','payment_installments'])['payment_installments'].size() products_by_installments = products_by_installments.sort_values(0, ascending=False) products_by_installments = pd.DataFrame(data=products_by_installments) products_by_installments = products_by_installments.rename(columns={"payment_installments":'Quantities of Products Installments'}) products_by_installments
_____no_output_____
MIT
DataScience/Olist/EnfaseLabs.ipynb
brunereduardo/DataPortfolio
>**ticket médio = Soma do faturamento em vendas (R$)/Nº de vendas concluídas** Análise para Logística: >Maior valor de frete encontrado por estado
aux = pd.merge(left=items, right=orders, on= 'order_id') #customers(ligando pelo customer_id e pegando os valores de estado e cidade) # items(order_id e pegando freight_value) #orders(ligando por order_id e pegando o customer_id) biggest_freight_value = pd.merge(left=customers, right=aux, on='customer_id') freight_value_by_state = biggest_freight_value.groupby(['customer_state'])['freight_value'].max() freight_value_by_state = freight_value_by_state.sort_values(0, ascending=False) freight_value_by_state = pd.DataFrame(data=freight_value_by_state) freight_value_by_state = freight_value_by_state.rename(columns={'freight_value':'Biggest Freight Value'}) freight_value_by_state.plot.bar() freight_value_by_state.boxplot()
_____no_output_____
MIT
DataScience/Olist/EnfaseLabs.ipynb
brunereduardo/DataPortfolio
debug Class> API details.
#hide import logging logging.basicConfig(level= logging.WARNING) log = logging.getLogger("pynamodb") log.setLevel(logging.DEBUG) log.setLevel(logging.WARNING) log.propagate = True #hide import pickle, os, json os.environ['DATABASE_TABLE_NAME'] = 'product-table-dev-manual' os.environ['BRANCH'] = 'dev' os.environ['REGION'] = 'ap-southeast-1' os.environ['INVENTORY_BUCKET_NAME'] = 'product-bucket-dev-manual' os.environ['INPUT_BUCKET_NAME'] = 'input-product-bucket-dev-manual' os.environ['DAX_ENDPOINT'] = 'longtermcluster.vuu7lr.clustercfg.dax.apse1.cache.amazonaws.com:8111' os.environ['LINEKEY'] = '2uAfV4AoYglUGmKTAk2xNOm0aV2Ufgh1BQPvQl9vJd4' os.environ['INTCOLS'] = json.dumps(['cprcode', 'iprcode', 'oprcode', 'sellingPrice']) REGION = 'ap-southeast-1' BRANCH='dev' ECOMMERCE_COL_LIST = f'https://raw.githubusercontent.com/thanakijwanavit/villaMasterSchema/{BRANCH}/product/ecommerceColList.yaml' #hide print(json.dumps(os.environ['INTCOLS'])) from villaProductDatabase.database import ProductDatabase, lambdaDumpOnlineS3 import pandas as pd from typing import List import yaml, requests
_____no_output_____
Apache-2.0
debug.ipynb
thanakijwanavit/villa-product-database
LambdaDumpOnline
lambdaDumpOnlineS3({}) from inspect import getsource print(getsource(lambdaDumpOnlineS3))
def lambdaDumpOnlineS3(event, *args): print(f'ecommece col list is {ECOMMERCE_COL_LIST}') # get all products from db df:pd.DataFrame = pd.DataFrame([i.data for i in ProductDatabase.scan()]) # get online list from ECOMMERCE_COL_LIST onlineList:List[str] = yaml.load(requests.get(ECOMMERCE_COL_LIST).content) # filter df for item ## condition 1 master online is true condition1 = df['master_online'] == True ## condition 2 hema_name_en is not blank condition2 = df['hema_name_en'] != '' ## filtered df onlineDf:pd.DataFrame = df[condition1 & condition2].loc[:,onlineList] ### log shape and size print('shape is:',onlineDf.shape) print('size is:',sys.getsizeof(onlineDf.to_json(orient='split'))/1e6, 'Mb') # save file as gzip key = 'onlineData' bucket = INVENTORY_BUCKET_NAME path = '/tmp/inventory.json' ## export to gzip onlineDf.to_json(path ,orient='split',compression='gzip') ## upload file to s3 S3.saveFile(key=key,path=path,bucket=bucket, ExtraArgs = {**ExtraArgs.gzip, **ExtraArgs.publicRead }) return Response.returnSuccess()
Apache-2.0
debug.ipynb
thanakijwanavit/villa-product-database
get all products
df:pd.DataFrame = pd.DataFrame([i.data for i in ProductDatabase.scan()]) df.head()
_____no_output_____
Apache-2.0
debug.ipynb
thanakijwanavit/villa-product-database
filter products
condition1 = df['master_online'] == True condition2 = df['hema_name_en'] != '' onlineList:List[str] = yaml.load(requests.get(ECOMMERCE_COL_LIST).content) onlineDf:pd.DataFrame = df[condition1 & condition2].loc[:,onlineList] onlineDf.head() df.shape df[condition1].shape ## filter for master_online df[condition1 & condition2].shape ## filter products with missing hema_name onlineDf[onlineDf.cprcode == 241490] url = 'https://product-bucket-dev-manual.s3-ap-southeast-1.amazonaws.com/onlineData' r = pd.read_json(url, orient = 'split', compression = 'gzip') r.shape r.shape
_____no_output_____
Apache-2.0
debug.ipynb
thanakijwanavit/villa-product-database
**Check whether two string are anagram of each other** ![download.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQMAAADCCAMAAAB6zFdcAAABiVBMVEX///+r280iHh/50T7u7tYAAAD9/P0aDRFngnrt7dLu7dfw79uw4NIjHR9fcm0YERQJAADd3N3l4+j29/TNXzro4ML42GD8zjv50C3yajoNOFtUe4oAMFb19PWp3M3u7O0gGhjQzs+ioKG/vb6WlJXU09LHxcYbExGXmG0jHRs2MTAvKikoIyLf3t5/fX6zsrCfzsJIREOKiInduzkAK1eem5xRT02urK1vbG0UECHR1MZdWlpAPTuDgYFzcnBkYWKHqqBASUYwNjWUuq/saTzGc1POWjNOY1zY7ud0j4dOWVUoLi2DopqfoXNZe4BXd3xRWkoAK1wAAC07LCg7WHK4wswAIEtCUE3QyrLR2uIWAAoXERpaV09EQTuHhXqfnpC4tqjR49THsJrGoYrKkHjzy6fvtJjwoX7wjWbxgVOtzbq2w6r2WRzWmnjBln71ZC/Ie17KZ0Ly13ru2Zv712W8nTufiEDs27M1MDgmIC7014Tr39LEt5+0yby+UTSqlIGJRS5kNSUAFBtCB0BRAAAZlUlEQVR4nO2dj5/cRnXAtZue1i23J+kuEKeNdvRbaPTrJKIfRFrp7HNs7BwtLYWkDlAwaQEb4gJtgZJAy1/eeTMjre68uvhgfT779vlje1c/RprvzLx5897MrDDhcihNqczu7S6O5Fu7k9dbFr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**
def anagram(w1,w2): w1=w1.replace(' ','').lower() w2=w2.replace(' ','').lower() return sorted(w1)==sorted(w2) anagram('do g','GOd') def anagramer(w1,w2): w1=w1.replace(' ','').lower() w2=w2.replace(' ','').lower() if len(w1) != len(w2): return False count ={} for letter in w1: print(letter) if letter in count: print(letter) count[letter] += 1 else: count[letter] = 1 for letter in w2: if letter in count: count[letter] -= 1 else: count[letter] =1 for k in count: if count[k] != 0: return False return True anagramer('wera','wesa') anagramer('rabbt','t bbra')
_____no_output_____
MIT
001_Anagram_Check.ipynb
ishancoderr/Coffee_code_Algorithms
MPST: A Corpus of Movie Plot Synopses with Tags
!pip install scikit-multilearn import re import os import tqdm import nltk import pickle import sqlite3 import warnings import numpy as np import pandas as pd from tqdm import tqdm import seaborn as sns import xgboost as xgb import tensorflow as tf from sklearn import metrics from tensorflow import keras from nltk.corpus import words from datetime import datetime from bs4 import BeautifulSoup from wordcloud import WordCloud import matplotlib.pyplot as plt from nltk.corpus import stopwords from gensim.models import Word2Vec from itertools import combinations from keras.models import load_model from keras.models import Sequential from tensorflow.keras import layers from nltk.stem import SnowballStemmer from sklearn.pipeline import Pipeline from nltk.tokenize import sent_tokenize from keras.preprocessing import sequence from scipy.sparse import coo_matrix, hstack from tensorflow.keras.utils import plot_model from keras.layers.embeddings import Embedding from sklearn.naive_bayes import MultinomialNB from sklearn.linear_model import SGDClassifier from sklearn.model_selection import GridSearchCV from sklearn.metrics import classification_report from sklearn.multiclass import OneVsRestClassifier from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import MultiLabelBinarizer from sklearn.model_selection import RandomizedSearchCV from skmultilearn.problem_transform import BinaryRelevance from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.metrics import f1_score,precision_score,recall_score,hamming_loss from keras.layers import Conv1D, Conv2D, Dense, Dropout, Flatten, LSTM, GlobalMaxPooling1D, MaxPooling2D, Activation, BatchNormalization %matplotlib inline nltk.download('punkt') nltk.download('wordnet') warnings.filterwarnings("ignore") stemmer = SnowballStemmer('english') %autosave 120 data_with_all_tags = pd.read_csv("data_with_all_tags.csv") data_with_all_tags.head() conn = sqlite3.connect('data.db') data_with_all_tags.to_sql('data', conn, if_exists='replace', index=False) train = pd.read_sql("Select * From data where split = 'train' OR split='val'",conn) test = pd.read_sql("Select * From data where split = 'test'",conn) conn.close() X_train = train["CleanedSynopsis"] y_train= train["tags"] X_test = test["CleanedSynopsis"] y_test= test["tags"] def tokenize(x): x=x.split(',') tags=[i.strip() for i in x] #Some tags contains whitespaces before them, so we need to strip them return tags cnt_vectorizer = CountVectorizer(tokenizer = tokenize, max_features=3, binary='true').fit(y_train) y_train_multilabel = cnt_vectorizer.transform(y_train) y_test_multilabel = cnt_vectorizer.transform(y_test)
_____no_output_____
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
1. TfidfVectorizer with 1 grams:
tf_vectorizer = TfidfVectorizer(min_df=0.09, tokenizer = lambda x: x.split(" "), ngram_range=(1,1)) X_train_multilabel = tf_vectorizer.fit_transform(X_train) X_test_multilabel = tf_vectorizer.transform(X_test) print("Dimensions of train data X:",X_train_multilabel.shape, "Y :",y_train_multilabel.shape) print("Dimensions of test data X:",X_test_multilabel.shape,"Y:",y_test_multilabel.shape)
Dimensions of train data X: (10989, 657) Y : (10989, 3) Dimensions of test data X: (2768, 657) Y: (2768, 3)
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
1.1 OneVsRestClassifier + MultinomialNB:
mb = MultinomialNB(class_prior = [0.5, 0.5]) clf = OneVsRestClassifier(mb) clf.fit(X_train_multilabel, y_train_multilabel) prediction1 = clf.predict(X_test_multilabel) precision1 = precision_score(y_test_multilabel, prediction1, average='micro') recall1 = recall_score(y_test_multilabel, prediction1, average='micro') f1_score1 = 2*((precision1 * recall1)/(precision1 + recall1)) print("precision1: {:.4f}, recall1: {:.4f}, F1-measure: {:.4f}".format(precision1, recall1, f1_score1)) for i in range(5): k = test.sample(1).index[0] print("Movie: ", test['title'][k]) print("Actual genre: ",y_test[k]) print("Predicted tag: ", cnt_vectorizer.inverse_transform(prediction1[k])[0],"\n")
Movie: Anastasia Actual genre: romantic, cute, entertaining Predicted tag: [] Movie: Dog City Actual genre: psychedelic Predicted tag: [] Movie: Aftermath Actual genre: violence Predicted tag: ['flashback' 'murder' 'violence'] Movie: What a Nightmare, Charlie Brown! Actual genre: psychedelic Predicted tag: [] Movie: Witchcraft 7: Judgement Hour Actual genre: paranormal Predicted tag: ['flashback' 'murder' 'violence']
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
1.2 OneVsRestClassifier + SGDClassifier with LOG Loss:
sgl = SGDClassifier(loss='log', class_weight='balanced') clf = OneVsRestClassifier(sgl) clf.fit(X_train_multilabel, y_train_multilabel) prediction2 = clf.predict(X_test_multilabel) precision2 = precision_score(y_test_multilabel, prediction2, average='micro') recall2 = recall_score(y_test_multilabel, prediction2, average='micro') f1_score2 = 2*((precision2 * recall2)/(precision2 + recall2)) print("precision2: {:.4f}, recall2: {:.4f}, F1-measure: {:.4f}".format(precision2, recall2, f1_score2)) for i in range(5): k = test.sample(1).index[0] print("Movie: ", test['title'][k]) print("Actual genre: ",y_test[k]) print("Predicted tag: ", cnt_vectorizer.inverse_transform(prediction2[k])[0],"\n")
Movie: Capitalism: A Love Story Actual genre: sentimental Predicted tag: ['flashback'] Movie: Saved! Actual genre: romantic, humor, satire Predicted tag: [] Movie: How to Train Your Dragon 2 Actual genre: revenge, cute Predicted tag: ['violence'] Movie: Orfeu Negro Actual genre: atmospheric Predicted tag: ['murder'] Movie: Accepted Actual genre: romantic, action Predicted tag: []
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
1.3 OneVsRestClassifier + SGDClassifier with Hinge Loss:
sgh = SGDClassifier(loss='hinge', class_weight='balanced') clf = OneVsRestClassifier(sgh) clf.fit(X_train_multilabel, y_train_multilabel) prediction3 = clf.predict(X_test_multilabel) precision3 = precision_score(y_test_multilabel, prediction3, average='micro') recall3 = recall_score(y_test_multilabel, prediction3, average='micro') f1_score3 = 2*((precision3 * recall3)/(precision3 + recall3)) print("precision3: {:.4f}, recall3: {:.4f}, F1-measure: {:.4f}".format(precision3, recall3, f1_score3)) for i in range(5): k = test.sample(1).index[0] print("Movie: ", test['title'][k]) print("Actual genre: ",y_test[k]) print("Predicted tag: ", cnt_vectorizer.inverse_transform(prediction3[k])[0],"\n")
Movie: Assassin's Creed IV: Black Flag Actual genre: action Predicted tag: ['flashback' 'murder' 'violence'] Movie: The Kite Runner Actual genre: romantic, violence, murder, storytelling, flashback Predicted tag: ['flashback' 'violence'] Movie: Guest House Paradiso Actual genre: psychedelic, comedy Predicted tag: [] Movie: Gingerdead Man 2: Passion of the Crust Actual genre: comedy, murder, violence Predicted tag: ['flashback' 'murder' 'violence'] Movie: Zazie dans le métro Actual genre: absurd, psychedelic Predicted tag: []
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
1.4 OneVsRestClassifier + LogisticRegression:
lr = LogisticRegression(class_weight='balanced') clf = OneVsRestClassifier(lr) clf.fit(X_train_multilabel, y_train_multilabel) prediction4 = clf.predict(X_test_multilabel) precision4 = precision_score(y_test_multilabel, prediction4, average='micro') recall4 = recall_score(y_test_multilabel, prediction4, average='micro') f1_score4 = 2*((precision4 * recall4)/(precision4 + recall4)) print("precision4: {:.4f}, recall4: {:.4f}, F1-measure: {:.4f}".format(precision4, recall4, f1_score4)) for i in range(5): k = test.sample(1).index[0] print("Movie: ", test['title'][k]) print("Actual genre: ",y_test[k]) print("Predicted tag: ", cnt_vectorizer.inverse_transform(prediction4[k])[0],"\n")
Movie: The Sting Actual genre: boring, depressing, murder, cult, plot twist, clever, inspiring, revenge, entertaining Predicted tag: ['flashback' 'murder'] Movie: Olivia Actual genre: neo noir, cruelty, murder, violence, revenge, sadist Predicted tag: [] Movie: El capo Actual genre: satire Predicted tag: ['flashback' 'murder' 'violence'] Movie: Bereavement Actual genre: cult Predicted tag: ['murder' 'violence'] Movie: Arpointeu Actual genre: neo noir, murder, paranormal, violence, flashback, revenge Predicted tag: ['flashback' 'murder' 'violence']
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
2. TfidfVectorizer with (1 - 2 Grams):
tf_vectorizer = TfidfVectorizer(min_df=0.09, tokenizer = lambda x: x.split(" "), ngram_range=(1,2)) X_train_multilabel = tf_vectorizer.fit_transform(X_train) X_test_multilabel = tf_vectorizer.transform(X_test) print("Dimensions of train data X:",X_train_multilabel.shape, "Y :",y_train_multilabel.shape) print("Dimensions of test data X:",X_test_multilabel.shape,"Y:",y_test_multilabel.shape)
Dimensions of train data X: (10989, 666) Y : (10989, 3) Dimensions of test data X: (2768, 666) Y: (2768, 3)
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
2.1 OneVsRestClassifier + MultinomialNB :
mb = MultinomialNB(class_prior = [0.5, 0.5]) clf = OneVsRestClassifier(mb) clf.fit(X_train_multilabel, y_train_multilabel) prediction5 = clf.predict(X_test_multilabel) precision5 = precision_score(y_test_multilabel, prediction5, average='micro') recall5 = recall_score(y_test_multilabel, prediction5, average='micro') f1_score5 = 2*((precision5 * recall5)/(precision5 + recall5)) print("precision5: {:.4f}, recall5: {:.4f}, F1-measure: {:.4f}".format(precision5, recall5, f1_score5)) for i in range(5): k = test.sample(1).index[0] print("Movie: ", test['title'][k]) print("Actual genre: ",y_test[k]) print("Predicted tag: ", cnt_vectorizer.inverse_transform(prediction5[k])[0],"\n")
Movie: Long-Distance Princess Actual genre: romantic Predicted tag: ['flashback'] Movie: Time Lapse Actual genre: plot twist, mystery, murder Predicted tag: ['murder'] Movie: What's Eating Gilbert Grape Actual genre: tragedy, whimsical, psychedelic, boring, depressing Predicted tag: ['flashback'] Movie: The Rebound Actual genre: comedy, romantic Predicted tag: ['flashback'] Movie: Une liaison pornographique Actual genre: pornographic, realism, flashback Predicted tag: ['flashback']
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
2.2 OneVsRestClassifier + SGDClassifier with LOG Loss :
sgl = SGDClassifier(loss='log', class_weight='balanced') clf = OneVsRestClassifier(sgl) clf.fit(X_train_multilabel, y_train_multilabel) prediction6 = clf.predict(X_test_multilabel) precision6 = precision_score(y_test_multilabel, prediction6, average='micro') recall6 = recall_score(y_test_multilabel, prediction6, average='micro') f1_score6 = 2*((precision6 * recall6)/(precision6 + recall6)) print("precision6: {:.4f}, recall6: {:.4f}, F1-measure: {:.4f}".format(precision6, recall6, f1_score6)) for i in range(5): k = test.sample(1).index[0] print("Movie: ", test['title'][k]) print("Actual genre: ",y_test[k]) print("Predicted tag: ", cnt_vectorizer.inverse_transform(prediction6[k])[0],"\n")
Movie: Cape Fear Actual genre: suspenseful, gothic, murder, neo noir, mystery, violence, cult, horror, flashback, good versus evil, revenge Predicted tag: ['flashback' 'murder' 'violence'] Movie: Wild Bill Actual genre: cult, revenge, storytelling, flashback Predicted tag: ['violence'] Movie: Beyond the Law Actual genre: romantic, neo noir, murder, violence, flashback Predicted tag: ['murder'] Movie: Blancanieves Actual genre: cruelty, murder Predicted tag: [] Movie: Gabriel Over the White House Actual genre: depressing Predicted tag: ['violence']
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
2.3 OneVsRestClassifier + SGDClassifier with HINGE Loss :
sgh = SGDClassifier(loss='hinge', class_weight='balanced') clf = OneVsRestClassifier(sgh) clf.fit(X_train_multilabel, y_train_multilabel) prediction7 = clf.predict(X_test_multilabel) precision7 = precision_score(y_test_multilabel, prediction7, average='micro') recall7 = recall_score(y_test_multilabel, prediction7, average='micro') f1_score7 = 2*((precision7 * recall7)/(precision7 + recall7)) print("precision7: {:.4f}, recall7: {:.4f}, F1-measure: {:.4f}".format(precision7, recall7, f1_score7)) for i in range(5): k = test.sample(1).index[0] print("Movie: ", test['title'][k]) print("Actual genre: ",y_test[k]) print("Predicted tag: ", cnt_vectorizer.inverse_transform(prediction7[k])[0],"\n")
Movie: Les deux orphelines vampires Actual genre: insanity Predicted tag: ['murder'] Movie: The Blob Actual genre: violence, cult, suspenseful, comedy, murder Predicted tag: ['murder'] Movie: La casa muda Actual genre: plot twist, revenge Predicted tag: [] Movie: Fist Fight Actual genre: prank Predicted tag: [] Movie: Linewatch Actual genre: good versus evil, violence Predicted tag: ['murder' 'violence']
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
2.4 OneVsRestClassifier + LogisticRegression:
lr = LogisticRegression(class_weight='balanced') clf = OneVsRestClassifier(lr) clf.fit(X_train_multilabel, y_train_multilabel) prediction8 = clf.predict(X_test_multilabel) precision8 = precision_score(y_test_multilabel, prediction8, average='micro') recall8 = recall_score(y_test_multilabel, prediction8, average='micro') f1_score8 = 2*((precision8 * recall8)/(precision8 + recall8)) print("precision8: {:.4f}, recall8: {:.4f}, F1-measure: {:.4f}".format(precision8, recall8, f1_score8)) for i in range(5): k = test.sample(1).index[0] print("Movie: ", test['title'][k]) print("Actual genre: ",y_test[k]) print("Predicted tag: ", cnt_vectorizer.inverse_transform(prediction8[k])[0],"\n")
Movie: Hare and Loathing in Las Vegas Actual genre: psychedelic Predicted tag: [] Movie: Misconduct Actual genre: neo noir Predicted tag: ['murder' 'violence'] Movie: Ten Little Indians Actual genre: murder Predicted tag: ['flashback' 'murder' 'violence'] Movie: Hostel Actual genre: boring, gothic, murder, stupid, violence, cult, horror, action, revenge, sadist Predicted tag: ['violence'] Movie: Scooby-Doo and the Witch's Ghost Actual genre: paranormal, psychedelic, horror, mystery Predicted tag: []
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
3. TfidfVectorizer with (1 - 3 Grams):
tf_vectorizer = TfidfVectorizer(min_df=0.09, tokenizer = lambda x: x.split(" "), ngram_range=(1,3)) X_train_multilabel = tf_vectorizer.fit_transform(X_train) X_test_multilabel = tf_vectorizer.transform(X_test) print("Dimensions of train data X:",X_train_multilabel.shape, "Y :",y_train_multilabel.shape) print("Dimensions of test data X:",X_test_multilabel.shape,"Y:",y_test_multilabel.shape)
Dimensions of train data X: (10989, 666) Y : (10989, 3) Dimensions of test data X: (2768, 666) Y: (2768, 3)
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
3.1 OneVsRestClassifier + MultinomialNB :
mb = MultinomialNB(class_prior = [0.5, 0.5]) clf = OneVsRestClassifier(mb) clf.fit(X_train_multilabel, y_train_multilabel) prediction9 = clf.predict(X_test_multilabel) precision9 = precision_score(y_test_multilabel, prediction9, average='micro') recall9 = recall_score(y_test_multilabel, prediction9, average='micro') f1_score9 = 2*((precision9 * recall9)/(precision9 + recall9)) print("precision9: {:.4f}, recall9: {:.4f}, F1-measure: {:.4f}".format(precision9, recall9, f1_score9)) for i in range(5): k = test.sample(1).index[0] print("Movie: ", test['title'][k]) print("Actual genre: ",y_test[k]) print("Predicted tag: ", cnt_vectorizer.inverse_transform(prediction9[k])[0],"\n")
Movie: Tezaab Actual genre: revenge, romantic, flashback Predicted tag: ['flashback' 'murder' 'violence'] Movie: My Summer of Love Actual genre: dramatic, romantic, queer Predicted tag: ['flashback'] Movie: The Ten Commandments: The Musical Actual genre: historical fiction Predicted tag: ['violence'] Movie: The Gambler and the Lady Actual genre: revenge, murder Predicted tag: ['murder' 'violence'] Movie: Roxanne Actual genre: romantic, psychedelic, entertaining Predicted tag: ['flashback']
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
3.2 OneVsRestClassifier + SGDClassifier with LOG Loss :
sgl = SGDClassifier(loss='log', class_weight='balanced') clf = OneVsRestClassifier(sgl) clf.fit(X_train_multilabel, y_train_multilabel) prediction10 = clf.predict(X_test_multilabel) precision10 = precision_score(y_test_multilabel, prediction10, average='micro') recall10 = recall_score(y_test_multilabel, prediction10, average='micro') f1_score10 = 2*((precision10 * recall10)/(precision10 + recall10)) print("precision10: {:.4f}, recall10: {:.4f}, F1-measure: {:.4f}".format(precision10, recall10, f1_score10)) for i in range(5): k = test.sample(1).index[0] print("Movie: ", test['title'][k]) print("Actual genre: ",y_test[k]) print("Predicted tag: ", cnt_vectorizer.inverse_transform(prediction10[k])[0],"\n")
Movie: American Son Actual genre: violence, romantic, flashback Predicted tag: ['flashback'] Movie: Conan the Destroyer Actual genre: murder, cult, fantasy, alternate history, violence Predicted tag: ['murder' 'violence'] Movie: Love & Other Drugs Actual genre: romantic Predicted tag: ['flashback'] Movie: The Gazebo Actual genre: suspenseful, murder Predicted tag: ['murder'] Movie: Kuch Kuch Hota Hai Actual genre: flashback Predicted tag: ['flashback']
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
3.3 OneVsRestClassifier + SGDClassifier with HINGE Loss :
sgh = SGDClassifier(loss='hinge', class_weight='balanced') clf = OneVsRestClassifier(sgh) clf.fit(X_train_multilabel, y_train_multilabel) prediction11 = clf.predict(X_test_multilabel) precision11 = precision_score(y_test_multilabel, prediction11, average='micro') recall11 = recall_score(y_test_multilabel, prediction11, average='micro') f1_score11 = 2*((precision11 * recall11)/(precision11 + recall11)) print("precision11: {:.4f}, recall11: {:.4f}, F1-measure: {:.4f}".format(precision11, recall11, f1_score11)) for i in range(5): k = test.sample(1).index[0] print("Movie: ", test['title'][k]) print("Actual genre: ",y_test[k]) print("Predicted tag: ", cnt_vectorizer.inverse_transform(prediction11[k])[0],"\n")
Movie: Austin Powers: International Man of Mystery Actual genre: comedy, boring, cult, good versus evil, psychedelic, humor, satire, revenge, entertaining Predicted tag: [] Movie: American Dreamer Actual genre: intrigue Predicted tag: ['flashback'] Movie: Shootout at Wadala Actual genre: violence Predicted tag: ['flashback' 'murder' 'violence'] Movie: Haunted - 3D Actual genre: paranormal Predicted tag: ['flashback'] Movie: All-Star Superman Actual genre: tragedy, whimsical, romantic, action Predicted tag: ['flashback']
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
3.4 OneVsRestClassifier + LogisticRegression:
lr = LogisticRegression(class_weight='balanced') clf = OneVsRestClassifier(lr) clf.fit(X_train_multilabel, y_train_multilabel) prediction12 = clf.predict(X_test_multilabel) precision12 = precision_score(y_test_multilabel, prediction12, average='micro') recall12 = recall_score(y_test_multilabel, prediction12, average='micro') f1_score12 = 2*((precision12 * recall12)/(precision12 + recall12)) print("precision12: {:.4f}, recall12: {:.4f}, F1-measure: {:.4f}".format(precision12, recall12, f1_score12)) for i in range(5): k = test.sample(1).index[0] print("Movie: ", test['title'][k]) print("Actual genre: ",y_test[k]) print("Predicted tag: ", cnt_vectorizer.inverse_transform(prediction12[k])[0],"\n")
Movie: End of Days Actual genre: mystery, neo noir, murder, stupid, violence, flashback, good versus evil, suspenseful Predicted tag: ['flashback' 'murder' 'violence'] Movie: Zombeavers Actual genre: absurd, entertaining Predicted tag: ['violence'] Movie: The Witches of Eastwick Actual genre: comedy Predicted tag: ['flashback'] Movie: Chain of Desire Actual genre: murder Predicted tag: [] Movie: Did You Hear About the Morgans? Actual genre: entertaining, murder Predicted tag: ['flashback' 'murder']
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
4. TfidfVectorizer with (1 - 4 Grams):
tf_vectorizer = TfidfVectorizer(min_df=0.09, tokenizer = lambda x: x.split(" "), ngram_range=(1, 4)) X_train_multilabel = tf_vectorizer.fit_transform(X_train) X_test_multilabel = tf_vectorizer.transform(X_test) print("Dimensions of train data X:",X_train_multilabel.shape, "Y :",y_train_multilabel.shape) print("Dimensions of test data X:",X_test_multilabel.shape,"Y:",y_test_multilabel.shape)
Dimensions of train data X: (10989, 666) Y : (10989, 3) Dimensions of test data X: (2768, 666) Y: (2768, 3)
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
4.1 OneVsRestClassifier + MultinomialNB :
mb = MultinomialNB(class_prior = [0.5, 0.5]) clf = OneVsRestClassifier(mb) clf.fit(X_train_multilabel, y_train_multilabel) prediction13 = clf.predict(X_test_multilabel) precision13 = precision_score(y_test_multilabel, prediction13, average='micro') recall13 = recall_score(y_test_multilabel, prediction13, average='micro') f1_score13 = 2*((precision13 * recall13)/(precision13 + recall13)) print("precision13: {:.4f}, recall13: {:.4f}, F1-measure: {:.4f}".format(precision13, recall13, f1_score13)) for i in range(5): k = test.sample(1).index[0] print("Movie: ", test['title'][k]) print("Actual genre: ",y_test[k]) print("Predicted tag: ", cnt_vectorizer.inverse_transform(prediction13[k])[0],"\n")
Movie: Hold Your Breath Actual genre: violence Predicted tag: ['flashback' 'murder' 'violence'] Movie: Nae Yeojachinguneun Gumiho Actual genre: romantic Predicted tag: [] Movie: World Without End Actual genre: murder Predicted tag: ['violence'] Movie: Absolon Actual genre: philosophical Predicted tag: ['flashback' 'murder' 'violence'] Movie: Dread Actual genre: violence, cruelty, murder, flashback Predicted tag: ['flashback' 'murder' 'violence']
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
4.2 OneVsRestClassifier + SGDClassifier with LOG Loss :
sgl = SGDClassifier(loss='log', class_weight='balanced') clf = OneVsRestClassifier(sgl) clf.fit(X_train_multilabel, y_train_multilabel) prediction14 = clf.predict(X_test_multilabel) precision14 = precision_score(y_test_multilabel, prediction14, average='micro') recall14 = recall_score(y_test_multilabel, prediction14, average='micro') f1_score14 = 2*((precision14 * recall14)/(precision14 + recall14)) print("precision14: {:.4f}, recall14: {:.4f}, F1-measure: {:.4f}".format(precision14, recall14, f1_score14)) for i in range(5): k = test.sample(1).index[0] print("Movie: ", test['title'][k]) print("Actual genre: ",y_test[k]) print("Predicted tag: ", cnt_vectorizer.inverse_transform(prediction14[k])[0],"\n")
Movie: The Spanish Main Actual genre: intrigue, action, violence Predicted tag: ['violence'] Movie: The Importance of Being Earnest Actual genre: romantic Predicted tag: [] Movie: Anastasia Actual genre: romantic, cute, entertaining Predicted tag: ['flashback'] Movie: Flawless Actual genre: violence, romantic, murder, storytelling Predicted tag: ['flashback' 'murder'] Movie: 8MM Actual genre: mystery, cruelty, murder, neo noir, cult, revenge, violence, suspenseful, sadist Predicted tag: ['murder' 'violence']
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
4.3 OneVsRestClassifier + SGDClassifier with HINGE Loss :
sgh = SGDClassifier(loss='hinge', class_weight='balanced') clf = OneVsRestClassifier(sgh) clf.fit(X_train_multilabel, y_train_multilabel) prediction15 = clf.predict(X_test_multilabel) precision15 = precision_score(y_test_multilabel, prediction15, average='micro') recall15 = recall_score(y_test_multilabel, prediction15, average='micro') f1_score15 = 2*((precision15 * recall15)/(precision15 + recall15)) print("precision15: {:.4f}, recall15: {:.4f}, F1-measure: {:.4f}".format(precision15, recall15, f1_score15)) for i in range(5): k = test.sample(1).index[0] print("Movie: ", test['title'][k]) print("Actual genre: ",y_test[k]) print("Predicted tag: ", cnt_vectorizer.inverse_transform(prediction15[k])[0],"\n")
Movie: Elizabeth: The Golden Age Actual genre: intrigue Predicted tag: ['murder'] Movie: Dishonored 2 Actual genre: sci-fi Predicted tag: ['murder' 'violence'] Movie: In Your Eyes Actual genre: paranormal, romantic, fantasy, mystery Predicted tag: [] Movie: Final Fantasy: The Spirits Within Actual genre: psychedelic, romantic, flashback Predicted tag: ['violence'] Movie: From A to Z-Z-Z-Z Actual genre: psychedelic Predicted tag: []
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
4.4 OneVsRestClassifier + LogisticRegression:
lr = LogisticRegression(class_weight='balanced') clf = OneVsRestClassifier(lr) clf.fit(X_train_multilabel, y_train_multilabel) prediction16 = clf.predict(X_test_multilabel) precision16 = precision_score(y_test_multilabel, prediction16, average='micro') recall16 = recall_score(y_test_multilabel, prediction16, average='micro') f1_score16 = 2*((precision16 * recall16)/(precision16 + recall16)) print("precision16: {:.4f}, recall16: {:.4f}, F1-measure: {:.4f}".format(precision16, recall16, f1_score16)) for i in range(5): k = test.sample(1).index[0] print("Movie: ", test['title'][k]) print("Actual genre: ",y_test[k]) print("Predicted tag: ", cnt_vectorizer.inverse_transform(prediction16[k])[0],"\n")
Movie: Red Sky Actual genre: violence, murder Predicted tag: [] Movie: Last Summer Actual genre: violence, cruelty, romantic Predicted tag: [] Movie: Real Life Actual genre: satire Predicted tag: [] Movie: One Crazy Summer Actual genre: psychedelic Predicted tag: [] Movie: Mumsy, Nanny, Sonny & Girly Actual genre: insanity, cult, murder Predicted tag: []
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
Conclusion:
from prettytable import PrettyTable tabel = PrettyTable() tabel.field_names=['Model','Vectorizer','ngrams','Precision','recall','f1_score'] tabel.add_row(['MultinomialNB', 'TfidfVectorizer', '(1, 1)', round(precision1, 3),round(recall1, 3), round(f1_score1, 3)]) tabel.add_row(['SGDClassifier(log)', 'TfidfVectorizer', '(1, 1)', round(precision2, 3), round(recall2, 3), round(f1_score2, 3)]) tabel.add_row(['SGDClassifier(hinge)','TfidfVectorizer','(1, 1)' ,round(precision3, 3), round(recall3, 3), round(f1_score3, 3)]) tabel.add_row(['LogisticRegression','TfidfVectorizer','(1, 1)', round(precision4, 3), round(recall4, 3), round(f1_score4, 3)]) tabel.add_row(['','','','','','']) tabel.add_row(['','','','','','']) tabel.add_row(['MultinomialNB', 'TfidfVectorizer', '(1, 2)', round(precision5, 3), round(recall5, 3), round(f1_score5, 3)]) tabel.add_row(['SGDClassifier(log)', 'TfidfVectorizer', '(1, 2)', round(precision6, 3), round(recall6, 3), round(f1_score6, 3)]) tabel.add_row(['SGDClassifier(hinge)','TfidfVectorizer','(1, 2)', round(precision7, 3), round(recall7, 3), round(f1_score7, 3)]) tabel.add_row(['LogisticRegression','TfidfVectorizer','(1, 2)', round(precision8, 3), round(recall8, 3), round(f1_score8, 3)]) tabel.add_row(['','','','','','']) tabel.add_row(['','','','','','']) tabel.add_row(['MultinomialNB', 'TfidfVectorizer', '(1, 3)', round(precision9, 3), round(recall9, 3), round(f1_score9, 3)]) tabel.add_row(['SGDClassifier(log)', 'TfidfVectorizer', '(1, 3)', round(precision10, 3), round(recall10, 3), round(f1_score10, 3)]) tabel.add_row(['SGDClassifier(hinge)','TfidfVectorizer','(1, 3)', round(precision11, 3), round(recall11, 3), round(f1_score11, 3)]) tabel.add_row(['LogisticRegression','TfidfVectorizer','(1, 3)', round(precision12, 3), round(recall12, 3), round(f1_score12, 3)]) tabel.add_row(['','','','','','']) tabel.add_row(['','','','','','']) tabel.add_row(['MultinomialNB', 'TfidfVectorizer', '(1, 4)', round(precision13, 3), round(recall13, 3), round(f1_score13, 3)]) tabel.add_row(['SGDClassifier(log)', 'TfidfVectorizer', '(1, 4)', round(precision14, 3), round(recall14, 3), round(f1_score14, 3)]) tabel.add_row(['SGDClassifier(hinge)','TfidfVectorizer','(1, 4)', round(precision15, 3), round(recall15, 3), round(f1_score15, 3)]) tabel.add_row(['LogisticRegression','TfidfVectorizer','(1, 4)', round(precision16, 3), round(recall16, 3), round(f1_score16, 3)]) print(tabel)
+----------------------+-----------------+--------+-----------+--------+----------+ | Model | Vectorizer | ngrams | Precision | recall | f1_score | +----------------------+-----------------+--------+-----------+--------+----------+ | MultinomialNB | TfidfVectorizer | (1, 1) | 0.467 | 0.686 | 0.556 | | SGDClassifier(log) | TfidfVectorizer | (1, 1) | 0.506 | 0.668 | 0.576 | | SGDClassifier(hinge) | TfidfVectorizer | (1, 1) | 0.511 | 0.661 | 0.576 | | LogisticRegression | TfidfVectorizer | (1, 1) | 0.508 | 0.684 | 0.583 | | | | | | | | | | | | | | | | MultinomialNB | TfidfVectorizer | (1, 2) | 0.468 | 0.686 | 0.556 | | SGDClassifier(log) | TfidfVectorizer | (1, 2) | 0.516 | 0.678 | 0.586 | | SGDClassifier(hinge) | TfidfVectorizer | (1, 2) | 0.491 | 0.702 | 0.578 | | LogisticRegression | TfidfVectorizer | (1, 2) | 0.508 | 0.685 | 0.583 | | | | | | | | | | | | | | | | MultinomialNB | TfidfVectorizer | (1, 3) | 0.468 | 0.686 | 0.556 | | SGDClassifier(log) | TfidfVectorizer | (1, 3) | 0.517 | 0.669 | 0.583 | | SGDClassifier(hinge) | TfidfVectorizer | (1, 3) | 0.496 | 0.686 | 0.576 | | LogisticRegression | TfidfVectorizer | (1, 3) | 0.508 | 0.685 | 0.583 | | | | | | | | | | | | | | | | MultinomialNB | TfidfVectorizer | (1, 4) | 0.468 | 0.686 | 0.556 | | SGDClassifier(log) | TfidfVectorizer | (1, 4) | 0.507 | 0.686 | 0.583 | | SGDClassifier(hinge) | TfidfVectorizer | (1, 4) | 0.495 | 0.689 | 0.576 | | LogisticRegression | TfidfVectorizer | (1, 4) | 0.508 | 0.685 | 0.583 | +----------------------+-----------------+--------+-----------+--------+----------+
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
5. Word2Vec
X_train_new = [] for i in tqdm(range(len(list(X_train)))): X_train_new.append(X_train[i].split(" ")) with open('glove.6B.300d.pkl', 'rb') as f: new_model = pickle.load(f) words = set(new_model.keys()) X_train_multilabel = []; # the avg-w2v for each sentence/review is stored in this list for sentence in tqdm(X_train.values): # for each review/sentence vector = np.zeros(300) # as word vectors are of zero length cnt_words =0; # num of words with a valid vector in the sentence/review for word in sentence.split(): if word in words: vector += new_model[word] cnt_words += 1 if cnt_words != 0: vector /= cnt_words X_train_multilabel.append(vector) X_test_multilabel = []; # the avg-w2v for each sentence/review is stored in this list for sentence in tqdm(X_test.values): # for each review/sentence vector = np.zeros(300) # as word vectors are of zero length cnt_words =0; # num of words with a valid vector in the sentence/review for word in sentence.split(): if word in words: vector += new_model[word] cnt_words += 1 if cnt_words != 0: vector /= cnt_words X_test_multilabel.append(vector)
100%|█████████████████████████████████████████████████████████████████████████████| 2768/2768 [00:03<00:00, 877.01it/s]
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
5.1 OneVsRestClassifier + SGDClassifier with LOG Loss :
sgl = SGDClassifier(loss='log', class_weight='balanced') clf = OneVsRestClassifier(sgl) clf.fit(X_train_multilabel, y_train_multilabel) prediction17 = clf.predict(X_test_multilabel) precision17 = precision_score(y_test_multilabel, prediction17, average='micro') recall17 = recall_score(y_test_multilabel, prediction17, average='micro') f1_score17 = 2*((precision17 * recall17)/(precision17 + recall17)) print("precision17: {:.4f}, recall17: {:.4f}, F1-measure: {:.4f}".format(precision17, recall17, f1_score17)) for i in range(5): k = test.sample(1).index[0] print("Movie: ", test['title'][k]) print("Actual genre: ",y_test[k]) print("Predicted tag: ", cnt_vectorizer.inverse_transform(prediction17[k])[0],"\n")
Movie: Topper Actual genre: comedy Predicted tag: [] Movie: La otra Actual genre: murder, melodrama Predicted tag: ['flashback' 'murder'] Movie: Conan the Destroyer Actual genre: murder, cult, fantasy, alternate history, violence Predicted tag: ['violence'] Movie: Magnificent Obsession Actual genre: melodrama, flashback Predicted tag: ['flashback'] Movie: Lilja 4-ever Actual genre: tragedy, violence, depressing Predicted tag: ['flashback' 'murder' 'violence']
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
5.2 OneVsRestClassifier + SGDClassifier with HINGE Loss :
sgh = SGDClassifier(loss='hinge', class_weight='balanced') clf = OneVsRestClassifier(sgh) clf.fit(X_train_multilabel, y_train_multilabel) prediction18 = clf.predict(X_test_multilabel) precision18 = precision_score(y_test_multilabel, prediction18, average='micro') recall18 = recall_score(y_test_multilabel, prediction18, average='micro') f1_score18 = 2*((precision18 * recall18)/(precision18 + recall18)) print("precision18: {:.4f}, recall18: {:.4f}, F1-measure: {:.4f}".format(precision18, recall18, f1_score18)) for i in range(5): k = test.sample(1).index[0] print("Movie: ", test['title'][k]) print("Actual genre: ",y_test[k]) print("Predicted tag: ", cnt_vectorizer.inverse_transform(prediction18[k])[0],"\n")
Movie: Orange County Actual genre: flashback Predicted tag: [] Movie: Mo' Money Actual genre: murder Predicted tag: ['flashback' 'murder' 'violence'] Movie: Serbuan maut Actual genre: cult, suspenseful, murder, violence, flashback Predicted tag: ['murder' 'violence'] Movie: Dog Park Actual genre: romantic Predicted tag: [] Movie: Aan Actual genre: romantic Predicted tag: []
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
5.3 OneVsRestClassifier + LogisticRegression:
lr = LogisticRegression(class_weight='balanced') clf = OneVsRestClassifier(lr) clf.fit(X_train_multilabel, y_train_multilabel) prediction19 = clf.predict(X_test_multilabel) precision19 = precision_score(y_test_multilabel, prediction19, average='micro') recall19 = recall_score(y_test_multilabel, prediction19, average='micro') f1_score19 = 2*((precision19 * recall19)/(precision19 + recall19)) print("precision19: {:.4f}, recall19: {:.4f}, F1-measure: {:.4f}".format(precision19, recall19, f1_score19)) for i in range(5): k = test.sample(1).index[0] print("Movie: ", test['title'][k]) print("Actual genre: ",y_test[k]) print("Predicted tag: ", cnt_vectorizer.inverse_transform(prediction19[k])[0],"\n")
Movie: In the Line of Fire Actual genre: suspenseful, neo noir, murder, mystery, violence, revenge, flashback, good versus evil, humor, action, romantic Predicted tag: ['flashback' 'murder' 'violence'] Movie: Huang jia shi jie Actual genre: violence Predicted tag: ['murder'] Movie: The Mirror Crack'd Actual genre: melodrama, mystery, satire, murder, flashback Predicted tag: ['flashback' 'murder'] Movie: Troll Actual genre: fantasy Predicted tag: ['violence'] Movie: Doragon bôru Z: Ginga girigiri!! Butchigiri no sugoi yatsu Actual genre: violence Predicted tag: ['violence']
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
Conclusion
from prettytable import PrettyTable tabel = PrettyTable() tabel.field_names=['Model', 'Vectorizer', 'Precision','recall','f1_score'] tabel.add_row(['SGDClassifier(log)', 'AVG W2V', round(precision17, 3), round(recall17, 3), round(f1_score17, 3)]) tabel.add_row(['SGDClassifier(hinge)','AVG W2V', round(precision18, 3), round(recall18, 3), round(f1_score18, 3)]) tabel.add_row(['LogisticRegression','AVG W2V', round(precision19, 3), round(recall19, 3), round(f1_score19, 3)]) print(tabel)
+----------------------+------------+-----------+--------+----------+ | Model | Vectorizer | Precision | recall | f1_score | +----------------------+------------+-----------+--------+----------+ | SGDClassifier(log) | AVG W2V | 0.423 | 0.788 | 0.551 | | SGDClassifier(hinge) | AVG W2V | 0.462 | 0.69 | 0.554 | | LogisticRegression | AVG W2V | 0.476 | 0.686 | 0.562 | +----------------------+------------+-----------+--------+----------+
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
6. LSTM-CNN Model
max_review_length = 400 X_train = sequence.pad_sequences(X_train_multilabel, maxlen=max_review_length, padding='post') X_test = sequence.pad_sequences(X_test_multilabel, maxlen=max_review_length, padding='post') inputt = 8252 batch_size = 32 epochs = 10 model =Sequential() model.add(Embedding(inputt, 50, input_length=max_review_length)) model.add(LSTM(100, return_sequences=True)) model.add(Dropout(0.2)) model.add(BatchNormalization()) model.add(LSTM(100, return_sequences=True)) model.add(Dropout(0.2)) model.add(BatchNormalization()) model.add(LSTM(100, return_sequences=True)) model.add(Dropout(0.2)) model.add(Activation('relu')) model.add(BatchNormalization()) model.add(GlobalMaxPooling1D()) model.add(Dense(3, activation='sigmoid')) print(model.summary()) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X_train, y_train_multilabel, batch_size = batch_size, validation_data=(X_test, y_test_multilabel), epochs=epochs) test_loss, test_acc = model.evaluate(X_test, y_test_multilabel, verbose=2) print('\nTest accuracy:', test_acc) model.save('lstm_model_top3.h5') #Saving the Model for Future Use model = load_model('lstm_model_top3.h5') #Loading the Model model_prediction = model.predict(X_test, verbose=0) for i in range(5): k = test.sample(1).index[0] print("Movie: ", test['title'][k]) print("Actual genre: ", y_test[k]) print("Predicted tag: ", cnt_vectorizer.inverse_transform(model_prediction[k])[0],"\n")
Movie: Beyond Tomorrow Actual genre: romantic, murder Predicted tag: ['flashback' 'murder' 'violence'] Movie: Rabbit's Kin Actual genre: psychedelic Predicted tag: ['flashback' 'murder' 'violence'] Movie: Zerophilia Actual genre: pornographic Predicted tag: ['flashback' 'murder' 'violence'] Movie: Austin Powers: International Man of Mystery Actual genre: comedy, boring, cult, good versus evil, psychedelic, humor, satire, revenge, entertaining Predicted tag: ['flashback' 'murder' 'violence'] Movie: The Lost World Actual genre: revenge Predicted tag: ['flashback' 'murder' 'violence']
Apache-2.0
IPYNB Notebooks/modeling_with_top_3_tags.ipynb
sandeeppanda22/Movie-Tag-Prediction-
Jupyter Notebook: Prioritization of Syphilis Serologies for Investigation (Modernizing the Syphilis Reactor Grid) Notes to keep in mind when using this notebook:* Please ignore the number on the left (that says "In [x]") when running these cells. When we refer to a cell number, look for it in the beginning of the cell body. Cell number 1: This cell is for importing python libraries to support the codes that have been used in this Notebook.
# Cell number 1 import sys import pandas as pd import numpy as np import os import textwrap import datetime as dt from collections import defaultdict # warning suppression import warnings warnings.filterwarnings('ignore')
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
Cell number 2: Jupyter Notebook cells output only 1 result by default. Lines 3-4 enable the cell to output all the results as an outcome of the script in the cell. This cell also holds several utility functions for the main algorithm loop. We've also included a convenience function to convert XLSX (excel) files to CSV files.
# Cell number 2 from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" ### Utility Functions # cleans a column of strings by typecasting to str and stripping whitespace def cleanstring(df, column): df[column] = df[column].astype(str) # converts column items into string df[column] = [x.strip() for x in df[column]] # removes any whitespace from the strings generated previously # these functions are used in the algorithm main loop towards the bottom of this notebook def reactive_nTT(df:pd.DataFrame, col:str, R:str, W:str, U:str, P:str) -> pd.DataFrame: return df[(df[col] != R) & (df[col] != W) & (df[col] != U) & (df[col] != P)]; def step3_nonreactive_TT(df:pd.DataFrame, col:str, R:str, W:str, U:str, P:str) -> pd.DataFrame: return df[(df[col] == R) | (df[col] == W) | (df[col] == U) | (df[col] == P)]; def step4_TT(df:pd.DataFrame, col:str, filters:list) -> pd.DataFrame: return df[(df[col] == filters[0]) | (df[col] == filters[1]) | (df[col] == filters[2]) | (df[col] == filters[3]) | (df[col] == filters[4]) | (df[col] == filters[5]) | (df[col] == filters[6]) | (df[col] == filters[7]) | (df[col] == filters[8]) | (df[col] == filters[9])]; ###### # converts a given excel file to a csv def excel2csv(file, name): p = pd.read_excel(file) p.to_csv(f'{name}.csv', sep=",")
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
Cell number 3: This is the script to import and read the CSV file. Please copy/paste the address of your file in place of "Please enter your file path and file name here.csv". This file is read into a DataFrame: `df_main`. It may take a while for the data to be read into `df_main`, so please wait for the cell to be fully executed before proceeding.
#Cell number 3 df_main = pd.read_csv("Please enter your file path and file name here.csv")
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
Cell number 4: Displays the column names of the imported file ( saved as `df_main`) and the first 5 lines of your uploaded dataframe
#Cell number 4 df_main_columns = df_main.columns df_main.columns = [x.strip() for x in df_main.columns] df_main.columns df_main.head()
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
Cell number 5: This changes the column names for the dataframe. The DataFrame might contain more elements than is required for this algorithm. Those column names can be left as is. Please change the corresponding column names for the following data elements to:| Column Name | Data Element || --- | --- || `ID_Profile` | Unique identifier for an individual || `Test` | Name of the test (e.g. VDRL, RPR, TP-AB, FTA-ABS) || `DT_Specimen` | Date of the above test (specimen collected) || `QuantitativeResult` | Quantitative result for test (titer) || `QualitativeResult` | Qualitative result for test || `CD_Gender` | Gender || `Age` | Age (in years) || `Disposition` | Disposition assigned || `DT_Disposition` | Date the disposition was assigned by the DIS (or the STD program) |_Note: We require that age be in years. Please handle this yourself or email the maintainers for further assistance._ For example, if the output of cell number 4 is: `['columnA', 'UniqueIdentifier', 'columnB', 'QualitativeResult','DateOfSpecimen', 'columnC', 'QuantitativeResult', 'NameOfTest', 'columnD','Gender',' Age', 'DS_Disposition','DT_Disposition']` Your code will be:`df_main.columns = ['columnA', 'ID_Profile', 'columnB', 'QualitativeResult' ,'DT_Specimen', 'columnC', 'QuantitativeResult', 'Test', 'columnD','CD_Gender', 'Age', 'Disposition','DT_Disposition']` Put any column renaming in the cell below:
#Cell number 5 df_main.columns df_main.rename(columns={'DS_QualitativeResult':'QualitativeResult', 'DS_QuantitativeResult':'QuantitativeResult', 'DS_Test':'Test', 'DS_Disposition':'Disposition'}, inplace=True) df_main.columns
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
Cell number 6: The CSV file does not have date attributes. The script below will assign a python date attribute to this column. The same script can be used for any other date elements. **The CSV file must contain date the date in the YYYY-MM-DD format. If it is not possible to create it in this format, please let us know.** The final line in this cell creates a new column and assigns the index number of the row to it. This will be used to join on at later stages. If you see output in this cell, please ignore it.
#Cell number 6 # function to convert strings in column `var` in pandas DataFrame `df` to datetime def str2date(df, var, dateformat='%Y-%m-%d'): cleanstring(df, var) # The line below can be adjusted to meet unique formats. For example, if the date appears as MM/DD/YYYY, the following # format will work: '%m/%d/%Y' Please let us know if you have more complicated date formats. # Furthermore, the last parameter can be customized in the function call section to change the specific date time to match your dataset # See the function calls section below for a commented out example of this df[var] = pd.to_datetime(df[var], format=dateformat) # converts the string to a datetime if it follows YYYY-MM-DD format # function calls str2date(df_main, 'DT_Specimen') str2date(df_main, 'DT_Disposition') ## function call example showing how to process datetimes for DT_Specimen if the format is MM/DD/YYYY # str2date(df_main, 'DT_Specimen', dateformat='%m/%d/%Y') df_main['S_No'] = df_main.index
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
Cell number 7: The database might default titers as '1:x', the following code removes the '1:' part from it and converts it to an integer. Only use the script below if the quantitative result in the dataframe is not extracted as a number. The script below takes away "1:" from, converts it into a number, and converts nan (No value) to 0. Cell number 7.b will execute the cleaning.
#Cell number 7 def cleannum(a): if a == 'nan': return 0 else: return (a[2:]) def cleanquant(df, var): cleanstring(df, var) df['quanttest'] = df[var].apply(cleannum) df['quanttest'] = df['quanttest'].astype(int) # cell number 7.b df_main['QuantitativeResult'].value_counts() # execute function cleanquant(df_main, 'QuantitativeResult') df_main['quanttest'].value_counts() df_main.columns df_main['QuantitativeResult'].value_counts()
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
Cell number 8: If the quantitative result or titer was a number in the data extract and cell number 7 was not required, we change the column name to `quanttest` Run Cell number 8 customized to the column headings, labelling the column with titer results (quantitative results) as quanttest, only if cell number 7 was not required
#Cell number 8 #df_main.columns = ['columnA', 'ID_Profile', 'columnB', 'DS_QualitativeResult','DT_Specimen', 'columnC', 'quanttest', 'DS_Test', 'columnD','CD_Gender','Age_clean']
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
Cell number 9: As part of data-wrangling, the following script ensures that the values for `ID_Profile`, `QualitativeResult`, and `Test` do not contain any spaces and are in string format. The data type displayed should show :| Column Name | Datatype || --- | --- || `ID_Profile` | `object` || `Test` | `object` || `DT_Specimen` | `datetime64[ns]` || `QuantitativeResult` | `object` || `quanttest` | `int32` || `CD_Gender` | `object` || `Age_clean` | `int32` || `Disposition` | `object` || `DT_Disposition` | `datetime64[ns]` |
#Cell number 9 dirty_columns = ['ID_Profile', 'QualitativeResult', 'Test', 'CD_Gender', 'Disposition'] for c in dirty_columns: cleanstring(df_main, c) df_main.dtypes
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
Cell number 10: Removes all tests with no dates (they can't be calculated in the algorithm) and reveals how many rows and columns are there in the DataFrame. The following step is not compulsory, but it ensures that all specimen dates have dates else the program will crash.
# Cell number 10 nulldates = df_main[df_main['DT_Specimen'].isnull()] beforelen = len(np.unique(nulldates['ID_Profile'])) nulldates_idx = nulldates.index df_main = df_main.drop(nulldates_idx) afterlen = len(np.unique(df_main['ID_Profile'])) # ------ output ------ print(f"") print(f"Number of Null Dates Before Removal: {beforelen}") print(f"Shape: {df_main.shape}") print(f"Number of Tests After Null Removal: {afterlen}")
Number of Null Dates Before Removal: 7946 Shape: (534599, 24) Number of Tests After Null Removal: 113507
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
Cell number 11: Creating a DataFrame for running the algorithm with only the essential columns. Since we select the core data elements, we remove duplicates (same person, same test, same result, same day). The row index is created as a separate column. This `index_no` will be used to join the rest of the data elements for analysis later on We display the number of rows and columns in this DataFrame. There should be 10 columns, the rows depend on how big the dataset is
# Cell number 11 df_main_dd = df_main[['ID_Profile','Test','DT_Specimen','quanttest','QualitativeResult','DT_Disposition']] df_main_dd = df_main_dd.drop_duplicates() df_main_dd['index_no'] = df_main_dd.index df_main_dd = df_main_dd.merge(df_main, left_on = 'index_no', right_on = 'S_No', how = 'left') # df_main_dd drops invalid tests with no assigned date # if there is an error, see below df_main_dd = df_main_dd[['ID_Profile_x', 'Test_x', 'DT_Specimen_x', 'quanttest_x', 'QualitativeResult_x','DT_Disposition_x', 'index_no', 'CD_Gender', 'Disposition', 'Age']] df_main_dd.columns = ['ID_Profile','Test','DT_Specimen','quanttest','QualitativeResult', 'DT_Disposition','index_no','CD_Gender', 'Disposition', 'Age'] #if there is an error: #It could be because the column names did not match #In a separate cell, please run #df_main_dd.dtypes #df_main_dd.columns #under the comment above, please insert how the column name appears in your output in place of these fields above: #['ID_Profile_x', 'DS_Test_x', 'DT_Specimen_x', 'quanttest_x', #'DS_QualitativeResult_x', 'index_no', 'CD_Gender', #'DS_Disposition', 'Age_clean'] # This cell simply prints the dimension of the dataset as well as the column names. # Feel free to use this cell to debug the previous cell. df_main_dd.shape df_main_dd.columns df_main_dd.dtypes
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
Cell number 12: This is were we define all of our variables. This ensures that we don't have to modify the codes everytime and can just make some adjustments here
# Cell number 12 #Step 8 allows for a cut-off date for titers since we found that titers can be from a long time ago and should not be compared. #This can be modified anytime. We define the duration as 'DaysBetweenTests' DaysBetweenTests = 365 #Step 8 quantifies what should be considered a high titer, given that the previous test is much older #This can be modified anytime. We define the titer cutoff as 'TiterCutOff' TiterCutOff = 32 #'Female' maybe coded in many foms, please assign the exact variable as it is in your DataFrame Female = 'F' #Step 8 also considers female of reproductive age, to prevent congenital syphilis. We have set the cut-off age as 50 #This can be modified anytime. We define the age as 'FemaleAge' FemaleAge = 50 #Step 8 was added, in part, to prevent congenital syphilis. For the general population, older titer is considered > 1year #For females of reproductive age, we consider the duration as 180 days and high titer as more than 1:9 #This can be modified anytime. We define the duration as 'FemaleDaysBetweenTests' and the titer as 'FemaleTiterCutOff' FemaleDaysBetweenTests = 180 FemaleTiterCutOff = 8 #Step 8: We found that if patient was not previously treated, their titer might not change and can be reached now #Please assign the exact disposition that the DIS had assigned corresponding to an individual who was infected but not treated disposition_InfNotTx = 'Infected, Not Treated' #Please assign the exact disposition that the DIS had assigned corresponding to an individual who was uable to be located unable_to_locate = 'Unable to Locate' #Please assign the exact disposition that the DIS had assigned corresponding to an individual who was out of jurisdiction OOJ = 'Administrative Closure OOJ' # Please assign values to the corresponding variable as it appears in your dataframe: #R is for reactive tests R = 'R' #W is for weakly positive/reactive tests W = 'W' #U is for unknown U = 'U' #P is for positive. RAPID tests seem to be assigned this qualitative result P = 'P' #N is for negative tests N = 'N' #Please assign how each non-Treponemal Test is coded in your dataframe. ONLY these 5 tests will be considered as NTTs. RPR = 'RPR' VDRL = 'VDRL' CSF_VDRL = 'CSF-VDRL' RPR_CordBlood = 'RPR Cord Blood' TRUST = 'TRUST' #Please assign how each Treponemal Test is coded in your dataframe. ONLY these10 tests will be considere as TTs. FTA_ABS = 'FTA-ABS' IgG_EIA = 'IgG EIA' TP_AB = 'TP-AB' TP_PA = 'TP-PA' RAPID = 'RAPID' EIA = 'EIA' MHATP = 'MHATP' FTA_IgG = 'FTA-IgG' CIA = 'CIA (CLIA)' TPHA = 'TPHA' #This defines all the Treponemal Tests used for filtering the dataframe in the main loop. tests = [FTA_ABS, IgG_EIA, TP_AB, TP_PA, RAPID, EIA, MHATP, FTA_IgG, CIA, TPHA]
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
Algorithm to Prioritize Reactive Non-Treponemal Tests Reported to Health Departments for Investigating Suspected Cases of Syphilis![algorithm diagram](../algorithm_manuscript_revised_final.png) Step 1: select only reactive Non-Treponemal Tests (NTT) Cell number 13 selects the tests for Step 1 in the algorithm
# cell number 13 dfm_6m_ntt = df_main_dd[(df_main_dd['Test'] == RPR) | (df_main_dd['Test'] == VDRL) | (df_main_dd['Test'] == CSF_VDRL)| (df_main_dd['Test'] == RPR_CordBlood)|(df_main_dd['Test']==TRUST)] dfm_6m_ntt = dfm_6m_ntt[(dfm_6m_ntt['QualitativeResult'] == R) | (dfm_6m_ntt['QualitativeResult'] == W) | (dfm_6m_ntt['QualitativeResult'] == U)] dfm_6m_ntt = [group[group['DT_Specimen'] == group['DT_Specimen'].max()] for name , group in dfm_6m_ntt.groupby("ID_Profile")] dfm_6m_ntt = pd.concat(dfm_6m_ntt) dfm_6m_ntt['Test'].value_counts() dfm_6m_ntt.shape np.unique(dfm_6m_ntt['ID_Profile'])
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
Cell number 13.1. We want to identify the first test in the latest DT_Disposition (episode of disease). Ideally, we would want to assign a disposition to this first test For the purpose of this study, we identify the latest test in the database to simulate it as the current, reported test under evaluation that the algorithm would assign a disposition to. Typically, this is straightforward, we just locate the latest test by reviewing the date when the specimen was collected (`DT_Specimen`). However, in some cases (specifically for a retrospective analysis of a large dataset), identifying the latest test will lead to errors in the disposition. This is because sometimes dispositions are assigned to an ___episode___ of infection, which may be represented by multiple reported serologies over a period of time. We determined that if a disposition was assigned for a group of tests representing one episode of infection, the disposition date (`DT_Disposition`) would be the same (even if there could potentially be multiple serologies reported over that period of __one__ infectious episode). The figure represents the testing history of an individual. The serologies contained within the yellow rectangle are represented by a single disposition date and would represent __one episode of infection__. Therefore, we must identify the first test in that episode to assign the disposition to since subsequent serologies would be follow-up serologies. It would also be inaccurate to assign disposition to the follow-up serologies. For e.g., the serologies contained within the red rectangle is the latest test, however, the algorithm would close it because it is not a 4-fold increase compared to the previous titer (and they fall under the same infectious period). The first test would be opened because 1:128 (tested on 02/27/2018) would represent a 4-fold increase compared to the previous titer of 1:16 (tested on 01/17/2017).![first test diagram](../Explaining_FirstTest.png)
#13.1 list1 = np.unique(dfm_6m_ntt['ID_Profile']) len(list1) df_first_test = pd.DataFrame(columns=['ID_Profile','Test','DT_Specimen','quanttest','QualitativeResult','CD_Gender', 'Age', 'DT_Disposition', 'index_no']) for i in list1: IncTest = dfm_6m_ntt[dfm_6m_ntt['ID_Profile']==i] time_IncTest = IncTest['DT_Disposition'] time_IncTest = time_IncTest.values[0] df_all = df_main[df_main['ID_Profile'] == i] df_all = df_all[(df_all['Test'] == RPR) | (df_all['Test'] == VDRL) | (df_all['Test'] == CSF_VDRL) | (df_all['Test'] == RPR_CordBlood) | (df_all['Test'] == TRUST)] df_sameDT = df_all[df_all['DT_Disposition'] == time_IncTest] df_earliestTest = [group[group['DT_Specimen'] == group['DT_Specimen'].min()] for name , group in df_sameDT.groupby("ID_Profile")] # skips to the next profile if its group doesn't exist if not df_earliestTest: continue df_earliestTest = pd.concat(df_earliestTest) df_first_test=df_first_test.append(df_earliestTest) df_first_test dfm_6m_ntt = df_first_test dfm_6m_ntt['Test'].value_counts() dfm_6m_ntt.shape
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
Cell number 14: A list (`profile_list`) is created with distinct unique identifiers. This profile list is used to loop in the program. A single unique identifier (`ID_Profile`) or a subset can be run by creating a list of the subset as `profile_list`. This is especially useful to debug the process and view a specific subset instead of running the entire dataset
# Cell number 14 profile_list = dfm_6m_ntt['ID_Profile'].unique() profile_list len(profile_list)
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
An example of cell 14.1 to run a fraction of the dataset (for e.g. a cut-off date) instead of the entire dataset. This will be useful to see if there are any bugs or issues.
# Cell number 14.1 profile_list = profile_list[:100] len(profile_list) #baseline_date = pd.to_datetime('20190318', format='%Y%m%d') #---->change the date within the '' to what you'd like #baseline_date #df_main_6m_ntt = df_main_dd[df_main_dd['DT_Specimen'] >= baseline_date] #df_main_6m_ntt = df_main_dd[(df_main_dd['DS_Test'] == RPR) | (df_main_dd['DS_Test'] == VDRL)|(df_main_dd['DS_Test']==CSF_VDRL)|(df_main_dd['DS_Test']==RPR_CordBlood)] #df_main_6m_ntt = df_main_6m_ntt[(df_main_6m_ntt['DS_QualitativeResult']==R) | (df_main_6m_ntt['DS_QualitativeResult']==W) | (df_main_6m_ntt['DS_QualitativeResult']==U)] #df_main_6m_ntt = [group[group['DT_Specimen'] == group['DT_Specimen'].max()] for name , group in df_main_6m_ntt.groupby("ID_Profile")] #df_main_6m_ntt = pd.concat(df_main_6m_ntt) #df_main_6m_ntt['DS_Test'].value_counts() #df_main_6m_ntt.shape
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
All of the code for the algorithm is below in cell number 1 Each loop corresponding to the Step number in the algorithm is assigned that loop number. Apart from the disposition assigned in the algorithm, tests are also assigned the exact decision point (for debugging and testing). Steps are numbered and commented at every decision node. In case there is an issue with the code, we can print each step to determine where the problem lies.
count = 0 dispo_type = 0 col1 = ['ID_Profile','Test','DT_Specimen','quanttest','QualitativeResult','CD_Gender', 'Age'] col2 = col1.copy() col2.append('index_no') # final dataframe which is written to a file at the end df_complete_merged = pd.DataFrame(columns = ['ID_Profile', 'Test_x', 'DT_Specimen_x', 'quanttest_x', 'QualitativeResult_x', 'CD_Gender_x', 'Age_x', 'index_no', 'algo_dispo', 'dispo', 'dis_type', 'Test_y', 'DT_Specimen_y', 'quanttest_y', 'QualitativeResult_y', 'CD_Gender_y', 'Age_y']) #1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 for profile_id in profile_list: #profile_id count = count+1 sero = 0 algo_dispo = 'NA' al_dis = 'NA' test_tocompare = pd.DataFrame(columns = col1) test_incoming = pd.DataFrame(columns = col2) #Dataframe df_incoming_test isolates the tests for that particular profile_id. #We will identify the test that should be assigned a disposition from this df_incoming_test = dfm_6m_ntt[dfm_6m_ntt['ID_Profile'] == profile_id] ########### This is taking in the reactive nontreponemal tests. We intend to assign a disposition to these tests, whether to administratively close or open for investigation######## #We first select the latest test as 'test_incoming', we will assign a disposition to this test if len(df_incoming_test.index) > 1: incoming_test = [group[group['DT_Specimen'] == group['DT_Specimen'].max()] for name , group in df_incoming_test.groupby("ID_Profile")] test_incoming = pd.concat(incoming_test) else: test_incoming = df_incoming_test #################### We identified test_incoming as THE TEST to assign this disposition ################### #time_of_test is the time the specimen was collected for 'test_incoming', it will be used for decision logic below time_of_test = pd.to_datetime(test_incoming['DT_Specimen'].values[0]) #!!!!!!!!!! df_match contains the entire dataset; we use this to identify the matches for the test !!!!!! df_match = df_main_dd[df_main_dd['ID_Profile'] == profile_id] #Creating a dataframe 'df_match_all' which has all the tests before 'time_of_test' for each individual ID_Profile df_match_all = df_match[df_match['DT_Specimen'] < time_of_test] #Creating a dataframe 'TT_tocompare' which has all the nonreactive treponemal tests before for each individual ID_Profile TT_tocompare = df_match TT_tocompare = reactive_nTT(TT_tocompare, 'QualitativeResult', R, W, U, P) TT_tocompare = step4_TT(TT_tocompare, 'Test', tests) TT_tocompare = TT_tocompare[~(TT_tocompare['DT_Specimen'] > time_of_test)] #Creating a marker step_3b. It is 1 when 2.b condition is met, otherwise it is 0. step_3b = 0 csf_cord = test_incoming[(test_incoming['Test'] == CSF_VDRL) | (test_incoming['Test'] == RPR_CordBlood)] #########################Step 222222222222222222222222222222222222222222222 ######################As per Step 2: current titer CSF or cord blood? ######################### if csf_cord.empty is False: csf_cord = [group[group['quanttest'] == group['quanttest'].max()] for name , group in csf_cord.groupby("ID_Profile")] test_incoming = pd.concat(csf_cord) test_incoming = test_incoming.iloc[[0]] algo_dispo = 'Open: CSF/Cord' al_dis = 'Open' dispo_type = '2.b' else: #333333333333333333333333333333333333333333333333333333333333333333333333333333 if TT_tocompare.empty is False: #If there is a Non-Reactive TT, we identify the latest test TT_tocompare = [group[group['DT_Specimen'] == group['DT_Specimen'].max()] for name , group in TT_tocompare.groupby("ID_Profile")] TT_tocompare = pd.concat(TT_tocompare) positive_TT = df_match positive_TT = step3_nonreactive_TT(positive_TT, 'QualitativeResult', R, W, U, P) positive_TT = step4_TT(positive_TT, 'Test', tests) positive_TT = positive_TT[~(positive_TT['DT_Specimen'] > time_of_test)] negative_TT = positive_TT[(positive_TT['QualitativeResult'] != R)] negative_TT = negative_TT[(positive_TT['QualitativeResult'] != W)] negative_TT = negative_TT[(positive_TT['QualitativeResult'] != U)] negative_TT = negative_TT[(positive_TT['QualitativeResult'] != P)] positive_TT = positive_TT[~(positive_TT['QualitativeResult'].isin(negative_TT['QualitativeResult']))] if len(positive_TT)>1: if (((pd.to_datetime(time_of_test) - pd.to_datetime(positive_TT['DT_Specimen'].values[0]))/np.timedelta64(1,'D')) <= 14): positive_TT = positive_TT.iloc[[0]] ##################### Step 3 in the algorithm 3333333333333333333333333333333333333 ################# Non-reactive TT in last 14 days with no reactive TT reported within this duration if (positive_TT.empty is True) & (((pd.to_datetime(time_of_test) - pd.to_datetime(TT_tocompare['DT_Specimen'].values[0]))/np.timedelta64(1,'D')) <= 14): #& (((pd.to_datetime(time_of_test) - pd.to_datetime(TT_tocompare['DT_Specimen'].values[0]))/np.timedelta64(1,'D')) >=0): #As per step 3: Non-Reactive Treponemal Test <= 14 Days Prior to Treponemal Test? ############################ algo_dispo = 'Close: TT_14d' al_dis = 'Close' dispo_type = '3.b' test_tocompare = TT_tocompare.iloc[[0]] test_incoming = test_incoming.iloc[[0]] # if serology meets this condition then 'step_3b' is assigned a value '1' and exits the next loop ######## step_3b = 1 ############################### If step 3 was not met ################################ if step_3b == 0: # test_incoming := latest test with disposition to assign to prior_test_date = df_match_all['DT_Specimen'].max() prior_test = df_match_all[df_match_all['DT_Specimen'] == prior_test_date] prior_test = step4_TT(prior_test, 'Test', tests) prior_test = reactive_nTT(prior_test, 'QualitativeResult', R, W, U, P) ########################## Step 4 in the algorithm 4444444444444444444444444444444444444444444 ###################### Penultimate test has a negative treponemal test ################### if prior_test.empty is False: test_tocompare = prior_test.iloc[[0]] test_incoming = test_incoming.iloc[[0]] algo_dispo = 'Open: Pen_N_TT' al_dis = 'Open' dispo_type = '4.b' else: ############################ Step 5 in the algorithm 555555555555555555555555555555555555555 #################### Does patient have Prior Syphilis Non-Treponemal Test? #################### #'df_match_ntt' creates a dataframe for Non_Treponemal Tests df_match_ntt = df_match_all[(df_match_all['Test'] == RPR) | (df_match_all['Test'] == VDRL)] ## Step 5 logic found in the else statement below near the end of loop close: if df_match_ntt.empty is False: incoming_test = test_incoming[test_incoming['quanttest']>0] if len(incoming_test) > 0: incoming_test = [group[group['quanttest'] == group['quanttest'].max()] for name , group in incoming_test.groupby("ID_Profile")] incoming_test = pd.concat(incoming_test) ########################## Step 6 in the algorithm 66666666666666666666666666666666666 if len(df_match_all) > 1: previouslynotx = [group[group['DT_Specimen'] == group['DT_Specimen'].max()] for name , group in df_match_all.groupby("ID_Profile")] previouslynotx = pd.concat(previouslynotx) previouslynotx = previouslynotx[(previouslynotx['Disposition'] == unable_to_locate) | (previouslynotx['Disposition'] == unable_to_locate) | (previouslynotx['Disposition'] == OOJ) | (previouslynotx['Disposition'] == disposition_InfNotTx)] else: previouslynotx = df_match_all[(df_match_all['Disposition'] == unable_to_locate) | (df_match_all['Disposition'] == unable_to_locate) | (df_match_all['Disposition'] == OOJ) | (df_match_all['Disposition'] == disposition_InfNotTx)] if len(previouslynotx)>1: previouslynotx = [group[group['DT_Specimen'] == group['DT_Specimen'].max()] for name , group in previouslynotx.groupby("ID_Profile")] previouslynotx = pd.concat(previouslynotx) ########################## Previous disposition 'infected, not treated': yes ################ if previouslynotx.empty is False: algo_dispo = 'Open: PrevNoTx' al_dis = 'Open' dispo_type = '6.b' previouslynotx = previouslynotx[['ID_Profile','Test','DT_Specimen','quanttest','QualitativeResult']] test_tocompare = previouslynotx.iloc[[0]] test_incoming = test_incoming.iloc[[0]] else: ########################## Step 7 in the algorithm 77777777777777777777777777777777777 ## Step 7 logic found in the else statement below near the end of loop close: if incoming_test.empty is False: test_incoming = incoming_test latest_titer = df_match_ntt[df_match_ntt['quanttest'] > 0] #@@@@@@ START: these codes :- ## 1: find previous titer to compare to current serology ## 2: any negative serology prior to current serology to look for serconversion if len(latest_titer) > 0: latest_titer = [group[group['DT_Specimen'] == group['DT_Specimen'].max()] for name , group in latest_titer.groupby("ID_Profile")] # 'latest_titer' identifies the previous titer, before the current reported serology latest_titer = pd.concat(latest_titer) seroconversion = df_match_ntt[df_match_ntt['QualitativeResult'] == N] seroconversion = seroconversion[seroconversion['DT_Specimen']>=latest_titer['DT_Specimen'].values[0]] else: last_titer = df_match_ntt[df_match_ntt['QualitativeResult']!=N] if len(last_titer) > 0: last_titer = [group[group['DT_Specimen'] == group['DT_Specimen'].max()] for name , group in last_titer.groupby("ID_Profile")] last_titer = pd.concat(last_titer) seroconversion = df_match_ntt[df_match_ntt['QualitativeResult'] == N] seroconversion = seroconversion[seroconversion['DT_Specimen'] >= last_titer['DT_Specimen'].values[0]] else: seroconversion = df_match_ntt[df_match_ntt['QualitativeResult'] == N] if len(seroconversion) > 1: seroconversion = [group[group['DT_Specimen'] == group['DT_Specimen'].max()] for name , group in seroconversion.groupby("ID_Profile")] seroconversion = pd.concat(seroconversion) seroconversion = seroconversion.iloc[[0]] #@@@@@@ END: these codes :- ## 1: find previous titer to compare to current serology ## 2: any negative serology prior to current serology to look for serconversion ########################## Step 8 in the algorithm 8888888888888888888888888888888888888 if latest_titer.empty is False: ############## (Current titer>1:32 AND previous titer >1 year) ##################### ############## OR ##################### ########### (Female < 50y AND titer > 1:8 AND previous titer > 6m) ################# duration = (pd.to_datetime(time_of_test) - pd.to_datetime(latest_titer['DT_Specimen'].values[0]))/np.timedelta64(1,'D') sero2 = (pd.to_datetime(seroconversion['DT_Specimen']) - pd.to_datetime(latest_titer['DT_Specimen'].values[0]))/np.timedelta64(1,'D') if (test_incoming['CD_Gender'].values[0]==Female) & (duration >= FemaleDaysBetweenTests) & (int(test_incoming['Age'].values[0]) < FemaleAge) & (test_incoming['quanttest'].values[0] > FemaleTiterCutOff): algo_dispo = 'Open: ModCrit' al_dis = 'Open' dispo_type = '8.b2' test_tocompare = latest_titer.iloc[[0]] test_incoming = test_incoming.iloc[[0]] elif (duration >= DaysBetweenTests) & (test_incoming['quanttest'].values[0]>TiterCutOff): algo_dispo = 'Open: ModCrit' al_dis = 'Open' dispo_type = '8.b1' test_tocompare = latest_titer.iloc[[0]] test_incoming = test_incoming.iloc[[0]] else: ##################### Step 9 in the algorithm 999999999999999999999999999999999999 ##################### >=4-fold Titer Increase: Yes ############################### if test_incoming['quanttest'].values[0] >= ((latest_titer['quanttest'].values[0]*2)*2): algo_dispo = 'Open: 4f' al_dis = 'Open' dispo_type = '9.b1' test_tocompare = latest_titer.iloc[[0]] test_incoming = test_incoming.iloc[[0]] else: ################# Step 10 in the algorithm 1010101010101010101010101010101010 if (test_incoming['QualitativeResult'].values[0]==R) & seroconversion.empty is False: ################# Check for serocoversion ################################### algo_dispo = 'Open: SeroConv' al_dis = 'Open' dispo_type = '10.b1' test_tocompare = seroconversion test_incoming = test_incoming.iloc[[0]] else: ################# No seroconversion, close: no 4-fold increase ############### algo_dispo = 'Close: 4f' al_dis = 'Close' dispo_type = '10.a1' test_incoming = test_incoming[test_incoming['QualitativeResult'] == R] test_incoming = test_incoming.iloc[[0]] test_tocompare = latest_titer.iloc[[0]] ############ Step 10 close loop 1010101010101010101010101010101010101010 ################ Step 9 close loop 999999999999999999999999999999999999999999 #################### if there were no titers reported previously##################### else: ################## if serconversion is present ############################ if (test_incoming['QualitativeResult'].values[0]==R) & seroconversion.empty is False: #As per step Non-Treponemal Seroconversion: Yes ********************** algo_dispo = 'Open: SeroConv' al_dis = 'Open' dispo_type = '10.b2' test_tocompare = seroconversion.iloc[[0]] test_incoming = test_incoming.iloc[[0]] ################## no seroconversion, no previous titer ############################ elif last_titer.empty is False: algo_dispo = 'Open: NoPrevTi' al_dis = 'Open' dispo_type = '9.b2' test_tocompare = last_titer.iloc[[0]] test_incoming = test_incoming.iloc[[0]] test_incoming = test_incoming.iloc[[0]] ################## does not meet 4-fold increase criteria ########################## else: algo_dispo = 'Close: 4f' al_dis = 'Close' dispo_type = '10.a2' test_incoming = test_incoming[test_incoming['QualitativeResult'] == R] test_incoming = test_incoming.iloc[[0]] test_tocompare = latest_titer.iloc[[0]] ####################### Step 8 close loop 888888888888888888888888888888888888888888 ######################## Step 7 in the algorithm############################# ####################### Quantitative titer reported on current serology? #################### else: algo_dispo = 'Open: NoC_NTT' al_dis = 'Open' dispo_type = '7.a' test_incoming = test_incoming.iloc[[0]] ########################### Step 7 close loop 77777777777777777777777777777777777777777 ############################### Step 6 close loop 66666666666666666666666666666666666666666 ######################## Step 5 in the algorithm############################# ####################### Does patient have Prior Syphilis Non-Treponemal Test? #################### else: algo_dispo = 'Open: NoM' al_dis = 'Open' dispo_type = '5.a' test_incoming = [group[group['quanttest'] == group['quanttest'].max()] for name , group in test_incoming.groupby("ID_Profile")] test_incoming = pd.concat(test_incoming) test_incoming = test_incoming.iloc[[0]] #################################### Step 5 close loop 5555555555555555555555555555555555555555 ######################################## Step 4 close loop 4444444444444444444444444444444444444444 ############################################ Step 3 close loop 3333333333333333333333333333333333333333 ################################################ Step 2 close loop 2222222222222222222222222222222222222222 test_incoming['algo_dispo'] = algo_dispo test_incoming['dispo'] = al_dis test_incoming['dis_type'] = dispo_type df_complete = pd.merge(test_incoming, test_tocompare, on='ID_Profile',how='left') df_complete_merged = df_complete_merged.append(df_complete) #1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 #print(count) #df_complete_merged
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
Cell number 16: The script below assigns 1 column for index number for the test. This index number is inherited from the original file df_main
df_complete_merged['test_index'] = df_complete_merged['index_no'].astype(str) + df_complete_merged['index_no_x'].astype(str) df_complete_merged['test_index'] = df_complete_merged['test_index'].map(lambda x: x.lstrip('nan').rstrip('nan')) df_complete_merged=df_complete_merged.drop(columns=['index_no', 'index_no_x']) str2date(df_complete_merged, 'DT_Specimen_x') str2date(df_complete_merged, 'DT_Specimen_y') df_complete_merged['day_diff'] = pd.to_datetime(df_complete_merged['DT_Specimen_x']) - pd.to_datetime(df_complete_merged['DT_Specimen_y']) df_complete_merged['day_value'] = df_complete_merged['day_diff']/np.timedelta64(1,'D') #df_complete_merged df_complete_merged['dispo'].value_counts() df_complete_merged['algo_dispo'].value_counts() df_complete_merged['dis_type'].value_counts()
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
Cell number 17 creates a CSV file for this dataset. Please replace 'ResultOfAlgorithm.csv' with a file path and name of your choice.
# Cell number 17 df_complete_merged.to_csv(r'ResultOfAlgorithm.csv', index=False)
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
Cell number 18We join the dataset generated by the algorithm script (`df_complete_merged`) on the main dataset (`df_main`). `test_index` and `S_No` are the same index inherited from `df_main`. We conduct a left join on this index number of both datasets because `Disposition` is assigned to the serology identified on `df_complete_merged`. Using `text_index` from `df_main`, we identify the test which helped make the Disposition decision in the algorithm. If there was no match found ("Open: NoM"), then there will be a missing value (`nan`) in those columns.
# Cell number 18 df_comp_merged_co = df_complete_merged.copy() df_main_co = df_main.copy() df_comp_merged_co['S_No'] = df_comp_merged_co['S_No'].astype(str) df_main_co['S_No'] = df_main_co['S_No'].astype(str) df_joined = df_comp_merged_co.merge(df_main_co, left_on='test_index',right_on = 'S_No', how='left')
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
Cell number 19 creates a CSV file for this dataset. Please replace 'AlgorithmMerged.csv' with a file path and name of your choice.
# Cell number 19 df_joined.to_csv(r'AlgorithmMerged.csv', index=False)
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
This is the end of the script for the algorithm
df_complete_merged['dispo'].value_counts() df_complete_merged['algo_dispo'].value_counts() df_complete_merged['dis_type'].value_counts() df_complete_merged.groupby(['Disposition','algo_dispo'])["ID_Profile"].count()
_____no_output_____
Apache-2.0
notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb
CDCgov/Syphilis_Record_Search_and_Review_Algorithm
Work with DataData is the foundation on which machine learning models are built. Managing data centrally in the cloud, and making it accessible to teams of data scientists who are running experiments and training models on multiple workstations and compute targets is an important part of any professional data science solution.In this notebook, you'll explore two Azure Machine Learning objects for working with data: *datastores*, and *datasets*. Connect to your workspaceTo get started, connect to your workspace.> **Note**: If you haven't already established an authenticated session with your Azure subscription, you'll be prompted to authenticate by clicking a link, entering an authentication code, and signing into Azure.
import azureml.core from azureml.core import Workspace # Load the workspace from the saved config file ws = Workspace.from_config() print('Ready to use Azure ML {} to work with {}'.format(azureml.core.VERSION, ws.name))
Ready to use Azure ML 1.22.0 to work with azure_ds_challenge
MIT
06 - Work with Data.ipynb
ChidiNdego/azure-challenge-mslearn-dp100
Work with datastoresIn Azure ML, *datastores* are references to storage locations, such as Azure Storage blob containers. Every workspace has a default datastore - usually the Azure storage blob container that was created with the workspace. If you need to work with data that is stored in different locations, you can add custom datastores to your workspace and set any of them to be the default. View datastoresRun the following code to determine the datastores in your workspace:
# Get the default datastore default_ds = ws.get_default_datastore() # Enumerate all datastores, indicating which is the default for ds_name in ws.datastores: print(ds_name, "- Default =", ds_name == default_ds.name)
azureml_globaldatasets - Default = False workspacefilestore - Default = False workspaceblobstore - Default = True
MIT
06 - Work with Data.ipynb
ChidiNdego/azure-challenge-mslearn-dp100
Extra note: Considerations for datastoresWhen planning for datastores, consider the following guidelines: When using Azure blob storage, premium level storage may provide improved I/O performance for large datasets. However, this option will increase cost and may limit replication options for data redundancy. When working with data files, although CSV format is very common, Parquet format generally results in better performance. You can access any datastore by name, but you may want to consider changing the default datastore (which is initially the built-in workspaceblobstore datastore).To change the default datastore, use the set_default_datastore() method:```ws.set_default_datastore('blob_data')``` You can also view and manage datastores in your workspace on the **Datastores** page for your workspace in [Azure Machine Learning studio](https://ml.azure.com). Upload data to a datastoreNow that you have determined the available datastores, you can upload files from your local file system to a datastore so that it will be accessible to experiments running in the workspace, regardless of where the experiment script is actually being run.
default_ds.upload_files(files=['./data/diabetes.csv', './data/diabetes2.csv'], # Upload the diabetes csv files in /data target_path='diabetes-data/', # Put it in a folder path in the datastore overwrite=True, # Replace existing files of the same name show_progress=True)
Uploading an estimated of 2 files Uploading ./data/diabetes.csv Uploaded ./data/diabetes.csv, 1 files out of an estimated total of 2 Uploading ./data/diabetes2.csv Uploaded ./data/diabetes2.csv, 2 files out of an estimated total of 2 Uploaded 2 files
MIT
06 - Work with Data.ipynb
ChidiNdego/azure-challenge-mslearn-dp100
Work with datasetsAzure Machine Learning provides an abstraction for data in the form of *datasets*. A dataset is a versioned reference to a specific set of data that you may want to use in an experiment. Datasets can be *tabular* or *file*-based. Create a tabular datasetLet's create a dataset from the diabetes data you uploaded to the datastore, and view the first 20 records. In this case, the data is in a structured format in a CSV file, so we'll use a *tabular* dataset.
from azureml.core import Dataset # Get the default datastore default_ds = ws.get_default_datastore() #Create a tabular dataset from the path on the datastore (this may take a short while) tab_data_set = Dataset.Tabular.from_delimited_files(path=(default_ds, 'diabetes-data/*.csv')) # Display the first 20 rows as a Pandas dataframe tab_data_set.take(20).to_pandas_dataframe()
_____no_output_____
MIT
06 - Work with Data.ipynb
ChidiNdego/azure-challenge-mslearn-dp100
Types of datasetDatasets are typically based on files in a datastore, though they can also be based on URLs and other sources. You can create the following types of dataset: Tabular: The data is read from the dataset as a table. You should use this type of dataset when your data is consistently structured and you want to work with it in common tabular data structures, such as Pandas dataframes. File: The dataset presents a list of file paths that can be read as though from the file system. Use this type of dataset when your data is unstructured, or when you need to process the data at the file level (for example, to train a convolutional neural network from a set of image files). Creating and registering datasetsYou can use the visual interface in Azure Machine Learning studio or the Azure Machine Learning SDK to create datasets from individual files or multiple file paths. The paths can include wildcards (for example, /files/*.csv) making it possible to encapsulate data from a large number of files in a single dataset.After you've created a dataset, you can register it in the workspace to make it available for use in experiments and data processing pipelines later. As you can see in the code above, it's easy to convert a tabular dataset to a Pandas dataframe, enabling you to work with the data using common python techniques. Create a file DatasetThe dataset you created is a *tabular* dataset that can be read as a dataframe containing all of the data in the structured files that are included in the dataset definition. This works well for tabular data, but in some machine learning scenarios you might need to work with data that is unstructured; or you may simply want to handle reading the data from files in your own code. To accomplish this, you can use a *file* dataset, which creates a list of file paths in a virtual mount point, which you can use to read the data in the files.
#Create a file dataset from the path on the datastore (this may take a short while) file_data_set = Dataset.File.from_files(path=(default_ds, 'diabetes-data/*.csv')) # Get the files in the dataset for file_path in file_data_set.to_path(): print(file_path)
/diabetes.csv /diabetes2.csv
MIT
06 - Work with Data.ipynb
ChidiNdego/azure-challenge-mslearn-dp100
Register datasetsNow that you have created datasets that reference the diabetes data, you can register them to make them easily accessible to any experiment being run in the workspace.We'll register the tabular dataset as **diabetes dataset**, and the file dataset as **diabetes files**.
# Register the tabular dataset try: tab_data_set = tab_data_set.register(workspace=ws, name='diabetes dataset', description='diabetes data', tags = {'format':'CSV'}, create_new_version=True) except Exception as ex: print(ex) # Register the file dataset try: file_data_set = file_data_set.register(workspace=ws, name='diabetes file dataset', description='diabetes files', tags = {'format':'CSV'}, create_new_version=True) except Exception as ex: print(ex) print('Datasets registered')
Datasets registered
MIT
06 - Work with Data.ipynb
ChidiNdego/azure-challenge-mslearn-dp100
Retrieving a registered datasetAfter registering a dataset, you can retrieve it by using any of the following techniques: The datasets dictionary attribute of a Workspace object. The get_by_name or get_by_id method of the Dataset class.Both of these techniques are shown in the following code:```import azureml.corefrom azureml.core import Workspace, Dataset Load the workspace from the saved config filews = Workspace.from_config() Get a dataset from the workspace datasets collectionds1 = ws.datasets['csv_table'] Get a dataset by name from the datasets classds2 = Dataset.get_by_name(ws, 'img_files')``` You can view and manage datasets on the **Datasets** page for your workspace in [Azure Machine Learning studio](https://ml.azure.com). You can also get a list of datasets from the workspace object:
print("Datasets:") for dataset_name in list(ws.datasets.keys()): dataset = Dataset.get_by_name(ws, dataset_name) print("\t", dataset.name, 'version', dataset.version)
Datasets: diabetes file dataset version 1 diabetes dataset version 1 TD-Auto_Price_Training-Clean_Missing_Data-Cleaning_transformation-91e1ac5f version 1 TD-Auto_Price_Training-Normalize_Data-Transformation_function-0f39eb1a version 1 MD-Auto_Price_Training-Train_Model-Trained_model-559e7cee version 1 bike-rentals version 1
MIT
06 - Work with Data.ipynb
ChidiNdego/azure-challenge-mslearn-dp100
Dataset versioningDatasets can be versioned, enabling you to track historical versions of datasets that were used in experiments, and reproduce those experiments with data in the same state.You can create a new version of a dataset by registering it with the same name as a previously registered dataset and specifying the create_new_version property:```img_paths = [(blob_ds, 'data/files/images/*.jpg'), (blob_ds, 'data/files/images/*.png')]file_ds = Dataset.File.from_files(path=img_paths)file_ds = file_ds.register(workspace=ws, name='img_files', create_new_version=True)```In this example, the .png files in the images folder have been added to the definition of the img_paths dataset example used in the previous topic. Retrieving a specific dataset versionYou can retrieve a specific version of a dataset by specifying the version parameter in the get_by_name method of the Dataset class.```img_ds = Dataset.get_by_name(workspace=ws, name='img_files', version=2)``` The ability to version datasets enables you to redefine datasets without breaking existing experiments or pipelines that rely on previous definitions. By default, the latest version of a named dataset is returned, but you can retrieve a specific version of a dataset by specifying the version number, like this:```pythondataset_v1 = Dataset.get_by_name(ws, 'diabetes dataset', version = 1)``` Train a model from a tabular datasetNow that you have datasets, you're ready to start training models from them. You can pass datasets to scripts as *inputs* in the estimator being used to run the script.Run the following two code cells to create:1. A folder named **diabetes_training_from_tab_dataset**2. A script that trains a classification model by using a tabular dataset that is passed to is as an argument.
import os # Create a folder for the experiment files experiment_folder = 'diabetes_training_from_tab_dataset' os.makedirs(experiment_folder, exist_ok=True) print(experiment_folder, 'folder created') %%writefile $experiment_folder/diabetes_training.py # Import libraries import os import argparse from azureml.core import Run, Dataset import pandas as pd import numpy as np import joblib from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve # Get the script arguments (regularization rate and training dataset ID) parser = argparse.ArgumentParser() parser.add_argument('--regularization', type=float, dest='reg_rate', default=0.01, help='regularization rate') parser.add_argument("--input-data", type=str, dest='training_dataset_id', help='training dataset') args = parser.parse_args() # Set regularization hyperparameter (passed as an argument to the script) reg = args.reg_rate # Get the experiment run context run = Run.get_context() # Get the training dataset print("Loading Data...") diabetes = run.input_datasets['training_data'].to_pandas_dataframe() # Separate features and labels X, y = diabetes[['Pregnancies','PlasmaGlucose','DiastolicBloodPressure','TricepsThickness','SerumInsulin','BMI','DiabetesPedigree','Age']].values, diabetes['Diabetic'].values # Split data into training set and test set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0) # Train a logistic regression model print('Training a logistic regression model with regularization rate of', reg) run.log('Regularization Rate', np.float(reg)) model = LogisticRegression(C=1/reg, solver="liblinear").fit(X_train, y_train) # calculate accuracy y_hat = model.predict(X_test) acc = np.average(y_hat == y_test) print('Accuracy:', acc) run.log('Accuracy', np.float(acc)) # calculate AUC y_scores = model.predict_proba(X_test) auc = roc_auc_score(y_test,y_scores[:,1]) print('AUC: ' + str(auc)) run.log('AUC', np.float(auc)) os.makedirs('outputs', exist_ok=True) # note file saved in the outputs folder is automatically uploaded into experiment record joblib.dump(value=model, filename='outputs/diabetes_model.pkl') run.complete()
Writing diabetes_training_from_tab_dataset/diabetes_training.py
MIT
06 - Work with Data.ipynb
ChidiNdego/azure-challenge-mslearn-dp100
Extra note: Use a script argument for a tabular datasetYou can pass a tabular dataset as a script argument. When you take this approach, the argument received by the script is the unique ID for the dataset in your workspace. In the script, you can then get the workspace from the run context and use it to retrieve the dataset by it's ID.ScriptRunConfig:```env = Environment('my_env')packages = CondaDependencies.create(conda_packages=['pip'], pip_packages=['azureml-defaults', 'azureml-dataprep[pandas]'])env.python.conda_dependencies = packagesscript_config = ScriptRunConfig(source_directory='my_dir', script='script.py', arguments=['--ds', tab_ds], environment=env)```Script:```from azureml.core import Run, Datasetparser.add_argument('--ds', type=str, dest='dataset_id')args = parser.parse_args()run = Run.get_context()ws = run.experiment.workspacedataset = Dataset.get_by_id(ws, id=args.dataset_id)data = dataset.to_pandas_dataframe()``` Use a named input for a tabular datasetAlternatively, you can pass a tabular dataset as a named input. In this approach, you use the as_named_input method of the dataset to specify a name for the dataset. Then in the script, you can retrieve the dataset by name from the run context's input_datasets collection without needing to retrieve it from the workspace. Note that if you use this approach, you still need to include a script argument for the dataset, even though you don’t actually use it to retrieve the dataset.ScriptRunConfig:```env = Environment('my_env')packages = CondaDependencies.create(conda_packages=['pip'], pip_packages=['azureml-defaults', 'azureml-dataprep[pandas]'])env.python.conda_dependencies = packagesscript_config = ScriptRunConfig(source_directory='my_dir', script='script.py', arguments=['--ds', tab_ds.as_named_input('my_dataset')], environment=env)```Script:```from azureml.core import Runparser.add_argument('--ds', type=str, dest='ds_id')args = parser.parse_args()run = Run.get_context()dataset = run.input_datasets['my_dataset']data = dataset.to_pandas_dataframe()``` > **Note**: In the script, the dataset is passed as a parameter (or argument). In the case of a tabular dataset, this argument will contain the ID of the registered dataset; so you could write code in the script to get the experiment's workspace from the run context, and then get the dataset using its ID; like this:>> ```> run = Run.get_context()> ws = run.experiment.workspace> dataset = Dataset.get_by_id(ws, id=args.training_dataset_id)> diabetes = dataset.to_pandas_dataframe()> ```>> However, Azure Machine Learning runs automatically identify arguments that reference named datasets and add them to the run's **input_datasets** collection, so you can also retrieve the dataset from this collection by specifying its "friendly name" (which as you'll see shortly, is specified in the argument definition in the script run configuration for the experiment). This is the approach taken in the script above.Now you can run a script as an experiment, defining an argument for the training dataset, which is read by the script.> **Note**: The **Dataset** class depends on some components in the **azureml-dataprep** package, which includes optional support for **pandas** that is used by the **to_pandas_dataframe()** method. So you need to include this package in the environment where the training experiment will be run.
from azureml.core import Experiment, ScriptRunConfig, Environment from azureml.core.conda_dependencies import CondaDependencies from azureml.widgets import RunDetails # Create a Python environment for the experiment sklearn_env = Environment("sklearn-env") # Ensure the required packages are installed (we need scikit-learn, Azure ML defaults, and Azure ML dataprep) packages = CondaDependencies.create(conda_packages=['scikit-learn','pip'], pip_packages=['azureml-defaults','azureml-dataprep[pandas]']) sklearn_env.python.conda_dependencies = packages # Get the training dataset diabetes_ds = ws.datasets.get("diabetes dataset") # Create a script config script_config = ScriptRunConfig(source_directory=experiment_folder, script='diabetes_training.py', arguments = ['--regularization', 0.1, # Regularizaton rate parameter '--input-data', diabetes_ds.as_named_input('training_data')], # Reference to dataset environment=sklearn_env) # submit the experiment experiment_name = 'mslearn-train-diabetes' experiment = Experiment(workspace=ws, name=experiment_name) run = experiment.submit(config=script_config) RunDetails(run).show() run.wait_for_completion()
_____no_output_____
MIT
06 - Work with Data.ipynb
ChidiNdego/azure-challenge-mslearn-dp100
> **Note:** The **--input-data** argument passes the dataset as a *named input* that includes a *friendly name* for the dataset, which is used by the script to read it from the **input_datasets** collection in the experiment run. The string value in the **--input-data** argument is actually the registered dataset's ID. As an alternative approach, you could simply pass `diabetes_ds.id`, in which case the script can access the dataset ID from the script arguments and use it to get the dataset from the workspace, but not from the **input_datasets** collection.The first time the experiment is run, it may take some time to set up the Python environment - subsequent runs will be quicker.When the experiment has completed, in the widget, view the **azureml-logs/70_driver_log.txt** output log and the metrics generated by the run. Register the trained modelAs with any training experiment, you can retrieve the trained model and register it in your Azure Machine Learning workspace.
from azureml.core import Model run.register_model(model_path='outputs/diabetes_model.pkl', model_name='diabetes_model', tags={'Training context':'Tabular dataset'}, properties={'AUC': run.get_metrics()['AUC'], 'Accuracy': run.get_metrics()['Accuracy']}) for model in Model.list(ws): print(model.name, 'version:', model.version) for tag_name in model.tags: tag = model.tags[tag_name] print ('\t',tag_name, ':', tag) for prop_name in model.properties: prop = model.properties[prop_name] print ('\t',prop_name, ':', prop) print('\n')
diabetes_model version: 3 Training context : Tabular dataset AUC : 0.8568595320655352 Accuracy : 0.7891111111111111 diabetes_model version: 2 Training context : Parameterized script AUC : 0.8484357430717946 Accuracy : 0.774 diabetes_model version: 1 Training context : Script AUC : 0.8483203144435048 Accuracy : 0.774
MIT
06 - Work with Data.ipynb
ChidiNdego/azure-challenge-mslearn-dp100
Train a model from a file datasetYou've seen how to train a model using training data in a *tabular* dataset; but what about a *file* dataset?When you're using a file dataset, the dataset argument passed to the script represents a mount point containing file paths. How you read the data from these files depends on the kind of data in the files and what you want to do with it. In the case of the diabetes CSV files, you can use the Python **glob** module to create a list of files in the virtual mount point defined by the dataset, and read them all into Pandas dataframes that are concatenated into a single dataframe.Run the following two code cells to create:1. A folder named **diabetes_training_from_file_dataset**2. A script that trains a classification model by using a file dataset that is passed to is as an *input*.
import os # Create a folder for the experiment files experiment_folder = 'diabetes_training_from_file_dataset' os.makedirs(experiment_folder, exist_ok=True) print(experiment_folder, 'folder created') %%writefile $experiment_folder/diabetes_training.py # Import libraries import os import argparse from azureml.core import Dataset, Run import pandas as pd import numpy as np import joblib from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve import glob # Get script arguments (rgularization rate and file dataset mount point) parser = argparse.ArgumentParser() parser.add_argument('--regularization', type=float, dest='reg_rate', default=0.01, help='regularization rate') parser.add_argument('--input-data', type=str, dest='dataset_folder', help='data mount point') args = parser.parse_args() # Set regularization hyperparameter (passed as an argument to the script) reg = args.reg_rate # Get the experiment run context run = Run.get_context() # load the diabetes dataset print("Loading Data...") data_path = run.input_datasets['training_files'] # Get the training data path from the input # (You could also just use args.data_folder if you don't want to rely on a hard-coded friendly name) # Read the files all_files = glob.glob(data_path + "/*.csv") diabetes = pd.concat((pd.read_csv(f) for f in all_files), sort=False) # Separate features and labels X, y = diabetes[['Pregnancies','PlasmaGlucose','DiastolicBloodPressure','TricepsThickness','SerumInsulin','BMI','DiabetesPedigree','Age']].values, diabetes['Diabetic'].values # Split data into training set and test set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0) # Train a logistic regression model print('Training a logistic regression model with regularization rate of', reg) run.log('Regularization Rate', np.float(reg)) model = LogisticRegression(C=1/reg, solver="liblinear").fit(X_train, y_train) # calculate accuracy y_hat = model.predict(X_test) acc = np.average(y_hat == y_test) print('Accuracy:', acc) run.log('Accuracy', np.float(acc)) # calculate AUC y_scores = model.predict_proba(X_test) auc = roc_auc_score(y_test,y_scores[:,1]) print('AUC: ' + str(auc)) run.log('AUC', np.float(auc)) os.makedirs('outputs', exist_ok=True) # note file saved in the outputs folder is automatically uploaded into experiment record joblib.dump(value=model, filename='outputs/diabetes_model.pkl') run.complete()
Writing diabetes_training_from_file_dataset/diabetes_training.py
MIT
06 - Work with Data.ipynb
ChidiNdego/azure-challenge-mslearn-dp100
Just as with tabular datasets, you can retrieve a file dataset from the **input_datasets** collection by using its friendly name. You can also retrieve it from the script argument, which in the case of a file dataset contains a mount path to the files (rather than the dataset ID passed for a tabular dataset).Next we need to change the way we pass the dataset to the script - it needs to define a path from which the script can read the files. You can use either the **as_download** or **as_mount** method to do this. Using **as_download** causes the files in the file dataset to be downloaded to a temporary location on the compute where the script is being run, while **as_mount** creates a mount point from which the files can be streamed directly from the datasetore.You can combine the access method with the **as_named_input** method to include the dataset in the **input_datasets** collection in the experiment run (if you omit this, for example by setting the argument to `diabetes_ds.as_mount()`, the script will be able to access the dataset mount point from the script arguments, but not from the **input_datasets** collection). Extra note: Use a script argument for a file datasetYou can pass a file dataset as a script argument. Unlike with a tabular dataset, you must specify a mode for the file dataset argument, which can be as_download or as_mount. This provides an access point that the script can use to read the files in the dataset. In most cases, you should use as_download, which copies the files to a temporary location on the compute where the script is being run. However, if you are working with a large amount of data for which there may not be enough storage space on the experiment compute, use as_mount to stream the files directly from their source.ScriptRunConfig:```env = Environment('my_env')packages = CondaDependencies.create(conda_packages=['pip'], pip_packages=['azureml-defaults', 'azureml-dataprep[pandas]'])env.python.conda_dependencies = packagesscript_config = ScriptRunConfig(source_directory='my_dir', script='script.py', arguments=['--ds', file_ds.as_download()], environment=env)```Script:```from azureml.core import Runimport globparser.add_argument('--ds', type=str, dest='ds_ref')args = parser.parse_args()run = Run.get_context()imgs = glob.glob(ds_ref + "/*.jpg")``` Use a named input for a file datasetYou can also pass a file dataset as a named input. In this approach, you use the as_named_input method of the dataset to specify a name before specifying the access mode. Then in the script, you can retrieve the dataset by name from the run context's input_datasets collection and read the files from there. As with tabular datasets, if you use a named input, you still need to include a script argument for the dataset, even though you don’t actually use it to retrieve the dataset.ScriptRunConfig:```env = Environment('my_env')packages = CondaDependencies.create(conda_packages=['pip'], pip_packages=['azureml-defaults', 'azureml-dataprep[pandas]'])env.python.conda_dependencies = packagesscript_config = ScriptRunConfig(source_directory='my_dir', script='script.py', arguments=['--ds', file_ds.as_named_input('my_ds').as_download()], environment=env)```Script:```from azureml.core import Runimport globparser.add_argument('--ds', type=str, dest='ds_ref')args = parser.parse_args()run = Run.get_context()dataset = run.input_datasets['my_ds']imgs= glob.glob(dataset + "/*.jpg")```
from azureml.core import Experiment from azureml.widgets import RunDetails # Get the training dataset diabetes_ds = ws.datasets.get("diabetes file dataset") # Create a script config script_config = ScriptRunConfig(source_directory=experiment_folder, script='diabetes_training.py', arguments = ['--regularization', 0.1, # Regularizaton rate parameter '--input-data', diabetes_ds.as_named_input('training_files').as_download()], # Reference to dataset location environment=sklearn_env) # Use the environment created previously # submit the experiment experiment_name = 'mslearn-train-diabetes' experiment = Experiment(workspace=ws, name=experiment_name) run = experiment.submit(config=script_config) RunDetails(run).show() run.wait_for_completion()
_____no_output_____
MIT
06 - Work with Data.ipynb
ChidiNdego/azure-challenge-mslearn-dp100
When the experiment has completed, in the widget, view the **azureml-logs/70_driver_log.txt** output log to verify that the files in the file dataset were downloaded to a temporary folder to enable the script to read the files. Register the trained modelOnce again, you can register the model that was trained by the experiment.
from azureml.core import Model run.register_model(model_path='outputs/diabetes_model.pkl', model_name='diabetes_model', tags={'Training context':'File dataset'}, properties={'AUC': run.get_metrics()['AUC'], 'Accuracy': run.get_metrics()['Accuracy']}) for model in Model.list(ws): print(model.name, 'version:', model.version) for tag_name in model.tags: tag = model.tags[tag_name] print ('\t',tag_name, ':', tag) for prop_name in model.properties: prop = model.properties[prop_name] print ('\t',prop_name, ':', prop) print('\n')
diabetes_model version: 4 Training context : File dataset AUC : 0.8568517900798176 Accuracy : 0.7891111111111111 diabetes_model version: 3 Training context : Tabular dataset AUC : 0.8568595320655352 Accuracy : 0.7891111111111111 diabetes_model version: 2 Training context : Parameterized script AUC : 0.8484357430717946 Accuracy : 0.774 diabetes_model version: 1 Training context : Script AUC : 0.8483203144435048 Accuracy : 0.774
MIT
06 - Work with Data.ipynb
ChidiNdego/azure-challenge-mslearn-dp100
We have a folder called `vrt`, however, we want to empty it first before writing new annotation files into it. The idea should be that we modify ELAN files, and the changes there result in update of old VRT files. Of course replacing all of them at once is not very effective, so there probably should be Git commit info in VRT, or in configuration file, with a check whether there has been an update or not since that commit.
folder = './vrt' for the_file in os.listdir(folder): file_path = os.path.join(folder, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) except Exception as e: print(e)
_____no_output_____
Apache-2.0
ikdp2korp.ipynb
langdoc/eaf2korp
`eaf2vrt` function is designed so that it takes an ELAN file and writes it into an arbitrary location as a VRT file. Thereby both input and output file have to be specified. Also ELAN tier that contains the annotations we want to work with has to be specified.
filenames = sorted(Path('/Users/niko/langdoc/kpv/').glob('**/kpv_izva*.eaf')) for filename in filenames: elan_file = str(filename) session_name = Path(elan_file).stem vrt_file = 'vrt/' + session_name + '.vrt' eaf2korp.eaf2vrt(elan_file_path = elan_file, vrt_file_path = vrt_file)
Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors... Parsing unknown version of ELAN spec... This could result in errors...
Apache-2.0
ikdp2korp.ipynb
langdoc/eaf2korp
This leaves us with a folder full of VRT files. In this point we just have to specify the language which uralicNLP uses to run the analyser.
filenames = sorted(Path('vrt/').glob('*.vrt')) for filename in filenames: vrt_file = str(filename) eaf2korp.annotate_vrt(vrt_file_path = vrt_file, language = "kpv")
_____no_output_____
Apache-2.0
ikdp2korp.ipynb
langdoc/eaf2korp
UT2000 Home Environment Exploratory AnalysisWe now take a closer look at the beacon and home environment survey data to see if we can tease anything out of it or at least show something.
import math
_____no_output_____
MIT
notebooks/archive/2.0-hef-beacon-exploration.ipynb
intelligent-environments-lab/utx000
Data ImportWe have two things to import: (1) the home environment survey and (2) the beacon data
import pandas as pd import numpy as np import os from datetime import datetime
_____no_output_____
MIT
notebooks/archive/2.0-hef-beacon-exploration.ipynb
intelligent-environments-lab/utx000
Home Environment SurveyThe get the home environment survey data, please make sure to run ```$ python3 src/data/make_dataset.py``` and choose the option for the HEH survey. This will combine, clean, and save the home environment survey data to the processed data directory.
HEH = pd.read_csv(f'/Users/hagenfritz/Projects/utx000/data/processed/ut3000-heh.csv') HEH.head()
_____no_output_____
MIT
notebooks/archive/2.0-hef-beacon-exploration.ipynb
intelligent-environments-lab/utx000
BeaconsTo get the beacon data for the UT2000 study, be sure ture run ```$ python3 src/data/make_dataset.py``` and chooose the option for the ut2000 beacons. This will combine, clean, and save the beacon data to the processed data directory.
beacons = pd.read_csv(f'/Users/hagenfritz/Projects/utx000/data/processed/ut2000-beacon.csv', index_col=0,parse_dates=True,infer_datetime_format=True) beacons.head()
_____no_output_____
MIT
notebooks/archive/2.0-hef-beacon-exploration.ipynb
intelligent-environments-lab/utx000
Visualization and AnalysisNow we get to the meat of it - visualizing and doing some simple statistics on the data.
import seaborn as sns import matplotlib.pyplot as plt import matplotlib.dates as mdates from matplotlib.colors import ListedColormap, LinearSegmentedColormap
_____no_output_____
MIT
notebooks/archive/2.0-hef-beacon-exploration.ipynb
intelligent-environments-lab/utx000
Heat Maps Investigating Participant 36dsqll3 (Beacon 6) who we used in the MADS Framework paper. There were some questions about the values reported in the Figure 3 which corresponds to 3/30.
fig,ax = plt.subplots(figsize=(8,6)) df = df_hm sns.heatmap(data=df,cmap='inferno_r',cbar=True,square=False,ax=ax) labels = [] for d in df.index: dd = datetime(d.year,d.month,d.day) if dd >= datetime(2019,3,18) and dd <= datetime(2019,3,23): labels.append(datetime.strftime(d,'%a %m/%d')+'*') else: labels.append(datetime.strftime(d,'%a %m/%d')) ax.set_yticklabels(labels) ax.set_xlabel('Hour of Day') plt.show() plt.close()
_____no_output_____
MIT
notebooks/archive/2.0-hef-beacon-exploration.ipynb
intelligent-environments-lab/utx000
Seems the concentration spikes for whatever reason on 3/30
def plot_heat_map(df): ''' ''' fig,ax = plt.subplots(figsize=(8,6)) df = df/np.nanmax(df) sns.heatmap(data=df,cmap='inferno_r',cbar=True,cbar_kws={'ticks':[]},square=False,ax=ax) ax.text(25,27.4,'Minimum',bbox={'facecolor':'white'},zorder=10) ax.text(25,-1,'Maximum',bbox={'facecolor':'white'},zorder=10) labels = [] for d in df.index: dd = datetime(d.year,d.month,d.day) if dd >= datetime(2019,3,18) and dd <= datetime(2019,3,23): labels.append(datetime.strftime(d,'%a %m/%d')+'*') else: labels.append(datetime.strftime(d,'%a %m/%d')) ax.set_yticklabels(labels) ax.set_ylabel('Day in 2019') ax.set_xlabel('Hour of Day') return ax
_____no_output_____
MIT
notebooks/archive/2.0-hef-beacon-exploration.ipynb
intelligent-environments-lab/utx000
per BeaconThe following cell creates heat maps for each beacon for each sensor.
for b in [1,2,5]: df = beacons[beacons['number'] == b] df = df.resample('1h').mean() df['hour'] = df.index.hour df['day'] = df.index.date df = df.dropna() df = df[datetime(2019,3,16):datetime(2019,4,5,23)] df_pm = df.pivot_table(index='day',columns='hour',values='pm2.5') df_tc = df.pivot_table(index='day',columns='hour',values='TC') df_rh = df.pivot_table(index='day',columns='hour',values='RH') df_tvoc = df.pivot_table(index='day',columns='hour',values='TVOC') fig, ax = plt.subplots(2,3,figsize=(14,14),gridspec_kw={'width_ratios': [15, 14, 1]}) sns.heatmap(df_pm,cmap='inferno_r',ax=ax[0,0], cbar=False) sns.heatmap(df_tvoc,cmap='inferno_r',ax=ax[0,1],cbar_ax=ax[0,2],cbar_kws={'ticks':[]}) sns.heatmap(df_tc,cmap='inferno_r',ax=ax[1,0], cbar=False) sns.heatmap(df_rh,cmap='inferno_r',ax=ax[1,1],cbar_ax=ax[1,2],cbar_kws={'ticks':[]}) labels = [] for d in df_pm.index: dd = datetime(d.year,d.month,d.day) if dd >= datetime(2019,3,18) and dd <= datetime(2019,3,23): labels.append(datetime.strftime(d,'%a %m/%d')+'*') else: labels.append(datetime.strftime(d,'%a %m/%d')) axis = ax[0,0] axis.set_yticklabels(labels) axis.set_ylabel('Day in 2019') axis.set_xlabel('Hour of Day') axis.set_title('PM2.5 Concentration') axis = ax[0,1] axis.set_yticks([]) axis.set_ylabel('') axis.set_xlabel('Hour of Day') axis.set_title('TVOC Concentration') axis = ax[1,0] axis.set_yticklabels(labels) axis.set_ylabel('Day in 2019') axis.set_ylabel('') axis.set_xlabel('Hour of Day') axis.set_title('Temperature') axis = ax[1,1] axis.set_yticks([]) axis.set_ylabel('') axis.set_xlabel('Hour of Day') axis.set_title('Relative Humidity') ax[0,2].text(30,np.nanmin(df_tvoc),'Minimum',bbox={'facecolor':'white'},zorder=10,ha='center',va='top') ax[0,2].text(30,np.nanmax(df_tvoc),'Maximum',bbox={'facecolor':'white'},zorder=10,ha='center',va='bottom') ax[1,2].text(30,np.nanmin(df_rh),'Minimum',bbox={'facecolor':'white'},zorder=10,ha='center',va='top') ax[1,2].text(30,np.nanmax(df_rh),'Maximum',bbox={'facecolor':'white'},zorder=10,ha='center',va='bottom') plt.subplots_adjust(wspace=0.1) plt.savefig(f'/Users/hagenfritz/Projects/utx000/reports/figures/framework_paper/ut2000-beacon{b}-sensortrends-heatmap.png') plt.show() plt.close()
_____no_output_____
MIT
notebooks/archive/2.0-hef-beacon-exploration.ipynb
intelligent-environments-lab/utx000
per Beacon per SensorNow we get even more fine-grained and show the heat map for each sensor on each beacon.
for no in [1,2,5,6]: df = beacons[beacons['number'] == no] df = df.resample('1h').mean() df['hour'] = df.index.hour df['day'] = df.index.date df = df.dropna() df = df[datetime(2019,3,11):datetime(2019,4,5)] df_hm = df.pivot_table(index='day',columns='hour',values='pm2.5') if len(df_hm) > 7: ax = plot_heat_map(df_hm) plt.savefig(f'/Users/hagenfritz/Projects/utx000/reports/figures/framework_paper/ut2000-beacon{no}-pm2p5-heatmap.png') ax.set_title(f'Beacon {no}: PM2.5') plt.show() plt.close() df_tc = df.pivot_table(index='day',columns='hour',values='TC') if len(df_tc) > 7: ax = plot_heat_map(df_tc) plt.savefig(f'/Users/hagenfritz/Projects/utx000/reports/figures/framework_paper/ut2000-beacon{no}-tc-heatmap.png') ax.set_title(f'Beacon {no}: Temperature') plt.show() plt.close() df_tvoc = df.pivot_table(index='day',columns='hour',values='TVOC') if len(df_tvoc) > 7: ax = plot_heat_map(df_tvoc) plt.savefig(f'/Users/hagenfritz/Projects/utx000/reports/figures/framework_paper/ut2000-beacon{no}-tvoc-heatmap.png') ax.set_title(f'Beacon {no}: TVOC') plt.show() plt.close()
_____no_output_____
MIT
notebooks/archive/2.0-hef-beacon-exploration.ipynb
intelligent-environments-lab/utx000
EverythingNow we combine all the beacons and all the sensors into one heat map. We still normalize the data, but now we do it per sensor for all the beacons.
fig, ax = plt.subplots(4,4,figsize=(16,18),sharex='col',gridspec_kw={'width_ratios': [15, 15, 15, 1]}) row = 0 for value in ['pm2.5','TVOC','TC','RH']: col = 0 for b in [1,2,5]: # Getting heatmap dataframe df = beacons[beacons['number'] == b] df = df.resample('1h').mean() df['hour'] = df.index.hour df['day'] = df.index.date df = df.dropna() df = df[datetime(2019,3,16):datetime(2019,4,2,23)] df_var = df.pivot_table(index='day',columns='hour',values=value) df_var /= np.max(df_var) # plotting with the colobar from the last figure if col == 2: sns.heatmap(df_var,cmap='inferno_r',ax=ax[row,col],cbar_ax=ax[row,col+1],cbar_kws={'ticks':[]}) else: sns.heatmap(df_var,cmap='inferno_r',ax=ax[row,col], cbar=False) # Formatting axes ax[row,col].set_xlabel('') ax[row,col].set_ylabel('') if col == 0: labels = [] for d in df_var.index: dd = datetime(d.year,d.month,d.day) if dd >= datetime(2019,3,18) and dd <= datetime(2019,3,23): labels.append(datetime.strftime(d,'%a %m/%d')+'*') else: labels.append(datetime.strftime(d,'%a %m/%d')) #ax[row,col].set_yticks(df_var.index) ax[row,col].set_yticklabels(labels) else: ax[row,col].set_yticks([]) if col == 1: if value == 'pm2.5': ax[row,col].set_title('PM2.5 Concentration') elif value == 'TVOC': ax[row,col].set_title('TVOC Concentration') elif value == 'TC': ax[row,col].set_title('Temperature') elif value == 'RH': ax[row,col].set_title('Relative Humidity') if row == 3: ax[row,col].set_xlabel('Hour of Day') col += 1 row += 1 ax[3,3].text(0.75,0,'Min',zorder=10,ha='center',va='center') ax[3,3].text(0.75,1,'Max',zorder=10,ha='center',va='bottom') #ax[2,3].text(30,np.nanmin(df_rh),'Minimum',bbox={'facecolor':'white'},zorder=10,ha='center',va='top') #ax[3,3].text(30,np.nanmax(df_rh),'Maximum',bbox={'facecolor':'white'},zorder=10,ha='center',va='bottom') plt.subplots_adjust(wspace=0.05,hspace=0.1) plt.savefig(f'/Users/hagenfritz/Projects/utx000/reports/figures/framework_paper/ut2000-beacon-comprehensive-heatmap.png') plt.show() plt.close()
_____no_output_____
MIT
notebooks/archive/2.0-hef-beacon-exploration.ipynb
intelligent-environments-lab/utx000
Split Heatmap
def create_cmap(colors,nodes): cmap = LinearSegmentedColormap.from_list("mycmap", list(zip(nodes, colors))) return cmap
_____no_output_____
MIT
notebooks/archive/2.0-hef-beacon-exploration.ipynb
intelligent-environments-lab/utx000
IAQ Heat MapThis heat map is NOT scaled but includes the actual values.
fig, ax = plt.subplots(2,3,figsize=(18,8),sharex='col',gridspec_kw={'width_ratios': [8, 8, 9]}) row = 0 for value in ['pm2.5','TVOC']: col = 0 for b in [1,2,5]: # Getting heatmap dataframe df = beacons[beacons['number'] == b] df = df.resample('1h').mean() df['hour'] = df.index.hour df['day'] = df.index.date df = df.dropna() df = df[datetime(2019,3,16):datetime(2019,4,2,23)] df_var = df.pivot_table(index='day',columns='hour',values=value) # plotting with the colobar from the last figure if value == 'pm2.5': if col == 2: sns.heatmap(df_var,vmin=0,vmax=500,cmap=create_cmap(["green", "yellow", "orange", "red", "purple", "black"],[0.0, 0.048, 0.14, 0.22, 0.6, 1]), ax=ax[row,col],cbar_kws={'ticks':[35,150,250,500]}) else: sns.heatmap(df_var,vmin=0,vmax=500,cmap=create_cmap(["green", "yellow", "orange", "red", "purple", "black"],[0.0, 0.048, 0.14, 0.22, 0.6, 1]), ax=ax[row,col], cbar=False) else: if col == 2: sns.heatmap(df_var,vmin=0,vmax=2200,cmap=create_cmap(["green", "yellow", "orange", "red", "purple"],[0.0, 0.03, 0.1, 0.3, 1]), ax=ax[row,col],cbar_kws={'ticks':[65,220,660,2200]}) else: sns.heatmap(df_var,vmin=0,vmax=2200,cmap=create_cmap(["green", "yellow", "orange", "red", "purple"],[0.0, 0.03, 0.1, 0.3, 1]), ax=ax[row,col], cbar=False) # Formatting axes ax[row,col].set_xlabel('') ax[row,col].set_ylabel('') if col == 0: labels = np.arange(1,len(df_var)+1,1) ax[row,col].set_yticklabels(labels) else: ax[row,col].set_yticks([]) if col == 1: if value == 'pm2.5': ax[row,col].set_title('PM2.5 Concentration ($\mu$g/m$^3$)') elif value == 'TVOC': ax[row,col].set_title('TVOC Concentration (ppb)') if row == 1: ax[row,col].set_xlabel('('+chr(ord('@')+col+1)+')') col += 1 row += 1 fig.text(0.5, 0.05, 'Hour of the Day', ha='center', va='center',size='x-large') fig.text(0.1, 0.5, 'Day During Study', ha='center', va='center', rotation='vertical',size='x-large') plt.subplots_adjust(wspace=0.05,hspace=0.15) plt.savefig(f'/Users/hagenfritz/Projects/utx000/reports/figures/framework_paper/ut2000-beacon-iaq-heatmap.pdf',bbox_inches='tight') plt.show() plt.close() fig, ax = plt.subplots(2,2,figsize=(16,8),sharex='col',gridspec_kw={'width_ratios': [8, 9]}) row = 0 for value in ['pm2.5','TVOC']: col = 0 for b in [1,2]: # Getting heatmap dataframe df = beacons[beacons['number'] == b] df = df.resample('1h').mean() df['hour'] = df.index.hour df['day'] = df.index.date df = df.dropna() df = df[datetime(2019,3,16):datetime(2019,4,2,23)] df_var = df.pivot_table(index='day',columns='hour',values=value) # plotting with the colobar from the last figure if value == 'pm2.5': if col == 1: sns.heatmap(df_var,vmin=0,vmax=500,cmap=create_cmap(["green", "yellow", "orange", "red", "purple", "black"],[0.0, 0.048, 0.14, 0.22, 0.6, 1]), ax=ax[row,col],cbar_kws={'ticks':[35,150,250,500]}) else: sns.heatmap(df_var,vmin=0,vmax=500,cmap=create_cmap(["green", "yellow", "orange", "red", "purple", "black"],[0.0, 0.048, 0.14, 0.22, 0.6, 1]), ax=ax[row,col], cbar=False) else: if col == 1: sns.heatmap(df_var,vmin=0,vmax=2200,cmap=create_cmap(["green", "yellow", "orange", "red", "purple"],[0.0, 0.03, 0.1, 0.3, 1]), ax=ax[row,col],cbar_kws={'ticks':[65,220,660,2200]}) else: sns.heatmap(df_var,vmin=0,vmax=2200,cmap=create_cmap(["green", "yellow", "orange", "red", "purple"],[0.0, 0.03, 0.1, 0.3, 1]), ax=ax[row,col], cbar=False) # Formatting axes ax[row,col].set_xlabel('') ax[row,col].set_ylabel('') if col == 0: labels = np.arange(1,len(df_var)+1,1) ax[row,col].set_yticklabels(labels) else: ax[row,col].set_yticks([]) if col == 1: if value == 'pm2.5': ax[row,col].set_title('PM2.5 Concentration ($\mu$g/m$^3$)') elif value == 'TVOC': ax[row,col].set_title('TVOC Concentration (ppb)') if row == 1: ax[row,col].set_xlabel('('+chr(ord('@')+col+1)+')') col += 1 row += 1 fig.text(0.5, 0.05, 'Hour of the Day', ha='center', va='center',size='x-large') fig.text(0.1, 0.5, 'Day During Study', ha='center', va='center', rotation='vertical',size='x-large') plt.subplots_adjust(wspace=0.05,hspace=0.15) plt.savefig(f'/Users/hagenfritz/Projects/utx000/reports/figures/framework_paper/ut2000-beacon-iaq-heatmap-b1and2.pdf',bbox_inches='tight') plt.show() plt.close()
_____no_output_____
MIT
notebooks/archive/2.0-hef-beacon-exploration.ipynb
intelligent-environments-lab/utx000
T/RH Heat MapThe T/RH values are scaled between 0 and 1.
fig, ax = plt.subplots(2,3,figsize=(18,8),sharex='col',gridspec_kw={'width_ratios': [8, 8, 9]}) row = 0 for value in ['TC','RH']: col = 0 for b in [1,2,5]: # Getting heatmap dataframe df = beacons[beacons['number'] == b] df = df.resample('1h').mean() df['hour'] = df.index.hour df['day'] = df.index.date df = df.dropna() df = df[datetime(2019,3,16):datetime(2019,4,2,23)] df_var = df.pivot_table(index='day',columns='hour',values=value) df_var = (df_var-df_var.min())/(df_var.max()-df_var.min()) # plotting with the colobar from the last figure if col == 2: sns.heatmap(df_var,vmin=0,vmax=1,cmap='coolwarm', ax=ax[row,col]) else: sns.heatmap(df_var,vmin=0,vmax=1,cmap='coolwarm', ax=ax[row,col], cbar=False) # Formatting axes ax[row,col].set_xlabel('') ax[row,col].set_ylabel('') if col == 0: labels = np.arange(1,len(df_var)+1,1) ax[row,col].set_yticklabels(labels) else: ax[row,col].set_yticks([]) if col == 1: if value == 'TC': ax[row,col].set_title('Temperature') elif value == 'RH': ax[row,col].set_title('Relative Humidity') if row == 1: ax[row,col].set_xlabel('('+chr(ord('@')+col+1)+')') col += 1 row += 1 fig.text(0.5, 0.05, 'Hour of the Day', ha='center', va='center',size='x-large') fig.text(0.1, 0.5, 'Day During Study', ha='center', va='center', rotation='vertical',size='x-large') plt.subplots_adjust(wspace=0.05,hspace=0.15) plt.savefig(f'/Users/hagenfritz/Projects/utx000/reports/figures/framework_paper/ut2000-beacon-trh-heatmap.pdf',bbox_inches='tight') plt.show() plt.close()
_____no_output_____
MIT
notebooks/archive/2.0-hef-beacon-exploration.ipynb
intelligent-environments-lab/utx000
Beacon Covariance PlotThe covariance plot will give a nice look at the relationship between the four variables measured on the beacon2.0: PM, TVOC, Temperature, and RH.
# Cleaning up the dataframe ## Removing high values df = beacons[beacons['TVOC'] < 800] df = df[df['pm2.5'] < 300] ## Removing and renaming columns df = df[['pm2.5','TVOC','TC','RH']] df.columns = ['PM2.5 ($\mu$g/m$^3$)','TVOC (ppb)', 'Temperature ($^\circ$C)', 'Relative Humidity'] # Plotting sns.pairplot(df,corner=False) plt.savefig('/Users/hagenfritz/Projects/utx000/reports/figures/framework_paper/ut2000-beacon-beacon-pairplot.png') plt.show() plt.close()
_____no_output_____
MIT
notebooks/archive/2.0-hef-beacon-exploration.ipynb
intelligent-environments-lab/utx000
Floor Type and PM/TVOC
# Getting only the ut200 responses and simplifying the dataframe heh2000 = HEH[HEH['study'] == 'ut2000'] floor2000 = heh2000[['record_id', 'amt_carpet','hardwd_amt', 'tile_amt','beacon']] floor2000 # Plotting the distributions of air pollutants based on floor type fig, ax = plt.subplots(2,1,figsize=(12,12)) heh2000.sort_values(['beacon'],inplace=True) for no in heh2000['beacon'].unique(): df = beacons[beacons['number'] == no] # Removing high tvoc/pm values and resaving df_tvoc = df[df['TVOC'] < 800] df_pm = df[df['pm2.5'] < 300] # Getting the row from the heh that corresponds to the beacon floorBeacon = floor2000[floor2000['beacon'] == no] # Plotting with slightly different formats for each floor type if floorBeacon['amt_carpet'].values[0] > 80: sns.kdeplot(df_tvoc['TVOC'],linewidth=2,color='firebrick',ax=ax[0],label=f'B{str(no)[:-2]}: carpet') sns.kdeplot(df_pm['pm2.5'],linewidth=2,color='firebrick',ax=ax[1],label='_nolabel_') elif floorBeacon['hardwd_amt'].values[0] > 80: sns.kdeplot(df_tvoc['TVOC'],color='gold',ax=ax[0],label=f'B{str(no)[:-2]}: hardwood') sns.kdeplot(df_pm['pm2.5'],color='gold',ax=ax[1],label='_nolabel_') elif floorBeacon['tile_amt'].values[0] > 80: sns.kdeplot(df_tvoc['TVOC'],color='seagreen',ax=ax[0],label=f'B{str(no)[:-2]}: tile') sns.kdeplot(df_pm['pm2.5'],color='seagreen',ax=ax[1],label='_nolabel_') else: print(f'No dominant floor type for the participant with beacon {no}') ax[0].legend(title='Beacon and Dwelling Type',loc='upper right',frameon=True,ncol=2) ax[0].set_xlabel('TVOC Concentration (ppb)') ax[1].set_xlabel('PM2.5 Concentration ($\mu$g/m$^3$)') plt.subplots_adjust(hspace=0.15) plt.savefig('../reports/figures/framework_paper/ut2000-beacon-heh-pollutants-flooring-distribution.png') plt.show() plt.close()
_____no_output_____
MIT
notebooks/archive/2.0-hef-beacon-exploration.ipynb
intelligent-environments-lab/utx000
Dwelling Type and PollutionNow we look at the different dwelling type and see if that has an effect on the pollutant concentration.
dwelling2000 = heh2000[['record_id', 'livingsit','beacon']] dwelling2000 fig, ax = plt.subplots(2,1,figsize=(12,12)) for no in heh2000['beacon'].unique(): df = beacons[beacons['number'] == no] # Removing high tvoc/pm values and resaving df_tvoc = df[df['TVOC'] < 800] df_pm = df[df['pm2.5'] < 300] # Getting the row from the heh that corresponds to the beacon dwellingBeacon = dwelling2000[dwelling2000['beacon'] == no] # Plotting with slightly different formats for each floor type if dwellingBeacon['livingsit'].values[0] == 'Apartment': sns.kdeplot(df_tvoc['TVOC'],linewidth=2,color='black',alpha=0.8,ax=ax[0],label=f'B{str(no)[:-2]}: Apt') sns.kdeplot(df_pm['pm2.5'],linewidth=2,color='black',alpha=0.8,ax=ax[1],label='_nolabel_') else: sns.kdeplot(df_tvoc['TVOC'],color='cornflowerblue',linewidth=2,ax=ax[0],label=f'B{str(no)[:-2]}: House') sns.kdeplot(df_pm['pm2.5'],color='cornflowerblue',linewidth=2,ax=ax[1],label='_nolabel_') ax[0].legend(title='Beacon and Dwelling Type',loc='upper right',frameon=True,ncol=2) ax[0].set_xlabel('TVOC Concentration (ppb)') ax[1].set_xlabel('PM2.5 Concentration ($\mu$g/m$^3$)') plt.subplots_adjust(hspace=0.15) plt.savefig('../reports/figures/framework_paper/ut2000-beacon-heh-pollutants-dwelling-distribution.png') plt.show() plt.close()
_____no_output_____
MIT
notebooks/archive/2.0-hef-beacon-exploration.ipynb
intelligent-environments-lab/utx000
自动生成字幕 工作内容:- 从视频文件自动生成外挂型字幕文件,不进行视频编辑等操作- 包括,时间轴主要工作:- 获取视频文件中的音频文件- 将音频文件分段- 采用IBM CLOUD进行语音转文字,每月500分钟免费- 自动构建B站字幕后续工作:- 采用 翻译API,自动进行初步翻译 - google: googletrans包,因为墙pass - youdao: 翻译 api B站字幕文件 .bcc 格式
# 示例 { "font_size":0.4, # 字体大小 "font_color":"#FFFFFF", # 字体颜色 "background_alpha":0.5, # 背景透明度 "background_color":"#9C27B0", # 背景颜色 "Stroke":"none", # "body":[ # 主体 { "from":13, # 起始处 "to":14.95, # 结束处 "location":2, # "content":"Hi I`m Larry Bill" # 主体 }, {"from":14.95,"to":18.825,"location":2,"content":"I`m chair guitar department Berklee College of Music"}, {"from":20.342341,"to":25.342341,"location":2,"content":"and it's my pleasure to work with you to "} ] }
_____no_output_____
MIT
自动生成字幕.ipynb
zhenghao0379/autosubpy
获取视频转音频
import moviepy.editor as mve path = r'D:\Music\电吉他\Berklee - Modern Method for Guitar - Vol1 (DVD)\video\Lesson 1' file = '001.mov' filepath = path + "\\" + file filepath video = mve.VideoFileClip(filepath) audio = video.audio audio.write_audiofile('test.mp3') audio.write_audiofile('test.mp3') # import ffmpeg # autosub,使用的时google 和 ffmpeg
_____no_output_____
MIT
自动生成字幕.ipynb
zhenghao0379/autosubpy
音频转文字
# IBM Cloud Speech to text # API密钥:-ijVpcr8DbYekYCkOEtalbfH6uMO1rI0qJAz0mEbDvre # URL:https://api.us-south.speech-to-text.watson.cloud.ibm.com/instances/48476942-3322-4bba-aae3-18a2b84015d7
_____no_output_____
MIT
自动生成字幕.ipynb
zhenghao0379/autosubpy
文字构成字幕 翻译
# 工具包 import requests import json # 有道翻译,调用有道翻译API(较不准,较快,稳定) def youdao_trans(text, t_type='AUTO'): text = text.replace(' ', '%20') url = 'http://fanyi.youdao.com/translate?&doctype=json&type='+t_type+'&i='+text # print(url) header = {} out = requests.get(url) out_json = out.json() # print(out_json) out_tgt = out_json['translateResult'][0][0]['tgt'] # print(out_tgt) return out_tgt # test youdao_trans("I'm chair of the guitar department here at Berklee college of music") # 谷歌翻译_1,调用谷歌翻译(较准,较慢,超时) from googletrans import Translator translator = Translator(service_urls=['translate.google.cn']) def google_trans0(text, dest='zh-cn'): try : out = translator.translate(text, dest=dest).text return out except: return '翻译异常' # test google_trans0("I'm chair of the guitar department here at Berklee college of music") text = "After you're done with this book and actually while you're playing this book you will develop a sense of musicality you'll develop strength in your hands you'll develop a sense of time with the chords a sense of melody and you'll just get better as a guitarist and as a musician." youdao_trans(text) google_trans0(text) # 谷歌翻译_2,调用网页版(准) # 构建中,tk解密破解 def google_trans(text, sl='auto', tl='zh_CN'): text = text.replace(' ', '%20') url = 'http://translate.google.cn/translate_a/single?client=t&dt=t&dj=1&ie=UTF-8&sl='+sl+'%tl='+tl+'&q='+text print(url) header = {} out = requests.get(url) out_json = out.json() print(out_json) out_tgt = out_json['translateResult'][0][0]['tgt'] print(out_tgt) return out_tgt # test # google_trans2('guitar department berklee college of music')
_____no_output_____
MIT
自动生成字幕.ipynb
zhenghao0379/autosubpy
Morph source estimates from one subject to another subjectA source estimate from a given subject 'sample' is morphedto the anatomy of another subject 'fsaverage'. The outputis a source estimate defined on the anatomy of 'fsaverage'
# Authors: Alexandre Gramfort <[email protected]> # Eric Larson <[email protected]> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne.datasets import sample print(__doc__) data_path = sample.data_path() subject_from = 'sample' subject_to = 'fsaverage' subjects_dir = data_path + '/subjects' fname = data_path + '/MEG/sample/sample_audvis-meg' # Read input stc file stc_from = mne.read_source_estimate(fname) # Morph using one method (supplying the vertices in fsaverage's source # space makes it faster). Note that for any generic subject, you could do: # vertices_to = mne.grade_to_vertices(subject_to, grade=5) # But fsaverage's source space was set up so we can just do this: vertices_to = [np.arange(10242), np.arange(10242)] stc_to = mne.morph_data(subject_from, subject_to, stc_from, n_jobs=1, grade=vertices_to, subjects_dir=subjects_dir) stc_to.save('%s_audvis-meg' % subject_to) # Morph using another method -- useful if you're going to do a lot of the # same inter-subject morphing operations; you could save and load morph_mat morph_mat = mne.compute_morph_matrix(subject_from, subject_to, stc_from.vertices, vertices_to, subjects_dir=subjects_dir) stc_to_2 = mne.morph_data_precomputed(subject_from, subject_to, stc_from, vertices_to, morph_mat) stc_to_2.save('%s_audvis-meg_2' % subject_to) # View source activations plt.plot(stc_from.times, stc_from.data.mean(axis=0), 'r', label='from') plt.plot(stc_to.times, stc_to.data.mean(axis=0), 'b', label='to') plt.plot(stc_to_2.times, stc_to.data.mean(axis=0), 'g', label='to_2') plt.xlabel('time (ms)') plt.ylabel('Mean Source amplitude') plt.legend() plt.show()
_____no_output_____
BSD-3-Clause
0.16/_downloads/plot_morph_data.ipynb
drammock/mne-tools.github.io
![title](img/cover4.png) Copyright! This material is protected, please do not copy or distribute. by:Taher Assaf ***Udemy course : Python Bootcamp for Data Science 2021 Numpy Pandas & Seaborn *** 14.5 Shifting Data Through Time (Lagging and Leading) First we import pandas library:
import pandas as pd
_____no_output_____
MIT
14.5 Shifting Data Through Time (Lagging and Leading).ipynb
SiamakMushakhian/Numpy-Pandas-Seaborn
Lets read a time series from a csv file using the function **pd.read_csv()**, we set the index column to be the date column using the argument **index_col**, and we convert the dates to datatime format using the argument **parse_dates = True**:
TS = pd.read_csv('data/ex17.csv', index_col = 'date', parse_dates = True) TS
_____no_output_____
MIT
14.5 Shifting Data Through Time (Lagging and Leading).ipynb
SiamakMushakhian/Numpy-Pandas-Seaborn
We can shift the price **one day** backward by using the function **shift()**:
TS.shift(periods = 1)
_____no_output_____
MIT
14.5 Shifting Data Through Time (Lagging and Leading).ipynb
SiamakMushakhian/Numpy-Pandas-Seaborn
We can shift the price **two days** backward by using the function **shift()**:
TS.shift(periods = 2)
_____no_output_____
MIT
14.5 Shifting Data Through Time (Lagging and Leading).ipynb
SiamakMushakhian/Numpy-Pandas-Seaborn
We can shift the price **three days** backward by using the function **shift()**:
TS.shift(periods = 3)
_____no_output_____
MIT
14.5 Shifting Data Through Time (Lagging and Leading).ipynb
SiamakMushakhian/Numpy-Pandas-Seaborn
We do not need to write the name of the argument **(periods)**, we can just pass the number of periods like this:
TS.shift(3)
_____no_output_____
MIT
14.5 Shifting Data Through Time (Lagging and Leading).ipynb
SiamakMushakhian/Numpy-Pandas-Seaborn