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
Uarray reduced Now let's use uarray's `optimize` decorator to create an updated function that specifes the dimensionality of the arrays to produced an optimized form:
# enable_logging() optimized_some_fn = optimize(args[0].shape, args[1].shape)(some_fn)
_____no_output_____
BSD-3-Clause
notebooks/NumPy Compat.ipynb
costrouc/uarray
Now let's try our function out to see if it's faster:
# NBVAL_IGNORE_OUTPUT %timeit optimized_some_fn(*args)
5.47 µs ± 48.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
BSD-3-Clause
notebooks/NumPy Compat.ipynb
costrouc/uarray
Yep about 10x as fast. Let's look at how this is done! First, we create an abstract representation of the array operations:
optimized_some_fn.__optimize_steps__['resulting_expr']
_____no_output_____
BSD-3-Clause
notebooks/NumPy Compat.ipynb
costrouc/uarray
Then, we compile that to Python AST:
print(optimized_some_fn.__optimize_steps__['ast_as_source'])
def fn(a, b): i_5 = () i_6 = 10 i_1 = ((i_6,) + i_5) i_0 = np.empty(i_1) i_2 = 10 for i_3 in range(i_2): i_4 = i_0[i_3] i_9 = 5 i_10 = a i_13 = i_10[i_9] i_11 = i_3 i_12 = b i_14 = i_12[i_11] i_4 = (i_13 * i_14) i_0[i_3] =...
BSD-3-Clause
notebooks/NumPy Compat.ipynb
costrouc/uarray
Numba optimized To give this an extra speed boost, we can compile the returned expression with Numba:
numba_optimized = njit(optimized_some_fn) # NBVAL_IGNORE_OUTPUT # run once first to compile numba_optimized(*args) %timeit numba_optimized(*args)
876 ns ± 16.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
BSD-3-Clause
notebooks/NumPy Compat.ipynb
costrouc/uarray
Great, another speedup! Unkown dimensionality? What if we want to produce a version of the function that works on any dimensional input? Or if we just want to actually defer to NumPy's implementation and not replace `outer`? We simply omit the `with_dim` methods and we get back an abstract representation that is compi...
dims_not_known = optimize(some_fn) dims_not_known.__optimize_steps__['resulting_expr'] print(dims_not_known.__optimize_steps__['ast_as_source'])
def fn(a, b): i_18 = 5 i_16 = a i_17 = b i_19 = np.multiply.outer(i_16, i_17) i_15 = i_19[i_18] return i_15
BSD-3-Clause
notebooks/NumPy Compat.ipynb
costrouc/uarray
TweepyPara acessar a API do twitter, deve-se acessar a área de desenvolvedor, criar uma aplicação e solicitar as credenciais de acesso. As células abaixo demonstram como fazer a conexão na API do twitter usando a biblioteca python Tweepy e retornar a lista de tweets na timeline do usuário.[Documentação do tweepy](http...
consumer_key = os.environ['CONSUMER_API_KEY'] consumer_secret = os.environ['CONSUMER_API_SECRET'] access_token = os.environ['ACCESS_TOKEN'] access_token_secret = os.environ['ACCESS_TOKEN_SECRET'] auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tw...
_____no_output_____
Apache-2.0
twitter-crawler.ipynb
phdabel/twitter-crawler
Recuperar tweets da timeline
public_tweets = api.home_timeline()
_____no_output_____
Apache-2.0
twitter-crawler.ipynb
phdabel/twitter-crawler
Criar um dicionário vazio para incluir os tweets.Passo necessário para criar um dataframe.
tweets = {'id':[],'author':[], 'screen_name':[], 'tweet':[],'created_at':[],'language':[],'n_retweets':[],'n_likes':[]} ct = 0 num_results = 1000 result_count = 0 last_id = None while result_count < num_results: gremio_tweets = api.search(q='gremio',lang='pt',since_id=last_id) for tweet in gremio_tweets: ...
id: 1201655788508471298 Screen name: RauenPaian Autor: IMORTAL 🖤💙🖤💙 Tweet: RT @SoccerGremio: A informação que nos chega, é que são apenas detalhes a serem finalizados entre Grêmio e Palmeiras por Raphael Veiga. Os… Data de criação: 03/12/2019, 00:14:00 Idioma: pt Retweets: 54 Curtidas: 0 ========================== ...
Apache-2.0
twitter-crawler.ipynb
phdabel/twitter-crawler
Criação do dataframe
df = pd.DataFrame.from_dict(tweets) df
_____no_output_____
Apache-2.0
twitter-crawler.ipynb
phdabel/twitter-crawler
Salvar o dataframe em csv para uso posterior.
df.to_csv('dataframe.csv')
_____no_output_____
Apache-2.0
twitter-crawler.ipynb
phdabel/twitter-crawler
Assignment 2Before working on this assignment please read these instructions fully. In the submission area, you will notice that you can click the link to **Preview the Grading** for each step of the assignment. This is the criteria that will be used for peer grading. Please familiarize yourself with the criteria befo...
import matplotlib.pyplot as plt import mplleaflet import pandas as pd def leaflet_plot_stations(binsize, hashid): df = pd.read_csv('data/C2A2_data/BinSize_d{}.csv'.format(binsize)) station_locations_by_hash = df[df['hash'] == hashid] lons = station_locations_by_hash['LONGITUDE'].tolist() lats = stat...
_____no_output_____
MIT
Applied Data Science with Python Specialzation/Applied Plotting Charting and Data Representation in Python/Assignment2/Assignment2.ipynb
lynnxlmiao/Coursera
Classical Machine Learning ApproachIn this notebook we will be learning to 1. Create a Naive TF - IDF based Bag of Words representation of text. 2. Use classical ML models to solve text classification. 3. Use a One Vs Rest strategy to solve multi-label text classification. **HOT TIP** : *Save them as pickle for ea...
# Installing packages. !pip install contractions !pip install textsearch !pip install tqdm # Importing packages. import nltk nltk.download('punkt') nltk.download('stopwords') %matplotlib inline import re import matplotlib import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selecti...
_____no_output_____
MIT
2_classical_ml_approach.ipynb
funmilola09/Recurrent-Neural-Pipeline
Creating one hot encoding from multilabelled tagged data
# In order to use one vs rest strategy we will need to one hot encoding each tag across all documents. mlb = MultiLabelBinarizer() question_tag['Tag_pop'] = question_tag['Tag'] question_tag = question_tag.join(pd.DataFrame(mlb.fit_transform(question_tag.pop('Tag_pop')), columns=mlb.classes_, ...
_____no_output_____
MIT
2_classical_ml_approach.ipynb
funmilola09/Recurrent-Neural-Pipeline
Text preprocessing
# Let us createa a very basic text preprocessor which we will use for cleaning text. def clean_text(text): text = text.lower() text = re.sub(r"what's", "what is ", text) text = re.sub(r"\'s", " ", text) text = re.sub(r"\'ve", " have ", text) text = re.sub(r"can't", "can not ", text) text = re.su...
_____no_output_____
MIT
2_classical_ml_approach.ipynb
funmilola09/Recurrent-Neural-Pipeline
Creating a 70/30 Train-Test Split
train, test = train_test_split(question_tag, random_state=42, test_size=0.30, shuffle=True) X_train = train.Body X_test = test.Body print("Train data shape : {}".format(X_train.shape)) print("Test data shape : {}".format(X_test.shape))
Train data shape : (736394,) Test data shape : (315598,)
MIT
2_classical_ml_approach.ipynb
funmilola09/Recurrent-Neural-Pipeline
Creating Bag of Words representation using TF - IDF 1. Initializing the Vectorizer object 2. Create a corpus from training data. 3. Create a document term matrix
#Initializing the Vectorizer object tfidf = TfidfVectorizer(stop_words=stop_words) #Create a corpus from training data #Create a document term matrix of training data based on the corpus. X_train_dtm = tfidf.fit_transform(X_train) #Create a document term matrix of test data based on the corpus. #Note that the dimensi...
_____no_output_____
MIT
2_classical_ml_approach.ipynb
funmilola09/Recurrent-Neural-Pipeline
Pipelinescikit-learn provides a Pipeline utility to help automate machine learning workflows. Pipelines are very common in Machine Learning systems, since there is a lot of data to manipulate and many data transformations to apply. So we will utilize pipeline to train every classifier. One Vs Rest Multilabel strategyT...
def tag_level_training_pipeline(X_train, train, X_test, test, classifier_pipeline, output_directory): #1. Create a classifier for each Tag for category in categories: print('... Processing {}'.format(category)) # 1. train the model using X_dtm & y classifier_pipeline.fit(X_train, train[category]...
/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:144: FutureWarning: The sklearn.svm.classes module is deprecated in version 0.22 and will be removed in version 0.24. The corresponding classes / functions should instead be imported from sklearn.svm. Anything that cannot be imported from sklearn.svm ...
MIT
2_classical_ml_approach.ipynb
funmilola09/Recurrent-Neural-Pipeline
Evaluating our results
# Here we define precision, recall, f1 measure at a single document level. def document_evaluation_metrics(prd_grp,grp,metric="precision"): pred_group = prd_grp if 0 in pred_group: pred_group.remove(0) group = grp set_pred_group = set(pred_group) set_group = set(group) intrsct = set_group.inter...
_____no_output_____
MIT
2_classical_ml_approach.ipynb
funmilola09/Recurrent-Neural-Pipeline
Let us train, score and evaluate Naive Bayes
#Naive Bayes Classifier NB_pipeline = Pipeline([ ('clf', OneVsRestClassifier(MultinomialNB( fit_prior=True, class_prior=None))), ]) tag_level_training_pipeline(X_train_dtm, train, X_test_dtm, test, NB_pipeline, 'NaiveBayes/') result = tag_level_predict(X_train_dtm, train...
_____no_output_____
MIT
2_classical_ml_approach.ipynb
funmilola09/Recurrent-Neural-Pipeline
Let us train, score and evaluate Support Vector Machines
#SVM Classifier SVC_pipeline = Pipeline([ ('clf', OneVsRestClassifier(LinearSVC(), n_jobs=1)), ]) tag_level_training_pipeline(X_train_dtm, train, X_test_dtm, test, SVC_pipeline, 'SVM/') result = tag_level_predict(X_train_dtm, train, X_test_dtm, test, 'SVM/') model_evaluation_stats(result, "...
... Processing .net Test accuracy is 0.9771893358006071 precision recall f1-score support 0 0.98 1.00 0.99 308362 1 0.51 0.09 0.15 7236 accuracy 0.98 315598 macro avg 0.75 0.54 0.57 ...
MIT
2_classical_ml_approach.ipynb
funmilola09/Recurrent-Neural-Pipeline
Let us train, score and evaluate Logistic Regression
#Logistic Regression Classifier LogReg_pipeline = Pipeline([ ('clf', OneVsRestClassifier(LogisticRegression(solver='sag'), n_jobs=1)), ]) tag_level_training_pipeline(X_train_dtm, train, X_test_dtm, test, LogReg_pipeline, 'LogisticRegression/') result = tag_level_predict(X_train_dtm, train, ...
_____no_output_____
MIT
2_classical_ml_approach.ipynb
funmilola09/Recurrent-Neural-Pipeline
Wikipedia Thanks-Receiver Study Randomization [J. Nathan Matias](https://twitter.com/natematias)October 29, 2019This code takes as input data described in the [randomization data format](https://docs.google.com/document/d/1plhoDbQryYQ32vZMXu8YmlLSp30QTdup43k6uTePOT4/edit?usp=drive_web&ouid=117701977297551627494) and p...
options("scipen"=9, "digits"=4) library(ggplot2) library(rlang) library(tidyverse) library(viridis) library(blockTools) library(blockrand) library(gmodels) # contains CrossTable library(DeclareDesign) library(DescTools) # contains Freq library(uuid) options(repr.plot.width=7, repr.plot.height=3.5) sessionInfo()
_____no_output_____
MIT
randomization/thanks-recipient-study-2019/generate-wikipedia-thanks-recipient-randomizations-final-10.29.2019.R.ipynb
mitmedialab/CivilServant-Wikipedia-Analysis
Load Input Dataframe
filename <- "all-thankees-historical-20191029.csv" data.path <- "/home/civilservant/Tresors/CivilServant/projects/wikipedia-integration/gratitude-study/Data Drills/thankee" recipient.df <- read.csv(file.path(data.path, "historical_output", filename))
_____no_output_____
MIT
randomization/thanks-recipient-study-2019/generate-wikipedia-thanks-recipient-randomizations-final-10.29.2019.R.ipynb
mitmedialab/CivilServant-Wikipedia-Analysis
Load Participants in the Thanker Study
thanker.df <- read.csv(file.path(data.path, "..", "thanker_hardlaunch", "randomization_output", "all-thanker-randomization-final-20190729.csv")) usernames.to.exclude <- thanker.df$user_name
_____no_output_____
MIT
randomization/thanks-recipient-study-2019/generate-wikipedia-thanks-recipient-randomizations-final-10.29.2019.R.ipynb
mitmedialab/CivilServant-Wikipedia-Analysis
Load Liaison Usernames
liaison.df <- read.csv(file.path(data.path, "..", "thanker_hardlaunch", "randomization_output", "liason-thanker-randomization-datadrill-20190718.csv")) usernames.to.exclude <- append(as.character(usernames.to.exclude), as.character(liaison.df$user_name)) print(paste(length(usernames.to....
[1] "462 usernames to exclude"
MIT
randomization/thanks-recipient-study-2019/generate-wikipedia-thanks-recipient-randomizations-final-10.29.2019.R.ipynb
mitmedialab/CivilServant-Wikipedia-Analysis
Adjust Column Names to Match Thankee Randomization Specification
recipient.df$prev_experience <- factor(as.integer(gsub("bin_", "", recipient.df$prev_experience))) recipient.df$anonymized_id <- sapply( seq_along(1:nrow(recipient.df)), UUIDgenerate ) recipient.df$newcomer <- recipient.df$prev_experience == 0 recipient.df <- subset(recipient.df, lang!="en") #recipient.df <- subset(re...
_____no_output_____
MIT
randomization/thanks-recipient-study-2019/generate-wikipedia-thanks-recipient-randomizations-final-10.29.2019.R.ipynb
mitmedialab/CivilServant-Wikipedia-Analysis
Confirm the number of participants
print("Newcomer Participants to Randomize") summary(subset(recipient.df, newcomer == 1)$lang) ## Polish Experienced Accounts print("Experienced Participants to Randomize") summary(subset(recipient.df, newcomer == 0)$lang)
[1] "Experienced Participants to Randomize"
MIT
randomization/thanks-recipient-study-2019/generate-wikipedia-thanks-recipient-randomizations-final-10.29.2019.R.ipynb
mitmedialab/CivilServant-Wikipedia-Analysis
Omit Participants Omit Participants in the Thanker Study
print(paste(nrow(recipient.df), "participants before removing thankers")) recipient.df <- subset(recipient.df, (user_name %in% usernames.to.exclude)!=TRUE) print(paste(nrow(recipient.df), "participants after removing thankers"))
[1] "3262 participants before removing thankers" [1] "3262 participants after removing thankers"
MIT
randomization/thanks-recipient-study-2019/generate-wikipedia-thanks-recipient-randomizations-final-10.29.2019.R.ipynb
mitmedialab/CivilServant-Wikipedia-Analysis
Subset values outside the 99% confidence intervalsWe are using upper confidence intervals from the first randomization, found at [generate-wikipedia-thanks-recipient-randomizations-final-07.28.3019](generate-wikipedia-thanks-recipient-randomizations-final-07.28.3019.R.ipynb) * Polish Experienced: 235.380736142341 ...
upper.conf.ints <- data.frame(lang=c("pl", "pl", "de", "ar"), newcomer=c(0,1,1,1), conf.int = c( 235.380736142341, 72.2118047599678, 54.7365066602131, ...
[1] "Language: ar" [1] " newcomer: FALSE" [1] " 0 rows from original dataset" [1] " 99% confidence intervals:" [1] " upper: " [1] " Removing 0 outliers observations because labor_hours_84_days_pre_sample is an outlier." [1] " 0 rows in trimmed dataset" [1] " newcomer: TRUE" [1] " 74...
MIT
randomization/thanks-recipient-study-2019/generate-wikipedia-thanks-recipient-randomizations-final-10.29.2019.R.ipynb
mitmedialab/CivilServant-Wikipedia-Analysis
Review and Generate Variables
print(aggregate(recipient.df.penultimate[c("labor_hours_84_days_pre_sample")], FUN=mean, by = list(recipient.df.penultimate$prev_experience))) print(CrossTable(recipient.df.penultimate$has_email, recipient.df.penultimate$newcomer, prop.r = FALSE, prop.c=TRUE, prop.t = FALSE, prop.chisq = FALSE)) ## Up...
[1] "prev_experience" 0 90 180 365 730 1460 2920 2698 63 52 69 81 102 144 [1] "Aggregate labor_hours_84_days_pre_sample" Group.1 labor_hours_84_days_pre_sample 1 0 5.878 2 90 4.519 3 180 8.063 4 365 ...
MIT
randomization/thanks-recipient-study-2019/generate-wikipedia-thanks-recipient-randomizations-final-10.29.2019.R.ipynb
mitmedialab/CivilServant-Wikipedia-Analysis
Subset Sample to Planned sample sizesSample sizes are reported in the experiment [Decisions Document](https://docs.google.com/document/d/1HryhsmWI6WthXQC7zv9Hz1a9DhpZ3FxVRLjTONuMg4I/edit)* Arabic newcomers (1750 goal) (hoping for as many as possible in first sample) * hoping for 1350 in the first sample and 400 lat...
## Seed generated by Brooklyn Integers # https://www.brooklynintegers.com/int/1495265601/ set.seed(1495265601) print("Newcomers") summary(subset(recipient.df.penultimate, newcomer==1)$lang) print("Experienced") summary(subset(recipient.df.penultimate, newcomer==0)$lang) ## CREATE THE FINAL PARTICIPANT SAMPLE BEFORE RAN...
_____no_output_____
MIT
randomization/thanks-recipient-study-2019/generate-wikipedia-thanks-recipient-randomizations-final-10.29.2019.R.ipynb
mitmedialab/CivilServant-Wikipedia-Analysis
Generate Randomization Blocks
recipient.df.final$lang_prev_experience <- factor(paste(recipient.df.final$lang, recipient.df.final$prev_experience)) colnames(recipient.df.final) ## BLOCKING VARIABLES bv = c("labor_hours_84_days_pre_sample", "num_prev_thanks_pre_sample") block.size = 2 ## TODO: CHECK TO SEE IF I CAN DO BALANCED RANDOMIZATION ## WIT...
_____no_output_____
MIT
randomization/thanks-recipient-study-2019/generate-wikipedia-thanks-recipient-randomizations-final-10.29.2019.R.ipynb
mitmedialab/CivilServant-Wikipedia-Analysis
Identify Incomplete Blocks and Remove Participants in Incomplete Blocks From the Experiment
block.sizes <- aggregate(recipient.df.final$randomization_block_id, FUN=length, by=list(recipient.df.final$randomization_block_id)) incomplete.blocks <- subset(block.sizes, x == 1)$Group.1 incomplete.blocks nrow(subset(recipient.df.final, randomization_block_id %in% incomplete.blocks)) removed.observations <- subset(re...
[1] "Removed 5 units placed in incomplete blocks."
MIT
randomization/thanks-recipient-study-2019/generate-wikipedia-thanks-recipient-randomizations-final-10.29.2019.R.ipynb
mitmedialab/CivilServant-Wikipedia-Analysis
Generate Randomizations
assignments <- block_ra(blocks=recipient.df.final$randomization_block_id, num_arms = 2, conditions = c(0,1)) recipient.df.final$randomization_arm <- assignments
_____no_output_____
MIT
randomization/thanks-recipient-study-2019/generate-wikipedia-thanks-recipient-randomizations-final-10.29.2019.R.ipynb
mitmedialab/CivilServant-Wikipedia-Analysis
Check Balance
print("Aggregating labor hours by treatment") print(aggregate(recipient.df.final[c("labor_hours_84_days_pre_sample")], FUN=mean, by = list(recipient.df.final$randomization_arm))) print("CrossTable of lang by treatment") CrossTable(recipient.df.final$lang, recipient.df.final$randomization_arm, prop.r ...
[1] "Aggregating labor hours by treatment" Group.1 labor_hours_84_days_pre_sample 1 0 6.008 2 1 5.944 [1] "CrossTable of lang by treatment" Cell Contents |-------------------------| | N | | N / Row Total | |-----------...
MIT
randomization/thanks-recipient-study-2019/generate-wikipedia-thanks-recipient-randomizations-final-10.29.2019.R.ipynb
mitmedialab/CivilServant-Wikipedia-Analysis
Subset Polish Experienced AccountsWithin Polish, identify 300 accounts (150 blocks) to include and drop all of the others.Note: since the previous randomization included a larger number of more experienced accounts, we're prioritizing accounts from experience groups 90, 180, 365, 730, and 1460 (all except 2920).
## SHOW PREVIOUS THANKS BY EXPERIENCE GROUP: recipient.df.final$count.var <- 1 print("Number of Accounts for each experience level among Polish Participants") print(aggregate(subset(recipient.df.final, lang="pl")[c("count.var")], FUN=sum, by = list(subset(recipient.df.final, lang="pl")$prev_experience))) cat("\n"...
[1] "Total number of rows: 3204" [1] "Total number of rows once we subset Polish: 3060"
MIT
randomization/thanks-recipient-study-2019/generate-wikipedia-thanks-recipient-randomizations-final-10.29.2019.R.ipynb
mitmedialab/CivilServant-Wikipedia-Analysis
Offset block IDs to be uniqueObserve the block IDs from the previous randomizations and ensure that these ones are unique and larger.
## LOAD PREVIOUS RANDOMIZATIONS prev_randomization_filename <- "thanks-recipient-randomizations-20190729.csv" prev.randomization.df <- read.csv(file.path(data.path, "randomization_output", prev_randomization_filename)) print(paste("Max Block ID: ", max(prev.randomization.df$randomization_block_id))) prev.max.block.id <...
_____no_output_____
MIT
randomization/thanks-recipient-study-2019/generate-wikipedia-thanks-recipient-randomizations-final-10.29.2019.R.ipynb
mitmedialab/CivilServant-Wikipedia-Analysis
Sort by block ID
recipient.df.final.a <- recipient.df.final.a[order(recipient.df.final.a$randomization_block_id),] print("Newcomers") summary(subset(recipient.df.final.a, newcomer==1)$lang) print("Experienced") summary(subset(recipient.df.final.a, newcomer==0)$lang)
[1] "Newcomers"
MIT
randomization/thanks-recipient-study-2019/generate-wikipedia-thanks-recipient-randomizations-final-10.29.2019.R.ipynb
mitmedialab/CivilServant-Wikipedia-Analysis
Output and Archive Randomizations
randomization.filename <- paste("thanks-recipient-randomizations-", format(Sys.Date(), format="%Y%m%d"), ".csv", sep="") write.csv(recipient.df.final.a, file = file.path(data.path, "randomization_output", randomization.filename)) colnames(recipient.df.final.a)
_____no_output_____
MIT
randomization/thanks-recipient-study-2019/generate-wikipedia-thanks-recipient-randomizations-final-10.29.2019.R.ipynb
mitmedialab/CivilServant-Wikipedia-Analysis
Get marriages
filepath = '/Volumes/backup_128G/z_repository/TBIO_data/RequestsFromTana/20190515' filename = 'marriages.tsv' read_filename = '{0}/{1}'.format(filepath, filename) marriageDf = pd.read_csv(read_filename, delimiter='\t') marriageDf.fillna('', inplace=True) marriageDf.shape, marriageDf.head()
_____no_output_____
MIT
tbio/marriages.ipynb
VincentCheng34/StudyOnPython
To unique spouses
startId = 10000 personIds = {} marriageDic = {} for idx in range(0, len(marriageDf)): row = marriageDf.loc[idx] man = str(row['?manVal']) wife = str(row['?wifeVal']) woman = str(row['?womanVal']) husband = str(row['?husbandVal']) if man != '' and man not in personIds: personIds[man...
_____no_output_____
MIT
tbio/marriages.ipynb
VincentCheng34/StudyOnPython
Read person-family map table
familymembers = 'Familymembers.xlsx' read_familymembers = '{0}/{1}'.format(filepath, familymembers) fmDf = pd.read_excel(read_familymembers) fmDf.shape, fmDf.head() startId = 20000 familyIds = {} fmDic = {} for idx in range(0, len(fmDf)): row = fmDf.loc[idx] person = str(row['personStr']) family = str(row...
_____no_output_____
MIT
tbio/marriages.ipynb
VincentCheng34/StudyOnPython
results `Source (Family)` | `Target(Family)`| `Type(Undirected)` | `Person/Source` | `Person/target`
def getFamilyName(INperson): if INperson not in fmDic: # print(INperson, " Not found!") return '' return fmDic[INperson] def getPersonId(INperson): if INperson not in personIds: return 0 return personIds[INperson] def getFamilyId(INfamily): if INfamily not in familyIds: ...
_____no_output_____
MIT
tbio/marriages.ipynb
VincentCheng34/StudyOnPython
LeNet Lab Solution![LeNet Architecture](lenet.png)Source: Yan LeCun Load DataLoad the MNIST data, which comes pre-loaded with TensorFlow.You do not need to modify this section.
from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", reshape=False) X_train, y_train = mnist.train.images, mnist.train.labels X_validation, y_validation = mnist.validation.images, mnist.validation.labels X_test, y_test = mnist.test.images, mn...
G:\ProgramData\Anaconda3\envs\tensorflow\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters as _register_convert...
MIT
LeNet-Lab-Solution.ipynb
mdeopujari/CarND-Traffic-Sign-Classifier-Project
The MNIST data that TensorFlow pre-loads comes as 28x28x1 images.However, the LeNet architecture only accepts 32x32xC images, where C is the number of color channels.In order to reformat the MNIST data into a shape that LeNet will accept, we pad the data with two rows of zeros on the top and bottom, and two columns of ...
import numpy as np # Pad images with 0s X_train = np.pad(X_train, ((0,0),(2,2),(2,2),(0,0)), 'constant') X_validation = np.pad(X_validation, ((0,0),(2,2),(2,2),(0,0)), 'constant') X_test = np.pad(X_test, ((0,0),(2,2),(2,2),(0,0)), 'constant') print("Updated Image Shape: {}".format(X_train[0].shape))
Updated Image Shape: (36, 36, 1)
MIT
LeNet-Lab-Solution.ipynb
mdeopujari/CarND-Traffic-Sign-Classifier-Project
Visualize DataView a sample from the dataset.You do not need to modify this section.
import random import numpy as np import matplotlib.pyplot as plt %matplotlib inline index = random.randint(0, len(X_train)) image = X_train[index].squeeze() plt.figure(figsize=(1,1)) plt.imshow(image, cmap="gray") print(y_train[index])
(32, 32) 4
MIT
LeNet-Lab-Solution.ipynb
mdeopujari/CarND-Traffic-Sign-Classifier-Project
Preprocess DataShuffle the training data.You do not need to modify this section.
from sklearn.utils import shuffle X_train, y_train = shuffle(X_train, y_train)
_____no_output_____
MIT
LeNet-Lab-Solution.ipynb
mdeopujari/CarND-Traffic-Sign-Classifier-Project
Setup TensorFlowThe `EPOCH` and `BATCH_SIZE` values affect the training speed and model accuracy.You do not need to modify this section.
import tensorflow as tf EPOCHS = 10 BATCH_SIZE = 128
_____no_output_____
MIT
LeNet-Lab-Solution.ipynb
mdeopujari/CarND-Traffic-Sign-Classifier-Project
SOLUTION: Implement LeNet-5Implement the [LeNet-5](http://yann.lecun.com/exdb/lenet/) neural network architecture.This is the only cell you need to edit. InputThe LeNet architecture accepts a 32x32xC image as input, where C is the number of color channels. Since MNIST images are grayscale, C is 1 in this case. Archite...
from tensorflow.contrib.layers import flatten def LeNet(x): # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer mu = 0 sigma = 0.1 # SOLUTION: Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6. conv1_W = tf.Variable(tf.trun...
_____no_output_____
MIT
LeNet-Lab-Solution.ipynb
mdeopujari/CarND-Traffic-Sign-Classifier-Project
Features and LabelsTrain LeNet to classify [MNIST](http://yann.lecun.com/exdb/mnist/) data.`x` is a placeholder for a batch of input images.`y` is a placeholder for a batch of output labels.You do not need to modify this section.
x = tf.placeholder(tf.float32, (None, 32, 32, 1)) y = tf.placeholder(tf.int32, (None)) one_hot_y = tf.one_hot(y, 10)
_____no_output_____
MIT
LeNet-Lab-Solution.ipynb
mdeopujari/CarND-Traffic-Sign-Classifier-Project
Training PipelineCreate a training pipeline that uses the model to classify MNIST data.You do not need to modify this section.
rate = 0.001 logits = LeNet(x) cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits) loss_operation = tf.reduce_mean(cross_entropy) optimizer = tf.train.AdamOptimizer(learning_rate = rate) training_operation = optimizer.minimize(loss_operation)
_____no_output_____
MIT
LeNet-Lab-Solution.ipynb
mdeopujari/CarND-Traffic-Sign-Classifier-Project
Model EvaluationEvaluate how well the loss and accuracy of the model for a given dataset.You do not need to modify this section.
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1)) accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) saver = tf.train.Saver() def evaluate(X_data, y_data): num_examples = len(X_data) total_accuracy = 0 sess = tf.get_default_session() for offset in ra...
_____no_output_____
MIT
LeNet-Lab-Solution.ipynb
mdeopujari/CarND-Traffic-Sign-Classifier-Project
Train the ModelRun the training data through the training pipeline to train the model.Before each epoch, shuffle the training set.After each epoch, measure the loss and accuracy of the validation set.Save the model after training.You do not need to modify this section.
with tf.Session() as sess: sess.run(tf.global_variables_initializer()) num_examples = len(X_train) print("Training...") print() for i in range(EPOCHS): X_train, y_train = shuffle(X_train, y_train) for offset in range(0, num_examples, BATCH_SIZE): end = offset + BATCH...
_____no_output_____
MIT
LeNet-Lab-Solution.ipynb
mdeopujari/CarND-Traffic-Sign-Classifier-Project
Evaluate the ModelOnce you are completely satisfied with your model, evaluate the performance of the model on the test set.Be sure to only do this once!If you were to measure the performance of your trained model on the test set, then improve your model, and then measure the performance of your model on the test set a...
with tf.Session() as sess: saver.restore(sess, tf.train.latest_checkpoint('.')) test_accuracy = evaluate(X_test, y_test) print("Test Accuracy = {:.3f}".format(test_accuracy))
_____no_output_____
MIT
LeNet-Lab-Solution.ipynb
mdeopujari/CarND-Traffic-Sign-Classifier-Project
Get data for only hepatocytes and rerun harmony+umap
# Reprocess t cell data for ds in DS_LIST: print(ds) ind_select = dic_data_raw[ds].obs['cell_ontology_class']=='hepatocyte' adata = dic_data_raw[ds][ind_select,:].copy() sc.pp.filter_cells(adata, min_genes=250) sc.pp.filter_genes(adata, min_cells=50) adata.obs['batch_harmony'] = adata.obs['mouse...
_____no_output_____
MIT
experiments/job.case_hepatocyte/s1_reprocess_tms_droplet_hep.ipynb
martinjzhang/scDRS
Dot Placeholder Pull() and dot behaves in the same way
library(tidyverse) library(dslabs) data(murders) murders <- murders %>% mutate(murder_rate = (total/population) * 100000) summarize(murders, mean = mean(murder_rate)) us_murder_rate <- murders %>% summarize(rate = sum(total)/ sum(population) *100000) r <- us_murder_rate %>% .$rate class(r) r class(us_murder_rate$rat...
_____no_output_____
MIT
HAR_DM/Practice Work/Summarizing with dplyr.ipynb
ashudva/HAR
Gaussian Mixture Models (GMM)KDE centers each bin (or kernel rather) at each point. In a [**mixture model**](https://en.wikipedia.org/wiki/Mixture_model) we don't use a kernel for each data point, but rather we fit for the *locations of the kernels*--in addition to the width. So a mixture model is sort of a hybrid b...
from IPython.display import YouTubeVideo YouTubeVideo("B36fzChfyGU")
_____no_output_____
MIT
MixtureModel.ipynb
gtrichards/PHYS_T480
A typical call to the [Gaussian Mixture Model](http://scikit-learn.org/stable/modules/mixture.html) algorithm looks like this:
# Execute this cell import numpy as np from sklearn.mixture import GMM X = np.random.normal(size=(1000,2)) #1000 points in 2D gmm = GMM(3) #three components gmm.fit(X) log_dens = gmm.score(X) BIC = gmm.bic(X)
_____no_output_____
MIT
MixtureModel.ipynb
gtrichards/PHYS_T480
Let's start with the 1-D example given in Ivezic, Figure 6.8, which compares a Mixture Model to KDE.[Note that the version at astroML.org has some bugs!]
# Execute this cell # Ivezic, Figure 6.8 # Author: Jake VanderPlas # License: BSD # The figure produced by this code is published in the textbook # "Statistics, Data Mining, and Machine Learning in Astronomy" (2013) # For more information, see http://astroML.github.com # To report a bug or issue, use the follow...
_____no_output_____
MIT
MixtureModel.ipynb
gtrichards/PHYS_T480
Hmm, that doesn't look so great for the 5000 point distribution. Plot the BIC values and see if anything looks awry. What do the individual components look like? Make a plot of those. Careful with the shapes of the arrays! Can you figure out something that you can do to improve the results? Ivezic, Figure 6.6 shows...
# Execute this cell # Ivezic, Figure 6.6 # Author: Jake VanderPlas # License: BSD # The figure produced by this code is published in the textbook # "Statistics, Data Mining, and Machine Learning in Astronomy" (2013) # For more information, see http://astroML.github.com # To report a bug or issue, use the follow...
_____no_output_____
MIT
MixtureModel.ipynb
gtrichards/PHYS_T480
That said, I'd say that there are *too* many components here. So, I'd be inclined to explore this a bit further if it were my data.Lastly, let's look at a 2-D case where we are using GMM more to characterize the data than to find clusters.
# Execute this cell # Ivezic, Figure 6.7 # Author: Jake VanderPlas # License: BSD # The figure produced by this code is published in the textbook # "Statistics, Data Mining, and Machine Learning in Astronomy" (2013) # For more information, see http://astroML.github.com # To report a bug or issue, use the follow...
_____no_output_____
MIT
MixtureModel.ipynb
gtrichards/PHYS_T480
Initial changes
ds_train = TiggeMRMSDataset( tigge_dir=f'{DATADRIVE}/tigge/32km/', tigge_vars=['total_precipitation'], mrms_dir=f'{DATADRIVE}/mrms/4km/RadarOnly_QPE_06H/', rq_fn=f'{DATADRIVE}/mrms/4km/RadarQuality.nc', # const_fn='/datadrive/tigge/32km/constants.nc', # const_vars=['orog', 'lsm'], data_perio...
_____no_output_____
MIT
notebooks/stephan_notebooks/10-Categorical.ipynb
raspstephan/nwp-downscale
Changes implemented
cat_bins = np.arange(0, 55, 5, dtype='float') cat_bins = np.append(np.insert(cat_bins, 1, 0.01), np.inf) len(cat_bins) plt.plot(cat_bins) ds_train = TiggeMRMSDataset( tigge_dir=f'{DATADRIVE}/tigge/32km/', tigge_vars=['total_precipitation'], mrms_dir=f'{DATADRIVE}/mrms/4km/RadarOnly_QPE_06H/', rq_fn=f'{D...
_____no_output_____
MIT
notebooks/stephan_notebooks/10-Categorical.ipynb
raspstephan/nwp-downscale
Overfitting test MSE
ds_train = TiggeMRMSDataset( tigge_dir=f'{DATADRIVE}/tigge/32km/', tigge_vars=['total_precipitation'], mrms_dir=f'{DATADRIVE}/mrms/4km/RadarOnly_QPE_06H/', rq_fn=f'{DATADRIVE}/mrms/4km/RadarQuality.nc', # const_fn='/datadrive/tigge/32km/constants.nc', # const_vars=['orog', 'lsm'], data_perio...
_____no_output_____
MIT
notebooks/stephan_notebooks/10-Categorical.ipynb
raspstephan/nwp-downscale
--- Saving your plot to a file (or to an io buffer):- `mplfinance.plot()` allows you to save your plot to a file, or io-buffer, using the `savefig` keyword.- The value of `savefig` may be a `str`, `dict`, or `io.ByteIO` object. - If the value is a `str` then it is assumed to be the file name to which to save the fig...
df = pd.read_csv('data/SP500_NOV2019_Hist.csv',index_col=0,parse_dates=True) %%capture ## cell magic function `%%capture` blocks jupyter notebook output, ## which is not needed here since the plot is saved to a file anyway: mpf.plot(df,type='candle',volume=True,savefig='testsave.png')
_____no_output_____
Apache-2.0
examples/savefig.ipynb
fadeawaylove/stock-trade-system
--- We can use IPython.display.Image to display the image file here in the notebook:
import IPython.display as IPydisplay %ls -l testsave.png IPydisplay.Image(filename='testsave.png')
-rw-rw-rw- 1 dino dino 24877 Jun 7 17:52 testsave.png
Apache-2.0
examples/savefig.ipynb
fadeawaylove/stock-trade-system
--- We can use io to save the plot as a byte buffer:
%%capture ## cell magic function `%%capture` blocks jupyter notebook output, ## which is not needed here, since the plot is saved to the io-buffer anyway: buf = io.BytesIO() mpf.plot(df,type='candle',volume=True,savefig=buf) buf.seek(0)
_____no_output_____
Apache-2.0
examples/savefig.ipynb
fadeawaylove/stock-trade-system
We can use Ipython.display.Image to display the image in the ioBytes buffer:
IPydisplay.Image(buf.read())
_____no_output_____
Apache-2.0
examples/savefig.ipynb
fadeawaylove/stock-trade-system
--- Specifying image attributes with `savefig`We can control various attributes of the saved figure/plot by passing a `dict`ionary as the value for the `savefig` keyword.The dictionary **must** contain the keyword `fname` for the file name to be saved, **and *may* contain any of the other keywords accepted by [`matplot...
%%capture ## %%capture blocks jupyter notebook output; plots are saved to files anyway: save = dict(fname='tsave30.jpg',dpi=30,pad_inches=0.25) mpf.plot(df,volume=True,savefig=save) mpf.plot(df,volume=True,savefig=dict(fname='tsave100.jpg',dpi=100,pad_inches=0.25)) %ls -l tsave30.jpg %ls -l tsave100.jpg IPydisplay.Imag...
-rw-rw-rw- 1 dino dino 11016 Jun 7 17:52 tsave30.jpg -rw-rw-rw- 1 dino dino 54172 Jun 7 17:52 tsave100.jpg
Apache-2.0
examples/savefig.ipynb
fadeawaylove/stock-trade-system
Specifying image attributes (via `savefig`) dict also works with an io.BytesIO buffer:- Just assign the io-buffer to the `fname` key in the savefig dict
%%capture buf30dpi = io.BytesIO() buf100dpi = io.BytesIO() mpf.plot(df,volume=True,savefig=dict(fname=buf30dpi ,dpi=30 ,pad_inches=0.25)) mpf.plot(df,volume=True,savefig=dict(fname=buf100dpi,dpi=100,pad_inches=0.25))
_____no_output_____
Apache-2.0
examples/savefig.ipynb
fadeawaylove/stock-trade-system
Use Ipython.display.Image to display the buffer contents:
_ = buf30dpi.seek(0) IPydisplay.Image(buf30dpi.read()) _ = buf100dpi.seek(0) IPydisplay.Image(buf100dpi.read())
_____no_output_____
Apache-2.0
examples/savefig.ipynb
fadeawaylove/stock-trade-system
Oxford University COVID-19 forecasting project dataThe data below was downloaded from the [Oxford University countermeasures database](https://www.notion.so/COVID-19-countermeasures-database-b532a58d6f944ef6982ab565627bdb08). See the website for a description of the data sources.
countermeasures_df = pd.read_csv("data/containment_measures_march23.csv") countermeasures_df.head(1) countermeasures_df[["Country", "Date Start", "Description of measure implemented"]].groupby("Country").head(10) print(countermeasures_df["Country"].unique()) print(countermeasures_df["Implementing City"].unique()) print...
[nan 'Quang Ninh' 'Gyeongbook Province' 'Daegu, Gyeongbook Province' 'Busan' 'Hubei' 'Hunan' 'Tianjin' 'Zheijang' 'Meituan' 'Chongqing' 'Zhejian' 'Shanghai' 'Sichuan' 'Jiangsu' 'Guangdong' 'Hangzhou' 'Shenzhen' 'Leishenshan' 'Guangzhou' 'Kanagawa prefecture' 'Guangxi' 'Guizhou' 'Huanggang' 'Henan, Shandong' 'Liaoni...
MIT
notebooks/data_sources.ipynb
braadbaart/covid19
John Hopkins containment measures databaseThe data is made available as part of the John Hopkins [Containment Measures Database](http://epidemicforecasting.org/containment). See the website in the link for a description of the data sources.
containment_df = pd.read_csv("data/countermeasures_db_johnshopkins_2020_03_30.csv") containment_df.columns print(containment_df["Country"].unique()) cases_df = containment_df[["Date", "Country", "Confirmed Cases", "Deaths"]]\ .loc[containment_df["Confirmed Cases"] > 3000]\ .pivot(index="Date", columns="Country", values...
_____no_output_____
MIT
notebooks/data_sources.ipynb
braadbaart/covid19
**Rendering component declaration.**
# imports for setting up display for the colab server. !sudo apt-get update > /dev/null 2>&1 !sudo apt-get install -y xvfb x11-utils > /dev/null 2>&1 !pip install gym==0.17.* pyvirtualdisplay==0.2.* PyOpenGL==3.1.* PyOpenGL-accelerate==3.1.* > /dev/null 2>&1 # gym related import statements. import gym from gym impor...
_____no_output_____
Unlicense
milestone-two/sarsa_lambda_agent_mountain_car_v0.ipynb
galleon/prototyping-self-driving-agents
**SARSA(Lambda) Algorithm Implementation for MountainCarV0 Environment**__The implementation consists of below stated sections:__ * __Agent class decleration and parsing environment.__* __SARSA(LAMBDA) Algorithm Implementation.__* __Plotting results, outputting results and downloading them.__ **Agent Class Declerati...
# This environment has two degrees of freedom: position and velocity. # Our agent will learn to interact with environment having these two values. class State: def __init__(self): self.pos = None self.vel = None # Agent class defined for storing all the agent related values. # and getting actions f...
Q Shape = (30, 20, 3)
Unlicense
milestone-two/sarsa_lambda_agent_mountain_car_v0.ipynb
galleon/prototyping-self-driving-agents
**SARSA(Lambda) algorithm implementation.**
# SARSA(lambda) algorithm takes part from TD(0) and TD(1) algorithm. eps = 0.8 # greedy epsilon exploration-vs-exploitation variable. changed_eps= [] changes_alpha= [] alpha = 0.2 # learning rate value lambda_val = 0.8 # credit assignment variable to previous states. alpha_decay = 0.999 eps_decay = 0.995 sarsa_agent.e...
100%|██████████| 2000/2000 [00:52<00:00, 37.97it/s]
Unlicense
milestone-two/sarsa_lambda_agent_mountain_car_v0.ipynb
galleon/prototyping-self-driving-agents
**Plotting reward fuction resuls and displaying output.**
# This graph shows the saturation of rewards to a minimum under 1000 episodes. fig, ax = plt.subplots(figsize = (9, 5)) plt.plot(sarsa_agent.collective_record[:],'.') plt.yticks(range(-110, -200, -10)) plt.ylabel("reward function values") plt.xlabel("episode number count") plt.grid() plt.show() # Calculating the mean p...
_____no_output_____
Unlicense
milestone-two/sarsa_lambda_agent_mountain_car_v0.ipynb
galleon/prototyping-self-driving-agents
Data
df = pd.read_csv("HW5_data.csv") x = df[["X", "Y"]].values y = df.Z.values df.head() df.describe()
_____no_output_____
MIT
.ipynb_checkpoints/polynomial_feat-checkpoint.ipynb
borab96/misc-notebooks
The data is split into training, validation and test sets with ratios $0.6:0.2:0.2$
x_train, x_val, x_test, y_train, y_val, y_test = train_test_val_split(x, y) print("Training size") print(x_train.shape) print("Validation size") print(x_val.shape) print("Test size") print(x_test.shape)
Training size (600, 2) Validation size (200, 2) Test size (200, 2)
MIT
.ipynb_checkpoints/polynomial_feat-checkpoint.ipynb
borab96/misc-notebooks
Model We are told to apply a polynomial transformation on the features and use linear regression to obtain the optimal coefficients of the polynomial fit. We create a simple pipeline to achieve this. The only hyperparameter is the maximal degree of the polynomial feature map. The feature map ignores the bias but the ...
def poly_fit_pipeline(degree): polynomial_features = PolynomialFeatures(degree=degree, include_bias=False) pipeline = Pipeline([("polynomial_features", polynomial_features), ("linear_regression", LinearRegression())]) return pipeline degrees = [2,3,4,5,6,7] mse = [] for d in degrees: model = poly_fit...
Training MSE: 0.008621014128936854 Validation MSE: 0.00895723100171667 Test MSE: 0.009421933878894272
MIT
.ipynb_checkpoints/polynomial_feat-checkpoint.ipynb
borab96/misc-notebooks
The optimization over the hyperparameter space indicates that a maximal degree of $6$ is optimal. Notice that the difference between a degree 5 fit and a degree 6 fit is miniscule so one could also go with the less complex model that offers very similar accuracy. We'll stick with $D=6$ though. Details of the optimal ...
print("Model parameters") print(model_optimal.get_params()) print("regression coefficients") print(model_optimal['linear_regression'].coef_) print("regression intercept") print(model_optimal['linear_regression'].intercept_)
Model parameters {'memory': None, 'steps': [('polynomial_features', PolynomialFeatures(degree=6, include_bias=False, interaction_only=False, order='C')), ('linear_regression', LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False))], 'verbose': False, 'polynomial_features': P...
MIT
.ipynb_checkpoints/polynomial_feat-checkpoint.ipynb
borab96/misc-notebooks
Object Detection Setup
#@title import os !pip install --quiet tensorflow_text os.environ["TFHUB_MODEL_LOAD_FORMAT"] = "COMPRESSED" #@title import os import math import numpy as np import requests import tensorflow as tf import tensorflow_hub as hub import tensorflow_text as tf_text import tensorflow_datasets as tfds import matplotlib.p...
_____no_output_____
Apache-2.0
notebooks/supervised/detection/object-detection-efficientdet-d4.ipynb
lucasdavid/algorithms-in-tensorflow
Model Definition
detector = hub.load("https://tfhub.dev/tensorflow/efficientdet/d4/1")
_____no_output_____
Apache-2.0
notebooks/supervised/detection/object-detection-efficientdet-d4.ipynb
lucasdavid/algorithms-in-tensorflow
Application
INPUT_SHAPE = [299, 299, 3] DATA_DIR = 'images/' IMAGES = [ 'https://raw.githubusercontent.com/keisen/tf-keras-vis/master/examples/images/goldfish.jpg', 'https://raw.githubusercontent.com/keisen/tf-keras-vis/master/examples/images/bear.jpg', 'https://raw.githubusercontent.com/keisen/tf-keras-vis/master/examples/...
_____no_output_____
Apache-2.0
notebooks/supervised/detection/object-detection-efficientdet-d4.ipynb
lucasdavid/algorithms-in-tensorflow
Imports
from IPython.display import clear_output !pip install path.py !pip install pytorch3d clear_output() import numpy as np import math import random import os import plotly.graph_objects as go import plotly.express as px import torch from torch.utils.data import Dataset, DataLoader, Subset from torchvision import transfor...
_____no_output_____
MIT
data_processing.ipynb
annwhoorma/pmldl-project
Data Preprocessing (optional)
with open(path/"dresser/train/dresser_0001.off", 'r') as f: verts, faces = read_off(f) i, j, k = np.array(faces).T x, y, z = np.array(verts).T # len(x) # visualize_rotate([go.Mesh3d(x=x, y=y, z=z, color='lightpink', opacity=0.50, i=i,j=j,k=k)]).show() # visualize_rotate([go.Scatter3d(x=x, y=y, z=z, mode='markers'...
_____no_output_____
MIT
data_processing.ipynb
annwhoorma/pmldl-project
Creating Loaders for Final Progress Report Redefine classes
class PointCloudData(Dataset): def __init__(self, root_dir, valid=False, folder="train", transform=default_transforms(), folders=None): self.root_dir = root_dir if not folders: folders = [dir for dir in sorted(os.listdir(root_dir)) if os.path.isdir(root_dir/dir)] self.classes = {...
_____no_output_____
MIT
data_processing.ipynb
annwhoorma/pmldl-project
Overfitting - all augmentations applied before training
BATCH_SIZE = 48 trs = transforms.Compose([ PointSampler(1024), ToSorted(), Normalize(), ToTensor() ]) beds_train_dataset = PointCloudDataPre(path, folders=['bed'], transform=trs) beds_valid_dataset = PointCloudDataPre(path...
mkdir: cannot create directory ‘dataloader_beds_pre’: File exists mkdir: cannot create directory ‘drive/MyDrive/Thesis/dataloaders/final’: File exists
MIT
data_processing.ipynb
annwhoorma/pmldl-project
Underfitting - all augmentations applied during training
BATCH_SIZE = 48 trs = transforms.Compose([ PointSampler(1024), ToSorted(), Normalize(), RandomNoise(), ToTensor() ]) beds_train_dataset = PointCloudData(path, fold...
/usr/local/lib/python3.7/dist-packages/torch/utils/data/dataloader.py:481: UserWarning: This DataLoader will create 4 worker processes in total. Our suggested max number of worker in current system is 2, which is smaller than what this DataLoader is going to create. Please be aware that excessive worker creation might...
MIT
data_processing.ipynb
annwhoorma/pmldl-project
Both - static and dynamic transformations
BATCH_SIZE = 48 static_trs = transforms.Compose([ PointSampler(1024), ToSorted(), Normalize(), ]) dynamic_trs = transforms.Compose([ RandomNoise(), ToTensor() ]) ...
mkdir: cannot create directory ‘dataloader_beds_both’: File exists
MIT
data_processing.ipynb
annwhoorma/pmldl-project
Two classes: beds and tables
BATCH_SIZE = 48 static_trs = transforms.Compose([ PointSampler(1024), ToSorted(), Normalize(), ]) dynamic_trs = transforms.Compose([ RandomNoise(), ToTensor() ]) ...
_____no_output_____
MIT
data_processing.ipynb
annwhoorma/pmldl-project
For 512
!mkdir drive/MyDrive/Thesis/dataloaders/final512
_____no_output_____
MIT
data_processing.ipynb
annwhoorma/pmldl-project
Overfitting - all augmentations applied before training
BATCH_SIZE = 48 trs = transforms.Compose([ PointSampler(512), ToSorted(), Normalize(), ToTensor() ]) beds_train_dataset = PointCloudDataPre(path, folders=['bed'], transform=trs) beds_valid_dataset = PointCloudDataPre(path,...
mkdir: cannot create directory ‘dataloader_beds_pre’: File exists mkdir: cannot create directory ‘drive/MyDrive/Thesis/dataloaders/final’: File exists
MIT
data_processing.ipynb
annwhoorma/pmldl-project
Underfitting - all augmentations applied during training
BATCH_SIZE = 48 trs = transforms.Compose([ PointSampler(512), ToSorted(), Normalize(), ToTensor() ]) beds_train_dataset = PointCloudData(path, folders=['bed'], transform=trs) beds_valid_dataset ...
/usr/local/lib/python3.7/dist-packages/torch/utils/data/dataloader.py:481: UserWarning: This DataLoader will create 4 worker processes in total. Our suggested max number of worker in current system is 2, which is smaller than what this DataLoader is going to create. Please be aware that excessive worker creation might...
MIT
data_processing.ipynb
annwhoorma/pmldl-project
Both - static and dynamic transformations
BATCH_SIZE = 48 static_trs = transforms.Compose([ PointSampler(512), ToSorted(), Normalize(), ]) dynamic_trs = transforms.Compose([ RandomNoise(), ToTensor() ]) b...
mkdir: cannot create directory ‘dataloader_beds_both’: File exists
MIT
data_processing.ipynb
annwhoorma/pmldl-project
Two classes: beds and tables
BATCH_SIZE = 48 static_trs = transforms.Compose([ PointSampler(512), ToSorted(), Normalize(), ]) dynamic_trs = transforms.Compose([ RandomNoise(), ToTensor() ]) b...
_____no_output_____
MIT
data_processing.ipynb
annwhoorma/pmldl-project
Fill in full author references for mentions of authorsFor example, if we find `Calderon`, we want to produce a string```Pedro Calderón de la Barca```
testTexts = [ "Calderón de la Barca, Pedro", "CCCCCalderón", "Caldeeeeeerón", "Pedro Barca", "Pedro Barca", "Agustin Moreto", "A. Moreto", "Agustin", "Augustine", ]
_____no_output_____
MIT
pyling/detectAuthors.ipynb
dirkroorda/explore
TriggersWe are going to find trigger strings for authors in the input texts.In order to do that successfully, we normalize the text first:* we remove all accents from accented letters* we make everything lowercase We need a function that can strip accents from characters.From [stackoverflow](https://stackoverflow.com/...
import re import unicodedata def normalize(text): text = unicodedata.normalize('NFD', text) text = text.encode('ascii', 'ignore') text = text.decode("utf-8") return text.lower().strip() normalize("Calderón de la Barca, Pedro")
_____no_output_____
MIT
pyling/detectAuthors.ipynb
dirkroorda/explore
AuthorsWe compile a list of authors that we want to detect.For each author we have a full name, a key, and a list of triggers.We format the specficiation as a *yaml* file (which maps to a Python dictionary).
authorSpec = ''' cald: full: Pedro Calderón de la Barca triggers: - calderon - barca more: full: Agustín Moreto triggers: - moreto - agustin - augustine '''
_____no_output_____
MIT
pyling/detectAuthors.ipynb
dirkroorda/explore