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 |
|---|---|---|---|---|---|
End Comment Working with bigger data - online algorithms and out-of-core learning | import numpy as np
import re
from nltk.corpus import stopwords
def tokenizer(text):
text = re.sub('<[^>]*>', '', text)
emoticons = re.findall('(?::|;|=)(?:-)?(?:\)|\(|D|P)', text.lower())
text = re.sub('[\W]+', ' ', text.lower()) + ' '.join(emoticons).replace('-', '')
tokenized = [w for w in text.split... | _____no_output_____ | MIT | .ipynb_checkpoints/sentiment_analysis-checkpoint.ipynb | prakharchoudhary/SentimentalAnalysis |
Serializing fitted scikit-learn estimators | '''
serialize the classifier as a pickle file
'''
import pickle
import os
dest = os.path.join('movieclassifier', 'pkl_objects')
if not os.path.exists(dest):
os.makedirs(dest)
# we serialize our stopwords so that we do not have to install NLTK on our servers
pickle.dump(stop,
open(os.path.join(... | Prediction: positive
Probability: 85.93
| MIT | .ipynb_checkpoints/sentiment_analysis-checkpoint.ipynb | prakharchoudhary/SentimentalAnalysis |
01_core ObjectivesTo create end-to-end multimodal classifers based on Fastai-tabular, Fastai-text and Fastai-vision.Specifically, I will construct 3 types of multimodal model:- `early concat`: concatinate cnt, cat, txt, img after data loading and data preprocessing, followed by a learner of choice (e.g. fastai tabular... | !pip install nbdev
# install most updated fastai & utils
! [ -e /content ] && pip install -Uqq fastai
#!pip install git+https://github.com/fastai/fastai # to deal with Error: found at least two devices, cuda:0 and cpu
"""
!pip install fastai wwf bayesian-optimization -q --upgrade
!pip install autogluon
"""
# auto ... | Requirement already satisfied: nbdev in /usr/local/lib/python3.7/dist-packages (1.2.5)
Requirement already satisfied: jupyter-client<8 in /usr/local/lib/python3.7/dist-packages (from nbdev) (7.2.2)
Requirement already satisfied: Jinja2<3.1.0 in /usr/local/lib/python3.7/dist-packages (from nbdev) (2.11.3)
Requirement al... | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
nbdev setup Since we don't have access to our Drive yet, be sure to hit the `Mount Drive` to mount it | #colab
from google.colab import drive
drive.mount('/content/drive') | Mounted at /content/drive
| Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
Now let's work out of our new library | from pathlib import Path
import os
!pwd
git_path = Path('drive/My Drive/fastai_multimodal')
#git_path = Path('drive/My Drive/techskills')
os.chdir(git_path)
!pwd
#export
from nbdev_colab.core import * | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
We'll make a quick addition function Now let's put in our hooks and update our library. We can just work out of our local directory now as we changed our working directory | #colab
setup_git('.', 'fastai_multimodal', 'wjlgatech', 'my-github-token', 'wjlgatech@gmail.com')
#colab
#git_push('.', '01 after simplify and re-organize this notebook')
start = os.getcwd()
os.chdir('.')
!nbdev_install_git_hooks
!nbdev_build_lib
!git add *
!git commit -m "04/01/22 5:40pm add Error Analysis & bigdata ... | [master e6f3cf4] 04/01/22 5:40pm add Error Analysis & bigdata ML 2 solutions
11 files changed, 3685 insertions(+), 485 deletions(-)
rewrite model/tabular_ensemble_enbeddings.pth (94%)
rewrite model/tabular_model.pth (89%)
remote: Invalid username or password.
fatal: Authentication failed for 'https://wjlgatech:ghp_6... | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
load packages | !pip install fastai wwf bayesian-optimization -q --upgrade
#export
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import requests
import re
import os
from fastai.tabular.all import *
from fastai.text.all import *
from fastai.vision.all import *
import tensorflow as tf | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
setup experimentNow set up experiemnt by choosing these experiment configs:- i: which dataset to choose- nrows: what large the dataset is | #choose the ith dataset
i = 1
#choose df size
nrows=5*10**2
#creat experiment config df
config_df = pd.DataFrame({'nrows': [nrows]*5,
'data_file': ['df_income.csv','df_entailment.csv', 'df_adoption.csv','df_salary.csv','iu_2022_101_325.csv'],
'label_col':["income_level",... | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
train test split | #export
def split_train_valid_test(df, train_valid_test=[0.7,0.15, 0.15], target='response_status', random_state=123, sort_split_by_col='start_datetime'):
'''Splits a Pandas Dataframe into training, evaluation and serving sets, stratifying on target column.
Args:
df : pandas dataframe to split
... | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
identify cnt_cols, cat_cols, txt_cols, img_cols | #export
import requests
def check_path(path):
"""check if path is a valid directory or not"""
try:
return os.path.exists(os.path.dirname(path))
except:
return False
def check_url(path):
"""check if path is a valid url or not"""
try: return requests.get(path)
except:
if 'http' ... | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
1) fastai text classifierThe limitation of fastai text classifier is that it only accept 1 txt_col. To deal with this limitation, I have 2 options:- run fastai text classifier through each of txt_cols and then later combine the output through some ensemble learner.- combine all txt_cols into one text col and run fasta... | #export
#! [ -e /content ] && pip install -Uqq fastai # upgrade fastai on colab
#from fastai.text.all import *
def train_fastai_text_classifier(df:pd.DataFrame, txt_col:str, label_col:str, model_path:str, lr:float=0.005, max_epochs:int=100, emb_size:int=128):
"""train a fastai text classifier and get its performa... | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
module: get_fastai_docs_embsInstead of using out of box embedding methods (tfidf, USE, SBERT), I want to use classifier based embedding method to calculate document embedding.References:- [Getting Document Encodings From ULMFiT (updated for Fastai v2)](https://alanjjian.medium.com/getting-document-encodings-from-ulmfi... | #export
def get_fastai_docs_embs(docs:list, learn, lm, df=None, txt_col=None):
"""use classifier to get document embedding vector (np.array)
Args:
docs:list of str e.g. ['Python (programming language)', 'Data Science', 'git, GitHub, NLP']
learn: e.g. fastai.text.learner.TextLearner
lm: e.g. fa... | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
2) fastai image classifier | #export
#from fastai.vision.all import *
def train_fastai_image_classifier(df:pd.DataFrame, label_col:str, img_col:str, img_path:str, model_path:str, model_name:str, lr:float=0.005, max_epochs:int=100, img_size:int=224, bs:int=64, emb_size:int=128):
"""train and evaluate a fastai image classifier, where image data... | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
module: get_fastai_imgs_embs() | #export
def get_fastai_imgs_embs(img_clf, df:pd.DataFrame=None, img_col:str=None):
"""use classifier to get image embedding vector (np.array)
Args:
img_clf: e.g. fastai.learner.Learner
df[[img_col]] store the path of image files
Returns:
embs: a np.array of shape (num_samples, 512)
Ex... | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
3) fastai tabular classifer | #export
#from fastai.tabular.all import *
def split_idxs(df, train_size=.9, flag_random_split=True):
""" split df index into 2 parts: train_idxs and test_idxs
Args:
df: the dataframe of all your data
train_size (float in [0,1], default 0.9)
flag_random_split(bool, default False): do y... | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
module: get_fastai_tab_embs() | #export
def get_fastai_tab_embs(tab_clf, df:pd.DataFrame, cnt_cols:list=None, cat_cols:list=None):
"""use classifier to get image embedding vector (np.array)
Args:
tab_clf: e.g. fastai.tabular.learner.TabularLearner
df[cnt_cols+cat_cols]
Returns:
embs: a np.array of shape (num_samples, 512... | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
4) ensembled modelsBig idea: you can blend multiple classifiers at different stages:- `early concat`: concatinate cnt, cat, txt, img after data loading and data preprocessing, followed by a learner of choice (e.g. fastai tabular).- `middle concat`: concatinate the embeddings from each of the trained tab (cnt+cat), txt... | #export
def train_ensembled_classifier(embs_ls, lr:float=0.005, max_epochs:int=10, model_path:str='/content/drive/My Drive/fastai_multimodal/model/', model_name:str='tabular_ensemble_enbeddings', n_components:float=1, df=df, label_col=label_col, emb_size=128):
"""train an ensembled classifier, using fastai tabular ... | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
5) End2End fastai multimodal model | #export
class Fastai_Multimodal_Classifier():
"""end to end fastai classifier for multimodal data which includes txt_cols, img_cols, cnt_cols, cat_cols"""
def __init__(self, txt_clfs=None, lms=None, tab_clf=None, img_clfs=None, ensembled_clf_embs=None, ensembled_clf_probs=None, model_path='/content/drive/My Drive/f... | ============ ensembled method using embs ("middle concat")============
| Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
6) Bigdata ML ref:https://gdmarmerola.github.io/big-data-ml-training/ bigdata ML solu1: ensemble learning | !python -m pip install "dask[dataframe]"
!pip install 'fsspec>=0.3.3'
# libs to help us track memory via sampling
import numpy as np
import tracemalloc
from time import sleep
import matplotlib.pyplot as plt
# sampling time in seconds
SAMPLING_TIME = 0.001
class MemoryMonitor:
def __init__(self, close=True):
... | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
bigdata ML solu2: incremental learning | import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Dropout
tf.keras.backend.set_floatx('float64')
class KerasWrapper:
def __init__(self, model, feat_mean, feat_std):
self.model = model
self.feat_mean = feat_mean
self.feat_std = feat_st... | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
7) Extra & Experimental experiment: create ensemble classifier using individual classifiers' various outputI can extract various info from each individual classifier, including- probs (highest level features)- embeddings (intermediate level features)- encoding of txt_cols, img_cols, cnt_cols, cat_cols (lowest level f... | # load lm and clf based on 'skills' column
lm0, clf0 = load_fastai_text_classifier(df,
txt_col=txt_cols[0],
label_col=label_col,
model_path='/content/drive/My Drive/fastai_multimodal/model/',
... | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
module: Visualize doc similarity | #export
"""
import pandas as pd
import re
import seaborn as sns
import tensorflow as tf
"""
def normalize(data):
return (data - np.min(data)) / (np.max(data) - np.min(data))
## permutation test
def perm_test(x1, x2):
"""return the p-value of similarity bw x1 and x2"""
import math, random
from scipy import sta... | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
Experiment2: Error analysis | # classifier performance by confusion matrix
interp = ClassificationInterpretation.from_learner(multimodal_clf)
interp.plot_confusion_matrix(figsize=(8,8), dpi=60)
interp.print_classification_report()
# how to get prediction/inference on validation data? https://forums.fast.ai/t/unable-to-get-predictions-on-validation-... | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
module: Error Analysis | #export
def get_fastai_classifier_error_analysis(learner, df:pd.DataFrame, label_col:str, txt_col:str=None):
"""get the error analysis of a fastai text classifier on its validation dataset
Args:
learner:a trained fastai text classifier e.g. clf2
df:pd.DataFrame the whole dataframe learner was traine... | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
experimentI need to convert tab_learn1, tab_learn2 as End-to-End classifiers which take raw input and output preds, probs | import pickle
with open("embs_ls.pickle","wb") as f:
pickle.dump(embs_ls,f)
with open("embs_ls.pickle","rb") as f:
embs_ls = pickle.load(f)
with open("probs_ls.pickle","wb") as f:
pickle.dump(probs_ls,f)
with open("probs_ls.pickle", "rb") as f:
probs_ls = pickle.load(f)
#export
def split_idxs(df, train_size=.9... | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
module: text classifier for multiple text columnsThe end2end ensemble classifier combines multiple txt_clfs and tab_clfs:- inputs: df[txt_cols]- outputs: preds, probsdf[txt_col]=>`txt_clfs`=>emb_ls|probs_ls=>`tab_clfs`=>preds, probs**Why it matters**- ensemble of multiple txt classifiers combine signal from multiple t... | class End2End_Fastai_Texts_Classifier():
"""end to end fastai classifier for multiple txt_cols"""
def __init__(self,txt_clfs=None, lms=None, tab_clfs=None):
self.txt_clfs = txt_clfs # a list of fastai text classifiers
self.lms = lms # a list of fastai text language models
self.tab_clfs = tab_clfs # a li... | /usr/local/lib/python3.7/dist-packages/torch/autocast_mode.py:141: UserWarning: User provided device_type of 'cuda', but CUDA is not available. Disabling
warnings.warn('User provided device_type of \'cuda\', but CUDA is not available. Disabling')
/usr/local/lib/python3.7/dist-packages/torch/cuda/amp/grad_scaler.py:11... | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
experiment: extract fastai tabular embeddings | #dbck
path = untar_data(URLs.ADULT_SAMPLE)
df_ = pd.read_csv(path/'adult.csv')
print(df_.head())
label_col_ = "salary"
tab_learn = train_fastai_tabular_classifier(df=df_, label_col=label_col_, cnt_cols=None, cat_cols=None, lr=0.005, max_epochs=100, model_path='/content/drive/My Drive/fastai_multimodal/model/', model_na... | TabularModel(
(embeds): ModuleList(
(0): Embedding(74, 18)
(1): Embedding(117, 23)
(2): Embedding(90, 20)
(3): Embedding(17, 8)
(4): Embedding(93, 20)
(5): Embedding(8, 5)
(6): Embedding(43, 13)
(7): Embedding(16, 8)
(8): Embedding(6, 4)
(9): Embedding(7, 5)
(10): Embedding... | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
experiment: get_fastai_imgs_embsTo extract image embedding, check out this post- https://www.kaggle.com/code/abhikjha/fastai-pytorch-hooks-random-forest/notebookFastai---Tabular | # pytorch hook
class SaveFeatures():
features=None
def __init__(self, m):
self.hook = m.register_forward_hook(self.hook_fn)
self.features = None
def hook_fn(self, module, input, output):
out = output.detach().cpu().numpy()
if isinstance(self.features, type(None)):
... | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
0) create datasets | from pathlib import Path
nrows = 10**20
data_path='/content/drive/MyDrive/fastai_multimodal/datasets/' | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
dataset0 (cnt, cat)This example uses the[United States Census Income Dataset](https://archive.ics.uci.edu/ml/datasets/Census-Income+%28KDD%29)provided by the[UC Irvine Machine Learning Repository](https://archive.ics.uci.edu/ml/index.php).The task is binary classification to determine whether a person makes over 50K a... | # Column names.
CSV_HEADER = [
"age",
"class_of_worker",
"detailed_industry_recode",
"detailed_occupation_recode",
"education",
"wage_per_hour",
"enroll_in_edu_inst_last_wk",
"marital_stat",
"major_industry_code",
"major_occupation_code",
"race",
"hispanic_origin",
"s... | /content/drive/MyDrive/multimodal_text_benchmark
| Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
dataset1 (txt+img)Ref: https://keras.io/examples/nlp/multimodal_entailment/ | import pandas as pd
import os
import tensorflow as tf
image_base_path = tf.keras.utils.get_file(
"tweet_images",
"https://github.com/sayakpaul/Multimodal-Entailment-Baseline/releases/download/v1.0.0/tweet_images.tar.gz",
untar=True,
)
df = pd.read_csv("https://github.com/sayakpaul/Multimodal-Entailment-Bas... | Index(['id_1', 'text_1', 'image_1', 'id_2', 'text_2', 'image_2', 'label'], dtype='object')
| Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
dataset2 (cnt, cat, txt)The original task in Kaggle's PetFinder.my Adoption Prediction competition was to predict the speed at which a pet will be adopted (e.g. in the first week, the first month, the first three months, and so on). | dataset_url = 'http://storage.googleapis.com/download.tensorflow.org/data/petfinder-mini.zip'
csv_file = 'datasets/petfinder-mini/petfinder-mini.csv'
tf.keras.utils.get_file('petfinder_mini.zip', dataset_url,
extract=True, cache_dir='.')
df = pd.read_csv(csv_file, nrows=nrows)
label_col = 'Ado... | Downloading data from http://storage.googleapis.com/download.tensorflow.org/data/petfinder-mini.zip
1671168/1668792 [==============================] - 0s 0us/step
1679360/1668792 [==============================] - 0s 0us/step
| Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
dataset3 (tab+txt)Ref: https://github.com/sxjscience/automl_multimodal_benchmark | from pathlib import Path
import os
data_path = Path('../multimodal_text_benchmark/') #/drive/My Drive
os.chdir(data_path)
#dbck
!pwd
# Install the benchmarking suite
!pip install -U -e .
# view all available datasets
from auto_mm_bench.datasets import create_dataset, TEXT_BENCHMARK_ALIAS_MAPPING
datasets = list(TEXT_B... | _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
dataset4 (tab, txt) skippable meeting | df = pd.read_csv(data_path+'iu_2022_101_325.csv', index_col=0)
label_col = 'response_status'
df.tail()
list(df.columns)
| _____no_output_____ | Apache-2.0 | nbs/fastai_multimodal.ipynb | wjlgatech/fastai_multimodal |
1. Correctly splitting the dataset into train, validate, and holdout | # Import the model we are using
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
baseline_classifier_model = RandomForestClassifier()
# Train the baseline model on training data
baseline_classifier_model = baseline_classifier_model.fit(X_train, y_train) | _____no_output_____ | MIT | notebook/HW4.ipynb | GWU-CS2021/CSCI6364 |
2. Correctly training your model on the training dataset | # Use the forest's predict method on the holdout
predictions = baseline_classifier_model.predict(X_valid)
# Calculate the accuracy_score
accuracy_score(predictions, y_valid) | _____no_output_____ | MIT | notebook/HW4.ipynb | GWU-CS2021/CSCI6364 |
3. Correctly scoring your model on the validation dataset | # Use the forest's predict method on the holdout
predictions = baseline_classifier_model.predict(X_test)
# Calculate the accuracy_score
accuracy_score(predictions, y_test) | _____no_output_____ | MIT | notebook/HW4.ipynb | GWU-CS2021/CSCI6364 |
4. Correctly explaining if your model overfit or not (or state it is impossible to tell and why)- As the validation set and test set both yielded similar results, it does not appear that the model is overfitted. This is because it doesn't perform any worse when tested on data that it has not yet seen, so it has not “me... | from sklearn.model_selection import GridSearchCV
rfc=RandomForestClassifier(random_state=42)
param_grid = {
'n_estimators': [200, 500],
'max_features': ['auto', 'sqrt', 'log2'],
'max_depth' : [4,6,8],
'criterion' :['gini', 'entropy'],
'min_samples_split':[2,4]
}
CV_rfc = GridSearchCV(estimator=rfc... | _____no_output_____ | MIT | notebook/HW4.ipynb | GWU-CS2021/CSCI6364 |
5. Tune at least five parameters using GridSearchCV, with 2-4 values for each parameter | CV_rfc.best_params_
rfc1 = RandomForestClassifier(random_state=42, max_features='auto', n_estimators= 500, max_depth=6, min_samples_split=2, criterion='entropy')
rfc1.fit(X_train, y_train)
pred=rfc1.predict(X_valid)
accuracy_score(pred, y_valid) | _____no_output_____ | MIT | notebook/HW4.ipynb | GWU-CS2021/CSCI6364 |
1. Darwin's bibliographyCharles Darwin is one of the few universal figures of science. His most renowned work is without a doubt his "On the Origin of Species" published in 1859 which introduced the concept of natural selection. But Darwin wrote many other books on a wide range of topics, including geology, plants or ... | # Import library
import glob
# The books files are contained in this folder
folder = "datasets/"
# List all the .txt files and sort them alphabetically
files = glob.glob(folder+'*.txt')
# ... YOUR CODE FOR TASK 1 ...
files.sort() | _____no_output_____ | MIT | notebook.ipynb | MLVPRASAD/Book-Recommendations-from-Charles-Darwin |
2. Load the contents of each book into PythonAs a first step, we need to load the content of these books into Python and do some basic pre-processing to facilitate the downstream analyses. We call such a collection of texts a corpus. We will also store the titles for these books for future reference and print their re... | # Import libraries
import re, os
# Initialize the object that will contain the texts and titles
txts = []
titles = []
for n in files:
# Open each file
f = open(n, encoding='utf-8-sig')
# Remove all non-alpha-numeric characters
data = re.sub('[\W_]+', ' ', f.read())
# ... YOUR CODE FOR TASK 2 ...
... | _____no_output_____ | MIT | notebook.ipynb | MLVPRASAD/Book-Recommendations-from-Charles-Darwin |
3. Find "On the Origin of Species"For the next parts of this analysis, we will often check the results returned by our method for a given book. For consistency, we will refer to Darwin's most famous book: "On the Origin of Species." Let's find to which index this book is associated. | # Browse the list containing all the titles
for i in range(len(titles)):
# Store the index if the title is "OriginofSpecies"
# ... YOUR CODE FOR TASK 3 ...
if titles[i] == 'OriginofSpecies':
ori = i
break
ori
# Print the stored index
# ... YOUR CODE FOR TASK 3 ... | _____no_output_____ | MIT | notebook.ipynb | MLVPRASAD/Book-Recommendations-from-Charles-Darwin |
4. Tokenize the corpusAs a next step, we need to transform the corpus into a format that is easier to deal with for the downstream analyses. We will tokenize our corpus, i.e., transform each text into a list of the individual words (called tokens) it is made of. To check the output of our process, we will print the fi... | # Define a list of stop words
stoplist = set('for a of the and to in to be which some is at that we i who whom show via may my our might as well'.split())
# Convert the text to lower case
txts_lower_case = [txt.lower() for txt in txts]
# Transform the text into tokens
txts_split = [txt.split() for txt in txts_lowe... | _____no_output_____ | MIT | notebook.ipynb | MLVPRASAD/Book-Recommendations-from-Charles-Darwin |
5. Stemming of the tokenized corpusIf you have read On the Origin of Species, you will have noticed that Charles Darwin can use different words to refer to a similar concept. For example, the concept of selection can be described by words such as selection, selective, select or selects. This will dilute the weight giv... | import pickle
texts_stem = pickle.load(open('datasets/texts_stem.p', 'rb'))
# Print the 20 first stemmed tokens from the "On the Origin of Species" book
texts_stem[ori][: 20] | _____no_output_____ | MIT | notebook.ipynb | MLVPRASAD/Book-Recommendations-from-Charles-Darwin |
6. Building a bag-of-words modelNow that we have transformed the texts into stemmed tokens, we need to build models that will be useable by downstream algorithms.First, we need to will create a universe of all words contained in our corpus of Charles Darwin's books, which we call a dictionary. Then, using the stemmed ... |
from gensim import corpora
# Create a dictionary from the stemmed tokens
dictionary = corpora.Dictionary(texts_stem)
# Create a bag-of-words model for each book, using the previously generated dictionary
bows = [dictionary.doc2bow(txt) for txt in texts_stem]
# Print the first five elements of the On the Origin of s... | _____no_output_____ | MIT | notebook.ipynb | MLVPRASAD/Book-Recommendations-from-Charles-Darwin |
7. The most common words of a given bookThe results returned by the bag-of-words model is certainly easy to use for a computer but hard to interpret for a human. It is not straightforward to understand which stemmed tokens are present in a given book from Charles Darwin, and how many occurrences we can find.In order t... | import pandas as pd
# Convert the BoW model for "On the Origin of Species" into a DataFrame
df_bow_origin = pd.DataFrame(bows[ori])
# Add the column names to the DataFrame
df_bow_origin.columns = ['index', 'occurrences']
# Add a column containing the token corresponding to the dictionary index
df_bow_origin['token'] ... | _____no_output_____ | MIT | notebook.ipynb | MLVPRASAD/Book-Recommendations-from-Charles-Darwin |
8. Build a tf-idf modelIf it wasn't for the presence of the stem "speci", we would have a hard time to guess this BoW model comes from the On the Origin of Species book. The most recurring words are, apart from few exceptions, very common and unlikely to carry any information peculiar to the given book. We need to use... | # Load the gensim functions that will allow us to generate tf-idf models
from gensim.models import TfidfModel
# Generate the tf-idf model
model = TfidfModel(bows)
# Print the model for "On the Origin of Species"
model[bows[ori]] | _____no_output_____ | MIT | notebook.ipynb | MLVPRASAD/Book-Recommendations-from-Charles-Darwin |
9. The results of the tf-idf modelOnce again, the format of those results is hard to interpret for a human. Therefore, we will transform it into a more readable version and display the 10 most specific words for the "On the Origin of Species" book. | # Convert the tf-idf model for "On the Origin of Species" into a DataFrame
df_tfidf = ...
# Name the columns of the DataFrame id and score
# ... YOUR CODE FOR TASK 9 ...
# Add the tokens corresponding to the numerical indices for better readability
# ... YOUR CODE FOR TASK 9 ...
# Sort the DataFrame by descending tf... | _____no_output_____ | MIT | notebook.ipynb | MLVPRASAD/Book-Recommendations-from-Charles-Darwin |
10. Compute distance between textsThe results of the tf-idf algorithm now return stemmed tokens which are specific to each book. We can, for example, see that topics such as selection, breeding or domestication are defining "On the Origin of Species" (and yes, in this book, Charles Darwin talks quite a lot about pigeo... | # Load the library allowing similarity computations
from gensim import similarities
# Compute the similarity matrix (pairwise distance between all texts)
sims = ...
# Transform the resulting list into a dataframe
sim_df = ...
# Add the titles of the books as columns and index of the dataframe
# ... YOUR CODE FOR TAS... | _____no_output_____ | MIT | notebook.ipynb | MLVPRASAD/Book-Recommendations-from-Charles-Darwin |
11. The book most similar to "On the Origin of Species"We now have a matrix containing all the similarity measures between any pair of books from Charles Darwin! We can now use this matrix to quickly extract the information we need, i.e., the distance between one book and one or several others. As a first step, we wil... | # This is needed to display plots in a notebook
%matplotlib inline
# Import libraries
import matplotlib.pyplot as plt
# Select the column corresponding to "On the Origin of Species" and
v = ...
# Sort by ascending scores
v_sorted = ...
# Plot this data has a horizontal bar plot
# ... YOUR CODE FOR TASK 11 ...
# M... | _____no_output_____ | MIT | notebook.ipynb | MLVPRASAD/Book-Recommendations-from-Charles-Darwin |
12. Which books have similar content?This turns out to be extremely useful if we want to determine a given book's most similar work. For example, we have just seen that if you enjoyed "On the Origin of Species," you can read books discussing similar concepts such as "The Variation of Animals and Plants under Domestica... | # Import libraries
from scipy.cluster import hierarchy
# Compute the clusters from the similarity matrix,
# using the Ward variance minimization algorithm
Z = ...
# Display this result as a horizontal dendrogram
# ... YOUR CODE FOR TASK 12 ... | _____no_output_____ | MIT | notebook.ipynb | MLVPRASAD/Book-Recommendations-from-Charles-Darwin |
Logistic Regression | import numpy as np
from sklearn import datasets
from sklearn.utils import shuffle
random_state = np.random.RandomState(0)
iris = datasets.load_iris()
X = iris.data
y = iris.target
print y
import seaborn as sns
%matplotlib inline
iris_sns = sns.load_dataset("iris")
g = sns.PairGrid(iris_sns)
g.map_diag(sns.kdeplot)... | _____no_output_____ | MIT | exercises/04_logistic_regression.ipynb | milroy/Spark-Meetup |
Make it a binary classification problem by removing the first class | X, y = X[y != 0], y[y != 0]
n_samples, n_features = X.shape
y[y==1] = 0
y[y==2] = 1
print X.shape, y.shape
print set(y) | _____no_output_____ | MIT | exercises/04_logistic_regression.ipynb | milroy/Spark-Meetup |
Using `sklearn` | from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
clf = LogisticRegression()
clf.fit(X_train,y_train)
y_pred_test = clf.predict(X... | _____no_output_____ | MIT | exercises/04_logistic_regression.ipynb | milroy/Spark-Meetup |
Save to file | print y_train.shape
print y_train.reshape(y_train.shape[0],1).shape
print X_train.shape
cX = np.concatenate((y_train.reshape(80,1), X_train), axis=1)
cX.shape | _____no_output_____ | MIT | exercises/04_logistic_regression.ipynb | milroy/Spark-Meetup |
Write to file.... | np.savetxt('iris_train.csv', cX, delimiter=' ', fmt='%0.4f')
!head iris_train.csv
cX = np.concatenate((y_test.reshape(len(y_test),1), X_test), axis=1)
np.savetxt('iris_test.csv', cX, delimiter=' ', fmt='%0.4f') | _____no_output_____ | MIT | exercises/04_logistic_regression.ipynb | milroy/Spark-Meetup |
With `Spark` | import findspark
import os
findspark.init() # you need that before import pyspark.
import pyspark
sc = pyspark.SparkContext()
points = sc.textFile('../data/iris_train.csv', 18)
points.take(5)
from pyspark.mllib.classification import LogisticRegressionWithSGD
from pyspark.mllib.classification import LabeledPoint
pars... | _____no_output_____ | MIT | exercises/04_logistic_regression.ipynb | milroy/Spark-Meetup |
Any idea about the "Cleaned shuffle" messages?Hint: narrow versus wide transformations. | y = parsed_data.map(lambda x: x.label)
y_pred = parsed_data.map(lambda x: model.predict(x.features))
tmp = y.zip(y_pred)
tmp.take(5) | _____no_output_____ | MIT | exercises/04_logistic_regression.ipynb | milroy/Spark-Meetup |
Training accuracy | 1.0 - tmp.filter(lambda (y, p): y!=p).count()/float(parsed_data.count()) | _____no_output_____ | MIT | exercises/04_logistic_regression.ipynb | milroy/Spark-Meetup |
Test accuracy | points = sc.textFile('../data/iris_test.csv', 18)
parsed_data = points.map(lambda line: np.array([float(x) for x in line.split(' ')]))
parsed_data = parsed_data.map(lambda arr: LabeledPoint(arr[0],arr[1:]))
y_pred = parsed_data.map(lambda x: model.predict(x.features))
y = parsed_data.map(lambda x: x.label)
tmp = y.zip(... | _____no_output_____ | MIT | exercises/04_logistic_regression.ipynb | milroy/Spark-Meetup |
Python BasicsThis tutorial is a quick introduction to training and testing your model with Vowpal Wabbit using Python. We explore passing some data to Vowpal Wabbit to learn a model and get a prediction.For more advanced Vowpal Wabbit tutorials, including how to format data and understand results, see [Tutorials](http... | from vowpalwabbit import pyvw | _____no_output_____ | BSD-3-Clause | python/docs/source/tutorials/python_first_steps.ipynb | jonpsy/vowpal_wabbit |
Next, we create an instance of Vowpal Wabbit, and pass the `quiet=True` option to avoid diagnostic information output to `stdout` location: | model = pyvw.vw(quiet=True) | _____no_output_____ | BSD-3-Clause | python/docs/source/tutorials/python_first_steps.ipynb | jonpsy/vowpal_wabbit |
Training scenario and datasetFor this tutorial scenario, we want Vowpal Wabbit to help us predict whether or not our house will require a new roof in the next 10 years.To create some examples, we use the Vowpal Wabbit text format and then learn on them: | train_examples = [
"0 | price:.23 sqft:.25 age:.05 2006",
"1 | price:.18 sqft:.15 age:.35 1976",
"0 | price:.53 sqft:.32 age:.87 1924",
]
for example in train_examples:
model.learn(example) | _____no_output_____ | BSD-3-Clause | python/docs/source/tutorials/python_first_steps.ipynb | jonpsy/vowpal_wabbit |
> **Note:** For more details on Vowpal Wabbit input format and feature hashing techniques see the [Linear Regression Tutorial](cmd_linear_regression.md).Now, we create a `test_example` to use for prediction: | test_example = "| price:.46 sqft:.4 age:.10 1924"
prediction = model.predict(test_example)
print(prediction) | _____no_output_____ | BSD-3-Clause | python/docs/source/tutorials/python_first_steps.ipynb | jonpsy/vowpal_wabbit |
4.3 컬러 이미지를 분류하는 CNN 구현CNN을 이용해 사진을 분류하는 방법을 다룹니다. 4.3.1 분류 CNN 패키지 임포트 1. 필요한 패키지들을 임포트합니다. | from sklearn import model_selection, metrics
from sklearn.preprocessing import MinMaxScaler | _____no_output_____ | MIT | nb_ex4_2_cnn_cifar10_cl.ipynb | jskDr/keraspp_2022 |
- 유용한 기능을 제공하는 다른 파이썬 패키지도 임포트합니다. | import numpy as np
import matplotlib.pyplot as plt
import os | _____no_output_____ | MIT | nb_ex4_2_cnn_cifar10_cl.ipynb | jskDr/keraspp_2022 |
- 케라스 모델링을 위한 서브패키지들을 불러옵니다. | from keras import backend as K
from keras.utils import np_utils
from keras.models import Model
from keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense, Dropout | _____no_output_____ | MIT | nb_ex4_2_cnn_cifar10_cl.ipynb | jskDr/keraspp_2022 |
- 케라스를 편리하게 사용하기 위해 여기서 만든 2가지 모듈을 불러옵니다. | from keraspp import skeras
from keraspp import sfile | _____no_output_____ | MIT | nb_ex4_2_cnn_cifar10_cl.ipynb | jskDr/keraspp_2022 |
4.3.2 분류 CNN 모델링 2. 분류 CNN 모델링을 만듭니다. | # 2. 분류 CNN 모델링
class CNN(Model):
def __init__(self, nb_classes):
super(CNN,self).__init__()
self.nb_classes = nb_classes
self.conv2D_A = Conv2D(32, kernel_size=(3, 3), activation='relu')
self.conv2D_B = Conv2D(64, (3, 3), activation='relu')
self.maxPooling2D_A = M... | _____no_output_____ | MIT | nb_ex4_2_cnn_cifar10_cl.ipynb | jskDr/keraspp_2022 |
4.3.3 분류 CNN을 위한 데이터 준비 3. 주어진 데이터를 해당 머신러닝에 사용하기 적합하도록 조정하는 기능을 하는 DataSet 클래스를 만듭니다. | # 3. 분류 CNN을 위한 데이터 준비
class DataSet:
def __init__(self, X, y, nb_classes, scaling=True,
test_size=0.2, random_state=0):
self.X = X
self.add_channels()
X = self.X
# the data, shuffled and split between train and test sets
X_train, X_test, y_train, y... | Epoch 1/2
313/313 [==============================] - 47s 150ms/step - loss: 2.3076 - accuracy: 0.1087 - val_loss: 2.2870 - val_accuracy: 0.1377
Epoch 2/2
313/313 [==============================] - 49s 158ms/step - loss: 2.2918 - accuracy: 0.1227 - val_loss: 2.2746 - val_accuracy: 0.1754
| MIT | nb_ex4_2_cnn_cifar10_cl.ipynb | jskDr/keraspp_2022 |
4.3.4 분류 CNN의 학습 및 성능 평가를 위한 머신 클래스 4. 학습 및 성능 평가를 쉽게 수행할 수 있는 상위 개념 클래스인 Machine을 만듭니다. | # 4. 분류 CNN의 학습 및 성능 평가를 위한 머신 클래스
class Machine():
def __init__(self, X, y, nb_classes=2, fig=True):
self.nb_classes = nb_classes
self.set_data(X, y)
self.set_model()
self.fig = fig
def set_data(self, X, y):
nb_classes = self.nb_classes
self.data = DataSet(X, y,... | _____no_output_____ | MIT | nb_ex4_2_cnn_cifar10_cl.ipynb | jskDr/keraspp_2022 |
--- 4.3.5 분류 CNN을 처리하는 머쉰의 전체 코드 | # File - keraspp/aicnn.py
# 1. 분류 CNN 패키지 임포트
from sklearn import model_selection, metrics
from sklearn.preprocessing import MinMaxScaler
import numpy as np
import matplotlib.pyplot as plt
import os
from keras import backend as K
from keras.utils import np_utils
from keras.models import Model
from keras.layers impor... | _____no_output_____ | MIT | nb_ex4_2_cnn_cifar10_cl.ipynb | jskDr/keraspp_2022 |
4.3.6 분류 CNN의 학습 및 성능 평가 수행 5. 분류 CNN을 위한 머쉰에 기반하여 컬러 이미지를 분류합니다. | # 5. 분류 CNN의 학습 및 성능 평가 수행
from keras import datasets
import keras
assert keras.backend.image_data_format() == 'channels_last'
# from keraspp import aicnn
class MyMachine(Machine):
def __init__(self):
(X, y), (x_test, y_test) = datasets.cifar10.load_data()
super(MyMachine,self).__init__(X, y, nb_cl... | _____no_output_____ | MIT | nb_ex4_2_cnn_cifar10_cl.ipynb | jskDr/keraspp_2022 |
--- 4.3.7 분류 CNN의 수행을 위한 전체 코드 | # File - ex4_2_cnn_ficar10_cl-cpu.py
# set to use CPU
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
# 5. 분류 CNN의 학습 및 성능 평가 수행
from keras import datasets
import keras
assert keras.backend.image_data_format() == 'channels_last'
from keraspp import aicnn
# from keraspp import aicnn
class MyMachine(aicnn.Machine)... | (40000, 32, 32, 3) (40000, 1)
X_train shape: (40000, 32, 32, 3)
40000 train samples
10000 test samples
data.input_shape (32, 32, 3)
| MIT | nb_ex4_2_cnn_cifar10_cl.ipynb | jskDr/keraspp_2022 |
Compute descriptor statistics on datasetThis notebook computes the staistics of the descriptor on a given dataset | import numpy as np
import time
import os
import matplotlib.pyplot as plt
import dense_correspondence_manipulation.utils.utils as utils
utils.add_dense_correspondence_to_python_path()
from torchvision import transforms
import torch
from dense_correspondence.dataset.spartan_dataset_masked import SpartanDataset
from de... | _____no_output_____ | BSD-3-Clause | dense_correspondence/evaluation/compute_descriptor_dataset_statistics.ipynb | jan-tgk/pytorch-dense-correspondence |
T1218.011 - Signed Binary Proxy Execution: Rundll32Adversaries may abuse rundll32.exe to proxy execution of malicious code. Using rundll32.exe, vice executing directly (i.e. [Shared Modules](https://attack.mitre.org/techniques/T1129)), may avoid triggering security tools that may not monitor execution of the rundll32.... | #Import the Module before running the tests.
# Checkout Jupyter Notebook at https://github.com/cyb3rbuff/TheAtomicPlaybook to run PS scripts.
Import-Module /Users/0x6c/AtomicRedTeam/atomics/invoke-atomicredteam/Invoke-AtomicRedTeam.psd1 - Force | _____no_output_____ | MIT | playbook/tactics/defense-evasion/T1218.011.ipynb | haresudhan/The-AtomicPlaybook |
Atomic Test 1 - Rundll32 execute JavaScript Remote Payload With GetObjectTest execution of a remote script using rundll32.exe. Upon execution notepad.exe will be opened.**Supported Platforms:** windows Attack Commands: Run with `command_prompt````command_promptrundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";d... | Invoke-AtomicTest T1218.011 -TestNumbers 1 | _____no_output_____ | MIT | playbook/tactics/defense-evasion/T1218.011.ipynb | haresudhan/The-AtomicPlaybook |
Atomic Test 2 - Rundll32 execute VBscript commandTest execution of a command using rundll32.exe and VBscript in a similar manner to the JavaScript test.Technique documented by Hexacorn- http://www.hexacorn.com/blog/2019/10/29/rundll32-with-a-vbscript-protocol/Upon execution calc.exe will be launched**Supported Platfor... | Invoke-AtomicTest T1218.011 -TestNumbers 2 | _____no_output_____ | MIT | playbook/tactics/defense-evasion/T1218.011.ipynb | haresudhan/The-AtomicPlaybook |
Atomic Test 3 - Rundll32 advpack.dll ExecutionTest execution of a command using rundll32.exe with advpack.dll.Reference: https://github.com/LOLBAS-Project/LOLBAS/blob/master/yml/OSLibraries/Advpack.ymlUpon execution calc.exe will be launched**Supported Platforms:** windows Dependencies: Run with `powershell`! Descrip... | Invoke-AtomicTest T1218.011 -TestNumbers 3 -GetPreReqs | _____no_output_____ | MIT | playbook/tactics/defense-evasion/T1218.011.ipynb | haresudhan/The-AtomicPlaybook |
Attack Commands: Run with `command_prompt````command_promptrundll32.exe advpack.dll,LaunchINFSection PathToAtomicsFolder\T1218.011\src\T1218.011.inf,DefaultInstall_SingleUser,1,``` | Invoke-AtomicTest T1218.011 -TestNumbers 3 | _____no_output_____ | MIT | playbook/tactics/defense-evasion/T1218.011.ipynb | haresudhan/The-AtomicPlaybook |
Atomic Test 4 - Rundll32 ieadvpack.dll ExecutionTest execution of a command using rundll32.exe with ieadvpack.dll.Upon execution calc.exe will be launchedReference: https://github.com/LOLBAS-Project/LOLBAS/blob/master/yml/OSLibraries/Ieadvpack.yml**Supported Platforms:** windows Dependencies: Run with `powershell`! D... | Invoke-AtomicTest T1218.011 -TestNumbers 4 -GetPreReqs | _____no_output_____ | MIT | playbook/tactics/defense-evasion/T1218.011.ipynb | haresudhan/The-AtomicPlaybook |
Attack Commands: Run with `command_prompt````command_promptrundll32.exe ieadvpack.dll,LaunchINFSection PathToAtomicsFolder\T1218.011\src\T1218.011.inf,DefaultInstall_SingleUser,1,``` | Invoke-AtomicTest T1218.011 -TestNumbers 4 | _____no_output_____ | MIT | playbook/tactics/defense-evasion/T1218.011.ipynb | haresudhan/The-AtomicPlaybook |
Atomic Test 5 - Rundll32 syssetup.dll ExecutionTest execution of a command using rundll32.exe with syssetup.dll. Upon execution, a window saying "installation failed" will be openedReference: https://github.com/LOLBAS-Project/LOLBAS/blob/master/yml/OSLibraries/Syssetup.yml**Supported Platforms:** windows Dependencies:... | Invoke-AtomicTest T1218.011 -TestNumbers 5 -GetPreReqs | _____no_output_____ | MIT | playbook/tactics/defense-evasion/T1218.011.ipynb | haresudhan/The-AtomicPlaybook |
Attack Commands: Run with `command_prompt````command_promptrundll32.exe syssetup.dll,SetupInfObjectInstallAction DefaultInstall 128 .\PathToAtomicsFolder\T1218.011\src\T1218.011_DefaultInstall.inf``` | Invoke-AtomicTest T1218.011 -TestNumbers 5 | _____no_output_____ | MIT | playbook/tactics/defense-evasion/T1218.011.ipynb | haresudhan/The-AtomicPlaybook |
Atomic Test 6 - Rundll32 setupapi.dll ExecutionTest execution of a command using rundll32.exe with setupapi.dll. Upon execution, a windows saying "installation failed" will be openedReference: https://github.com/LOLBAS-Project/LOLBAS/blob/master/yml/OSLibraries/Setupapi.yml**Supported Platforms:** windows Dependencies... | Invoke-AtomicTest T1218.011 -TestNumbers 6 -GetPreReqs | _____no_output_____ | MIT | playbook/tactics/defense-evasion/T1218.011.ipynb | haresudhan/The-AtomicPlaybook |
Attack Commands: Run with `command_prompt````command_promptrundll32.exe setupapi.dll,InstallHinfSection DefaultInstall 128 .\PathToAtomicsFolder\T1218.011\src\T1218.011_DefaultInstall.inf``` | Invoke-AtomicTest T1218.011 -TestNumbers 6 | _____no_output_____ | MIT | playbook/tactics/defense-evasion/T1218.011.ipynb | haresudhan/The-AtomicPlaybook |
Importamos la libreria RE | import re | _____no_output_____ | MIT | Materias/ProcesamientoLenguaje/Clases/S01_003_RE.ipynb | jorgeo80/UP_MDC |
Para hacer pruebas y experimentos podemos utilizar el texto de la dirección: https://raw.githubusercontent.com/apimentelaUP/recursos/master/M%C3%A9xico_texto.txt | import requests
url = 'https://raw.githubusercontent.com/apimentelaUP/recursos/master/M%C3%A9xico_texto.txt'
page = requests.get(url)
texto = page.text
texto | _____no_output_____ | MIT | Materias/ProcesamientoLenguaje/Clases/S01_003_RE.ipynb | jorgeo80/UP_MDC |
Recordemos que las ER son texto, y siempre y cuando no se incluya ninguno de los caracteres especiales, el texto formará una expresión regular que va a coincidir consigo mismo, asi se forman las ER mas simples.Para declarar una expresión regular, vamos a usar la función `re.compile()` | expresion_mexico = re.compile(r"México") | _____no_output_____ | MIT | Materias/ProcesamientoLenguaje/Clases/S01_003_RE.ipynb | jorgeo80/UP_MDC |
OJO: Presten atención a esa `'r'` justo antes de abrir las comillas del texto de la expresión regular, son importantes.Esa `'r'` le indica a Python que ese texto va a contener caracteres especiales de expresión regular. Python tiene caracteres especiales propios, de los cuáles varios coinciden con los de ER. Por lo tan... | busqueda = expresion_mexico.search(texto)
print(busqueda.group(0)) | México
| MIT | Materias/ProcesamientoLenguaje/Clases/S01_003_RE.ipynb | jorgeo80/UP_MDC |
Y para sorpresa de nadie, lo que obtenemos es el mismo texto que queríamos buscar en primer lugar. Pero este ejemplo es importante para mostrar cómo se obtiene el resultado.Primero, la función `er.search()` recibe el texto donde se va a buscar la expresión regular compilada y devuelve un resultado de esa búsqueda.Para ... | busqueda = expresion_mexico.finditer(texto)
for resultado in busqueda:
print(resultado.group(0)) | México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
México
Méxic... | MIT | Materias/ProcesamientoLenguaje/Clases/S01_003_RE.ipynb | jorgeo80/UP_MDC |
El resultado será una lista con todas las apariciones de la palabra "México" en el texto. Cada uno de los resultados que regresa el iterador se comporta igual que el resultado de la función `er.search()` Punto (`.`) Ahora podemos comenzar con los símbolos especiales de las expresiones regulares, comenzaremos por el pu... | expresion_punto = re.compile(r".")
busqueda = expresion_punto.finditer(texto)
contador = 0
for resultado in busqueda:
print(resultado.group(0))
contador += 1
if contador >= 100 :
break | <
d
o
c
i
d
=
"
1
8
3
0
"
u
r
l
=
"
h
t
t
p
s
:
/
/
e
s
.
w
i
k
i
p
e
d
i
a
.
o
r
g
/
w
i
k
i
?
c
u
r
i
d
=
1
8
3
0
"
t
i
t
l
e
=
"
M
é
x
i
c
o
"
>
M
é
x
i
c
o
M
é
x
i
c
o
(
)
,
o
f
i
c
i
a
| MIT | Materias/ProcesamientoLenguaje/Clases/S01_003_RE.ipynb | jorgeo80/UP_MDC |
El punto es capaz de coincidir con cualquier caracter, el que sea, en el código puse un límite de 100 resultados para cortar la salida, de otra manera tendrán todo el texto, un caracter a la vez.Usarlo por sí mismo no tiene mucho sentido, pero tanto letras como símbolos se pueden usar en conjunto dentro de las expresio... | expresion_punto = re.compile(r"M..ic.")
busqueda = expresion_punto.finditer(texto)
for resultado in busqueda:
print(resultado.group(0)) | México
México
México
Mexica
México
México
México
México
México
México
México
México
México
Mexica
México
Mexica
Mejica
Mexica
Mexica
Mexica
Mexica
Mexica
Mexica
Mexica
México
México
México
México
México
México
México
México
México
México
México
México
Mexica
México
México
México
México
México
México
México
México
Méxic... | MIT | Materias/ProcesamientoLenguaje/Clases/S01_003_RE.ipynb | jorgeo80/UP_MDC |
Esta búsqueda nos dará direrentes coincidencias similares a "México", por ejemplo con y sin acento, escrito con 'j' o con una diferente terminación. Repetidores En segundo lugar, veamos los símbolos repetidores: `+ *` . Ambos símbolos se usan DESPUES de UN caracter que se quiera repteir: `*` cualquier cantidad de vec... | expresion_mas = re.compile(r".0+")
expresion_asterisco = re.compile(r".0*")
busqueda_mas = expresion_mas.finditer(texto)
busqueda_asterisco = expresion_asterisco.finditer(texto)
print("########## RESULTADOS MAS ########## ")
for resultado in busqueda_mas:
print(resultado.group(0))
print("########## RESULTADOS ASTE... | ########## RESULTADOS MAS ##########
30
30
30
20
000
300
10
0
10
000
30
000
9000
000
8000
1000
10
500
500
500
200
200
900
900
900
300
20
300
40
300
80
10
20
90
90
10
20
20
40
50
60
70
2000
200
100
000
20
10
20
200
20
20
20
20
500
10
70
20
70
80
2000
200
20
80
50
50
20
20
20
0
30
10
90
40
20
50
30
50
40
10
20
10... | MIT | Materias/ProcesamientoLenguaje/Clases/S01_003_RE.ipynb | jorgeo80/UP_MDC |
Nuevamente le puse un límite a la salida de la expresión regular, o de lo contrario tendremos el texto completo un caracter a la vez (casi). ¿Por qué? porque el punto coincide con cualquier cosa, y si no tiene un cero a su derecha, no importa (por el asterisco), aún así va a coincidir. Si, por el contrario, si tiene ce... | # Se va a buscar mínimo 2 nueves, si se coloca un número después de la coma es un rango
# y sin coma es una cantidad fija de repeticiones
expresion_llaves = re.compile(r".9{2,}.")
busqueda = expresion_llaves.finditer(texto)
for resultado in busqueda:
print(resultado.group(0)) | 1994
1994
1994
1997
1994
1994
1995
990
1990
1995
1990
1993
1992
1994
1999;
1993
1990
1992
1992
1990
1994
1996
1992
1994
1992
1996
| MIT | Materias/ProcesamientoLenguaje/Clases/S01_003_RE.ipynb | jorgeo80/UP_MDC |
Aquí también vale la pena hablar de otro símbolo similar: `?`. No es exactamente un repetidor ya que solo acepta 0 o 1 aparición, es decir, hace que un caracter sea opcional. | expresion_interrogacion = re.compile(r"años?")
busqueda = expresion_interrogacion.finditer(texto)
for resultado in busqueda:
print(resultado.group(0)) | año
años
años
años
año
año
año
año
año
año
años
año
año
año
año
año
año
año
años
año
año
año
año
año
año
año
años
año
año
año
años
años
año
año
año
año
años
años
años
año
año
años
años
años
año
año
año
años
año
años
año
año
año
año
año
años
años
años
años
año
año
año
años
año
años
años
año
año
año
año
año
año
año
año
a... | MIT | Materias/ProcesamientoLenguaje/Clases/S01_003_RE.ipynb | jorgeo80/UP_MDC |
Posición Las expresiones regulares también tienen símbolos especiales para indicar posición, en particular podemos hablar del inicio y final del texto. La versión, en expresión regular, de las funciones `s.startswith()` y `s.endswith()`. Los símbolos son `^` y `$` respectivamente | # Es mejor manejar el texto segmentado para este experimento
segmentado = texto.split("\n")
expresion_inicio = re.compile(r"^......")
expresion_fin = re.compile(r"......$")
for segmento in segmentado:
resultado_inicio = expresion_inicio.search(segmento)
resultado_fin = expresion_fin.search(segmento)
if resulta... | <doc i
xico">
############
México
México
############
México
eral).
############
El ter
con .
############
México
mundo.
############
La pre
ítico.
############
Según
undo.
############
En tér
mundo,
############
México
micas.
############
El pri
ulos.
############
Los do
ncia.
############
Desde
común.
#########... | MIT | Materias/ProcesamientoLenguaje/Clases/S01_003_RE.ipynb | jorgeo80/UP_MDC |
Si no segmentamos el texto, solamente vamos a obtener los primeros y últimos seis caracteres de todo el texto, de esta manera obtenermos los primeros y últimos de cada línea. Miscelaneos Lamentablemente, los símbolos que quedan tienen todos efectos particulares y ya no los pude agrupar más. Pero vamos a empezar con un... | expresion_sinInterrogacion = re.compile(r"\(.*\)")
expresion_conInterrogacion = re.compile(r"\(.*?\)")
busqueda_sinInterrogacion = expresion_sinInterrogacion.finditer(texto)
busqueda_conInterrogacion = expresion_conInterrogacion.finditer(texto)
for resultado in busqueda_sinInterrogacion:
print(resultado.group(0))
... | (), oficialmente Estados Unidos Mexicanos, es un país soberano ubicado en la parte meridional de América del Norte con capital en la Ciudad de México. Políticamente es una república representativa, democrática, federal y laica, compuesta por 32 entidades federativas (31 estados y la capital federal)
(principalmente el ... | MIT | Materias/ProcesamientoLenguaje/Clases/S01_003_RE.ipynb | jorgeo80/UP_MDC |
Matamos dos pajaros de un tiro, podemos analizar la diferencia entre una expresión codiciosa y una reacia; y además, observamos un uso de la diagonal invertida (`\`): Cancelar el efecto de los símbolos especiales. ( ) Los paréntesis tienen exactamente el efecto que uno podría esperar: agrupar. Eso quiere decir que se ... | expresion_parentesis = re.compile(r"(el)?(los)? país(es)?")
busqueda = expresion_parentesis.finditer(texto)
for resultado in busqueda:
print(resultado.group(0)) | país
el país
el país
país
el país
el país
país
el país
los países
países
país
el país
el país
el país
el país
país
el país
el país
el país
país
el país
el país
país
el país
el país
el país
el país
el país
el país
país
el país
el país
el país
país
país
país
el país
países
el país
el país
país
países
el pa... | MIT | Materias/ProcesamientoLenguaje/Clases/S01_003_RE.ipynb | jorgeo80/UP_MDC |
| Podemos ver que el código anterior es mas o menos equivalente a buscar "el país" o "los países" o incluso solo "países". Pero con esa construcción, en realidad también se podrían encontrar cosas como "ellos países" si es que algo así estuviera en el texto.Afortunadamente las expresiones regulares cuentan con instruc... | expresion_barra = re.compile(r"(el|los) país(es)?")
busqueda = expresion_barra.finditer(texto)
for resultado in busqueda:
print(resultado.group(0)) | el país
el país
el país
el país
el país
los países
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el país
el pa... | MIT | Materias/ProcesamientoLenguaje/Clases/S01_003_RE.ipynb | jorgeo80/UP_MDC |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.