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_insta...
_____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_valu...
_____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['REGI...
_____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) #...
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 & condit...
_____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/vb6WlJXU09LHxcYbExGXmG0jHRs2M...
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(l...
_____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.cor...
_____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("Dimensi...
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')...
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 ...
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, ave...
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 t...
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, a...
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 Predicte...
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='mic...
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: [...
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("Dimensi...
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')...
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: ...
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, ave...
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 ...
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, a...
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 Predicte...
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='mic...
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, mur...
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("Dimensi...
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')...
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'] Mov...
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...
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...
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, prediction...
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 ...
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...
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 Predict...
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("Dimens...
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='mi...
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: ...
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...
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, r...
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, prediction...
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...
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...
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 & Gir...
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)', 'TfidfVectoriz...
+----------------------+-----------------+--------+-----------+--------+----------+ | Model | Vectorizer | ngrams | Precision | recall | f1_score | +----------------------+-----------------+--------+-----------+--------+----------+ | MultinomialNB | TfidfVectorizer | (1, 1) | 0.467 | 0.68...
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 tq...
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...
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: me...
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, prediction...
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: roman...
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...
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 ...
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,...
+----------------------+------------+-----------+--------+----------+ | Model | Vectorizer | Precision | recall | f1_score | +----------------------+------------+-----------+--------+----------+ | SGDClassifier(log) | AVG W2V | 0.423 | 0.788 | 0.551 | | SGDClassifier(hinge) | AVG W2V | ...
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=...
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: Austi...
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 cel...
# 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...
# 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 int...
_____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 f...
#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` ...
#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 ...
#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 wor...
_____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 n...
#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(...
_____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 no...
#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_...
#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 Remova...
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...
# 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 dr...
_____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...
_____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...
_____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 alg...
#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_Di...
_____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...
# 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...
_____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 e...
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', ...
_____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']) st...
_____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 `...
# 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 ...
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 ...
# 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. Wh...
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 ...
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 y...
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 Pa...
_____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 w...
#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'}, ...
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.co...
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-...
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 ...
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 impor...
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 ...
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...
_____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....
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....
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...
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...
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 impo...
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 ne...
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', ...
_____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 exp...
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.nam...
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 :...
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...
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...
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: ...
_____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={'facecolo...
_____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...
_____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) >...
_____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['hou...
_____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.ho...
_____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 ...
_____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=Fal...
_____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.sor...
_____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] # ...
_____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 La...
_____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 # auto...
_____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(...
_____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 <alexandre.gramfort@telecom-paristech.fr> # Eric Larson <larson.eric.d@gmail.com> # # 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' su...
_____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