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 |
|---|---|---|---|---|---|
Load candidates and training marginals | from snorkel.models import candidate_subclass
from snorkel.contrib.models.text import RawText
Tweet = candidate_subclass('Tweet', ['tweet'], cardinality=5)
train_tweets = session.query(Tweet).filter(Tweet.split == 0).order_by(Tweet.id).all()
len(train_tweets)
from snorkel.annotations import load_marginals
train_margina... | _____no_output_____ | Apache-2.0 | test/learning/tensorflow/test_TF_notebook.ipynb | AndyLc/snorkel |
Train `LogisticRegression` | # Simple unigram featurizer
def get_unigram_tweet_features(c):
for w in c.tweet.text.split():
yield w, 1
# Construct feature matrix
from snorkel.annotations import FeatureAnnotator
featurizer = FeatureAnnotator(f=get_unigram_tweet_features)
%time F_train = featurizer.apply(split=0)
F_train
%time F_test = ... | _____no_output_____ | Apache-2.0 | test/learning/tensorflow/test_TF_notebook.ipynb | AndyLc/snorkel |
Train `SparseLogisticRegression`Note: Testing doesn't currently work with `LogisticRegression` above, but no real reason to use that over this... | from snorkel.learning.tensorflow import SparseLogisticRegression
model = SparseLogisticRegression(cardinality=Tweet.cardinality)
model.train(F_train, train_marginals, n_epochs=50, print_freq=10)
import numpy as np
test_labels = np.load('crowdsourcing_test_labels.npy')
acc = model.score(F_test, test_labels)
print(acc)
... | _____no_output_____ | Apache-2.0 | test/learning/tensorflow/test_TF_notebook.ipynb | AndyLc/snorkel |
Train basic LSTMWith dev set scoring during execution (note we use test set here to be simple) | from snorkel.learning.tensorflow import TextRNN
test_tweets = session.query(Tweet).filter(Tweet.split == 1).order_by(Tweet.id).all()
train_kwargs = {
'dim': 100,
'lr': 0.001,
'n_epochs': 25,
'dropout': 0.2,
'print_freq': 5
}
lstm = TextRNN(seed=123, cardinality=Tweet.cardinality... | _____no_output_____ | Apache-2.0 | test/learning/tensorflow/test_TF_notebook.ipynb | AndyLc/snorkel |
Run `GridSearch` | from snorkel.learning.utils import GridSearch
# Searching over learning rate
param_ranges = {'lr': [1e-3, 1e-4], 'dim': [50, 100]}
model_class_params = {'seed' : 123, 'cardinality': Tweet.cardinality}
model_hyperparams = {
'dim': 100,
'n_epochs': 20,
'dropout': 0.1,
'print_freq': 10
}
searc... | _____no_output_____ | Apache-2.0 | test/learning/tensorflow/test_TF_notebook.ipynb | AndyLc/snorkel |
Reload saved model outside of `GridSearch` | lstm = TextRNN(seed=123, cardinality=Tweet.cardinality)
lstm.load('TextRNN_best', save_dir='checkpoints/grid_search')
acc = lstm.score(test_tweets, test_labels)
print(acc)
assert acc > 0.60 | _____no_output_____ | Apache-2.0 | test/learning/tensorflow/test_TF_notebook.ipynb | AndyLc/snorkel |
Reload a model with different structure | lstm.load('TextRNN_0', save_dir='checkpoints/grid_search')
acc = lstm.score(test_tweets, test_labels)
print(acc)
assert acc < 0.60 | _____no_output_____ | Apache-2.0 | test/learning/tensorflow/test_TF_notebook.ipynb | AndyLc/snorkel |
Testing `GenerativeModel` Testing `GridSearch` on crowdsourcing data | from snorkel.annotations import load_label_matrix
import numpy as np
L_train = load_label_matrix(session, split=0)
train_labels = np.load('crowdsourcing_train_labels.npy')
from snorkel.learning import GenerativeModel
# Searching over learning rate
searcher = GridSearch(GenerativeModel, {'epochs': [0, 10, 30]}, L_trai... | _____no_output_____ | Apache-2.0 | test/learning/tensorflow/test_TF_notebook.ipynb | AndyLc/snorkel |
Analyze population data from https://covidtracking.com**Note:** This is a Jupyter notebook which is also available as its executable export as a Python 3 script (therefore with automatically generated comments). Sept 29,2021: Obsolete dataOur source https://covidtracking.com/data/api says:- `As of March 7, 2021 we ar... | import sys,os
addPath= [os.path.abspath("../venv/lib/python3.9/site-packages/"),
os.path.abspath("../source")]
addPath.extend(sys.path)
sys.path = addPath
# Sys import
import sys, os, re
# Common imports
import math
import numpy as NP
import numpy.random as RAND
import scipy.stats as ST... | _____no_output_____ | MIT | JupySessions/USA-covidtracking-com.ipynb | AlainLich/COVID-Data |
Import my own modulesThe next cell attempts to give user some information if things improperly setup.Intended to work both in Jupyter and when executing the Python file directly. | if not get_ipython() is None and os.path.abspath("../source/") not in sys.path:
sys.path.append(os.path.abspath("../source/"))
try:
from lib.utilities import *
from lib.figureHelpers import *
from lib.DataMgrJSON import *
from lib.DataMgr import *
from lib.pandaUtils import *
exce... | _____no_output_____ | MIT | JupySessions/USA-covidtracking-com.ipynb | AlainLich/COVID-Data |
Check environmentIt is expected that:- your working directory is named `JupySessions`, - that it has subdirectories - `images/*` where generated images may be stored to avoid overcrowding. - At the same level as your working dir there should be directories - `../data` for storing input data and - `../source` ... | checkSetup(chap="Chap04")
ImgMgr = ImageMgr(chapdir="Chap04") | _____no_output_____ | MIT | JupySessions/USA-covidtracking-com.ipynb | AlainLich/COVID-Data |
Load Data Functions Load CSV and XLSX data from remote The `dataFileVMgr` will manage a cache of data files in `../dataUSCovidTrack`.We check what is in the cache/data directory; for each file, we identify the latest version, and list this below to make sure. Files of interest are documented in `.filespecs.json`Cons... | dataFileVMgr = manageAndCacheFilesJSONHandwritten("../dataUSCovidTrack")
dataFileVMgr.getRemoteInfo()
dataFileVMgr.updatePrepare()
dataFileVMgr.cacheUpdate()
print("Most recent versions of files in data directory:")
for f in dataFileVMgr.listMostRecent() :
print(f"\t{f}")
last = lambda x: dataFileVMgr.getRecentVers... | _____no_output_____ | MIT | JupySessions/USA-covidtracking-com.ipynb | AlainLich/COVID-Data |
This ensures we load the most recent version, so that it is not required to update the list below. The timestamps shown in the following sequence will be update by the call to `getRecentVersion`. | USStatesDailyCSV = last('CTStatesDaily.csv' )
USStatesInfoCSV = last('CTStatesInfo.csv')
USDailyCSV = last('CTUSDaily.csv')
USAPopChangeCSV = last('USACensusPopchange.csv')
USAPopChangeRankCSV = last('USACensusPopchangeRanks.csv') | _____no_output_____ | MIT | JupySessions/USA-covidtracking-com.ipynb | AlainLich/COVID-Data |
Now load the stuff | ad = lambda x: "../dataUSCovidTrack/"+x
data_USStatesDaily = read_csvPandas(ad(USStatesDailyCSV) , error_bad_lines=False, sep="," )
data_USStatesInfo = read_csvPandas(ad(USStatesInfoCSV), error_bad_lines=False, sep="," )
data_USDaily = read_csvPandas(ad(USDailyCSV), error_bad_lines=False, sep... | _____no_output_____ | MIT | JupySessions/USA-covidtracking-com.ipynb | AlainLich/COVID-Data |
Show the shape of the loaded data: | def showBasics(data,dataName):
print(f"{dataName:24}\thas shape {data.shape}")
dataListDescr = ( (data_USStatesDaily, "data_USStatesDaily"),
(data_USStatesInfo, "data_USStatesInfo"),
(data_USDaily , "data_USDaily"),
(data_USAPopChange, "data_USAPopChange... | _____no_output_____ | MIT | JupySessions/USA-covidtracking-com.ipynb | AlainLich/COVID-Data |
Get demographics informationThe metadata is in `../dataUSCovidTrack/*.pdf`. We need to preprocess the demographics information for ease of use below. Notice that column `STATE` features state's **FIPS codes**. | demogrCols=("SUMLEV","STATE","NAME","POPESTIMATE2019" )
demogrX = data_USAPopChange.loc[:,demogrCols]
demogrX["SUMLEV"]== 40
demogr = demogrX[demogrX["SUMLEV"]== 40 ].copy()
dtCols = ('date','fips', 'state',
'positive', 'negative',
'hospitalizedCurrently', 'hospitalizedCumulative',
'in... | _____no_output_____ | MIT | JupySessions/USA-covidtracking-com.ipynb | AlainLich/COVID-Data |
Now, the figure making process is generalized into this class, since we plan to emit multiple figures. First attempt, just get the first! | plotCols=("recovered","death","hospitalized")
psFig = appUSA.perStateFigure(dateStart)
psFig.getDemographics(data_USAPopChange)
psFig.initPainter(subnodeSpec=15, maxCol=3)
psFig.mkImage(dtg,plotCols)
ImgMgr.save_fig("FIG001")
print(f"Had issues with state encodings:{psFig.abbrevIssueList}") | _____no_output_____ | MIT | JupySessions/USA-covidtracking-com.ipynb | AlainLich/COVID-Data |
Now select States according to multiple criteria Start with most populated states | tble = psFig.getPopStateTble(dtg)
mostPopulated = tble.sort_values(by=["pop"], ascending=False,).iloc[:15,0].values
psFig2 = appUSA.perStateSelected(dateStart,mostPopulated)
psFig2.getDemographics(data_USAPopChange)
psFig2.initPainter(subnodeSpec=15, maxCol=3)
psFig2.mkImage(dtg,plotCols)
ImgMgr.save_fig("FIG002")
pri... | _____no_output_____ | MIT | JupySessions/USA-covidtracking-com.ipynb | AlainLich/COVID-Data |
Entradas por tecladoYa conocemos la función input() que lee una cadena por teclado. Su único inconveniente es que debemos transformar el valor a numérico si deseamos hacer operaciones con él: | decimal = float( input("Introduce un número decimal con punto: ") )
valores = []
print("Introduce 3 valores")
for x in range(3):
valores.append( input("Introduce un valor >") )
valores | _____no_output_____ | MIT | MaterialCursoPython/Fase 2 - Manejo de datos y optimizacion/Tema 05 - Entradas y salidas de datos/Apuntes/Leccion 1 (Apuntes) - Entradas.ipynb | mangrovex/CursoPython |
[CatBoost](https://github.com/catboost/catboost)Бустинг от Яндекса для категориальных фичей и много чего еще.Для начала настоятельно рекомендуется посмотреть видео. Там идет основная теория по CatBoost | from IPython.display import YouTubeVideo
YouTubeVideo('UYDwhuyWYSo', width=640, height=360) | _____no_output_____ | MIT | 10-BoostingPractice/.ipynb_checkpoints/CatBoost-checkpoint.ipynb | samstikhin/mlmathmech |
Резюмируя видео:Catboost строится на **Obvious Decision Tree** (ODT полное бинарное дерево) - это значит, что на каждом уровне дерева во всех вершинах идет разбиение по одному и тому же признаку. Дерево полное и симметричное. Листов - $2^H$, где $H$ - высота дерева и количество используемых фич.В Catboost куча фичей дл... | from IPython.display import YouTubeVideo
YouTubeVideo('xl1fwCza9C8', width=640, height=360) | _____no_output_____ | MIT | 10-BoostingPractice/.ipynb_checkpoints/CatBoost-checkpoint.ipynb | samstikhin/mlmathmech |
Простой пример | train_data = [[1, 4, 5, 6],
[4, 5, 6, 7],
[30, 40, 50, 60]]
eval_data = [[2, 4, 6, 8],
[1, 4, 50, 60]]
train_labels = [10, 20, 30]
# Initialize CatBoostRegressor
model = CatBoostRegressor(iterations=2,
learning_rate=1,
depth=... | 0: learn: 6.1237244 total: 164us remaining: 164us
1: learn: 4.5927933 total: 519us remaining: 0us
| MIT | 10-BoostingPractice/.ipynb_checkpoints/CatBoost-checkpoint.ipynb | samstikhin/mlmathmech |
Визуализация | rng = np.random.RandomState(31337)
boston = load_boston()
y = boston['target']
X = boston['data']
kf = KFold(n_splits=3, shuffle=True, random_state=rng)
X_train, X_rest, y_train, y_rest = train_test_split(X, y, test_size=0.25)
X_val, X_test, y_val, y_test = train_test_split(X_rest, y_rest, test_size=0.5)
cb = CatBoo... | _____no_output_____ | MIT | 10-BoostingPractice/.ipynb_checkpoints/CatBoost-checkpoint.ipynb | samstikhin/mlmathmech |
Тут включена крутая визуализация, с которой можно поиграться, она не работает в Jupyter Lab, но работает в Jupyter Notebook | cb.fit(X_train, y_train, eval_set=[(X_val , y_val ), (X_test, y_test)], plot=True) | _____no_output_____ | MIT | 10-BoostingPractice/.ipynb_checkpoints/CatBoost-checkpoint.ipynb | samstikhin/mlmathmech |
Бинаризации float Выбрать стратегию бинаризации можно установив параметр *feature_border_type*. - **Uniform**. Границы выбираются равномерно по значениям; - **Median**. В каждый бин попадает примерно одинаковое число различных значений; - **UniformAndQuantiles**. Uniform + Median; - **MaxLogSum, GreedyLogSum**. ... | from sklearn.model_selection import GridSearchCV
params = {"feature_border_type": [
"Uniform",
"Median",
"UniformAndQuantiles",
"MaxLogSum",
"GreedyLogSum",
"MinEntropy"
]}
cb = CatBoostRegressor(silent=True)
grid = GridSearchCV(cb, params)
grid.fit(X, y)
for score, strategy in sorted(zip(gri... | MSE: 0.6691938464447091, strategy: Uniform
MSE: 0.6748412401429629, strategy: GreedyLogSum
MSE: 0.6799599408912946, strategy: MaxLogSum
MSE: 0.6800117523745861, strategy: MinEntropy
MSE: 0.6809778425359567, strategy: UniformAndQuantiles
MSE: 0.6871689084536771, strategy: Median
| MIT | 10-BoostingPractice/.ipynb_checkpoints/CatBoost-checkpoint.ipynb | samstikhin/mlmathmech |
Feature importance | cb = CatBoostRegressor(silent=True)
cb.fit(X_train, y_train)
for value, name in sorted(zip(cb.get_feature_importance(fstr_type="FeatureImportance"),
boston["feature_names"])):
print("{}\t{}".format(name, value))
| CHAS 0.7931402360726668
ZN 1.0494204022222386
INDUS 1.7426222080011684
RAD 2.448575683482915
TAX 2.793079491612796
NOX 3.4660541597836496
AGE 3.6293317827732454
B 3.7497167241771456
CRIM 6.265450147752076
PTRATIO 6.32854168803267
DIS 8.319406311024368
LSTAT 26.740053619030157
RM 32.6746075460349
| MIT | 10-BoostingPractice/.ipynb_checkpoints/CatBoost-checkpoint.ipynb | samstikhin/mlmathmech |
Categorical features | from catboost.datasets import titanic
titanic_df = titanic()
X = titanic_df[0].drop('Survived',axis=1)
y = titanic_df[0].Survived
X.head(5)
is_cat = (X.dtypes != float)
is_cat.to_dict()
is_cat = (X.dtypes != float)
for feature, feat_is_cat in is_cat.to_dict().items():
if feat_is_cat:
X[feature].fillna("NAN... | _____no_output_____ | MIT | 10-BoostingPractice/.ipynb_checkpoints/CatBoost-checkpoint.ipynb | samstikhin/mlmathmech |
Аналогом для класса DMatrix в катбусте служит класс **catboost.Pool**. Помимо прочего, содержит индексы категориальных факторов и описание пар для режима попарного обучения.[Подробнее](https://tech.yandex.com/catboost/doc/dg/concepts/python-reference_pool-docpage/) | from catboost import Pool
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=.85, random_state=1234)
train_pool = Pool(data=X_train,
label=y_train,
cat_features=cat_features_index, # в явном виде передаем категориальные фичи, которыми хотим работать
... | Learning rate set to 0.029583
0: learn: 0.8124174 test: 0.8059701 best: 0.8059701 (0) total: 8.47ms remaining: 8.47s
100: learn: 0.8533686 test: 0.8059701 best: 0.8059701 (0) total: 317ms remaining: 2.82s
200: learn: 0.8837517 test: 0.8208955 best: 0.8208955 (200) total: 623ms remaining: 2.48s
300: learn: 0.9009247 tes... | MIT | 10-BoostingPractice/.ipynb_checkpoints/CatBoost-checkpoint.ipynb | samstikhin/mlmathmech |
На самом деле в Catboost происходит еще много чего интересного при обработке категорий: - среднее сглаживается некоторым априорным приближением; - по факту обучается несколько (3) модели на разных перестановках; - рассматриваются композиции категориальных факторов (max_ctr_complexity); - в момент применения модели,... | df_train = pd.DataFrame({'float':[1,2,3,4,5],
'animal': ['cat', 'dog', 'cat', 'dog', 'cat'],
'sign': ['rock', 'rock', 'paper', 'paper', 'paper']})
y_train = np.array([0,1,0,1, 0])
df_test = pd.DataFrame({'float':[6,7,8,9],
'animal': ['cat', 'dog... | _____no_output_____ | MIT | 10-BoostingPractice/.ipynb_checkpoints/CatBoost-checkpoint.ipynb | samstikhin/mlmathmech |
Данный подход лучше чем One-Hot, так как при нем мы можем серьезно вылететь за пределы памяти. Важный момент. В ходе подсчета статистики мы по сути сильно привязываемся к данным. Из-за чего может произойти сильное **переобучение**. Накопительные статистики Такие манипуляции очень легко могут привести к переобучению,... | def late_mean_target(df_train, df_test, y_train):
n = len(df_train)
cat_features = df_train.columns[df_train.dtypes == 'object'].tolist()
num_features = df_train.columns[df_train.dtypes != 'object'].tolist()
new_X_test = df_test.copy()
new_X_train = df_train.copy()
new_X_train['y'] = y_trai... | _____no_output_____ | MIT | 10-BoostingPractice/.ipynb_checkpoints/CatBoost-checkpoint.ipynb | samstikhin/mlmathmech |
Evaluación 1. Parte Computacional (60 puntos) (Elementos de Probabilidad y Estadística: 3008450)Se tiene información acerca de 694 propiedades ubicadas en el valle de aburra. La base de datos fue recolectada en el año 2015, e incluye las siguientes variables: 1. valor comercial de la propiedad en millones de pesos `p... | # importar librerias
import pandas as pd
from bokeh.server.server import Server
from bokeh.application import Application
from bokeh.application.handlers.function import FunctionHandler
from bokeh.io import output_notebook, push_notebook, show
from bokeh.layouts import column, row, gridplot
from bokeh.models import Col... | _____no_output_____ | MIT | examen_1.ipynb | sebastiangonzalezv/examen_estadistica |
Recategorice la variable estrato así: medio-bajo para los estratos 2 y 3, medio-alto para los estratos 4 y 5, y alto para el estrato 6. Realice un análisis descriptivo de las variables de la base de datos y resalte las características más destacadas de cada una de ellas. Utilice todos los gráficos y resúmenes que consi... | def modify_doc(doc):
def update():
current = df[(df.estrato.isin([str(x) for x in estrato.value])) & (df.ubicacion.isin([str(x) for x in ubicacion.value])) &
(df.alcobas.isin([int(x) for x in alcobas.value])) & (df.banos.isin([int(x) for x in banos.value])) &
... | _____no_output_____ | MIT | examen_1.ipynb | sebastiangonzalezv/examen_estadistica |
Elabore una tabla de doble entrada donde relacione si la propiedad tiene o no mejoras con la nueva categorización de la variable estrato. ¿En cuál de los nuevos estratos se presenta la mayor proporción de propiedades que tienen mejoras? Explique. |
frec_clase_peso = pd.pivot_table(df, columns='terminado', index='estrato', values='administracion', aggfunc='count')
frec_rel_clase_peso = frec_clase_peso/frec_clase_peso.sum().sum()
pd.concat([frec_clase_peso, frec_rel_clase_peso], axis=1)
frec_rel_clase_peso.plot(kind='bar')
plt.show() | _____no_output_____ | MIT | examen_1.ipynb | sebastiangonzalezv/examen_estadistica |
el estrarto alto es el que mas modificaciones ha hecho a sus vivienda esto se debe a su poder adqusitivo puede gastar en comodities Elabore un histograma de frecuencias relativas para la variable precio. ¿Qué observa? Comente | hist, hedges = np.histogram(df.precio, density=True, bins='sturges')
plot = figure(plot_width=350, plot_height=350)
plot.quad(bottom=0, left=hedges[:-1], right=hedges[1:], top=hist)
show(plot, notebook_url="localhost:8888") | _____no_output_____ | MIT | examen_1.ipynb | sebastiangonzalezv/examen_estadistica |
Right-Skewed Mode < Median < Mean 5. ¿Es muy diferente el comportamiento de los precios de las propiedades de acuerdo a la ubicación? Comente. Elabore los gráficos y/o resúmenes que considere pertinentes. 6. Grafique un diagrama de dispersión de las variables avalúo y precio. ¿Qué observa? ¿Qué pasa si los puntos grafi... | print('pearson')
df.corr(method='pearson')
print('kendall')
df.corr(method='kendall')
print('spearman')
df.corr(method='spearman') | spearman
| MIT | examen_1.ipynb | sebastiangonzalezv/examen_estadistica |
Sorting Madonna SongsThis project will randomly order the entire backlog of Madonna's songs. This was motivated following a colleague's offhand remark about one's favourite song being *Material Girl* by Madge, which triggered another colleague to provide the challenge of ranking all of Madonna's songs. In particular,... | # Export our environment, "NewEnv" and save it as "anomaly-detection.yml"
!conda env export -n NewEnv -f environment_anaconda.yml
# Check working directory to ensure user notebook is easily transferable
import os
os.getcwd()
# Import required libraries
import numpy as np
import pandas as pd
import xlrd
import csv | _____no_output_____ | Unlicense | DataImport.ipynb | avisionh/Sorting-Madonna-Songs |
Convert to CSVDo not have Excel installed so cannot convert it via that. Instead, get round it via the *xlrd* and *csv* packages.Note, could directly read in Excel file and play with that. However, learn less that way!Code for function was taken from this [link](https://stackoverflow.com/questions/9884353/xls-to-csv-c... | def csv_from_excel(file_input, file_output, sheet_index):
wb = xlrd.open_workbook(filename = file_input)
sh = wb.sheet_by_index(sheet_index)
file_csv = open(file = file_output, mode = 'wt')
wr = csv.writer(file_csv, quoting = csv.QUOTE_ALL)
for rownum in range(sh.nrows):
wr.writerow(sh.row... | _____no_output_____ | Unlicense | DataImport.ipynb | avisionh/Sorting-Madonna-Songs |
Data WrangleLoad in our .csv file so that we can add distinct random numbers as a column which we will use to sort on.Note: File is encoded as *ANSI* which is `mbcs` in the `pd.red_csv()`. | # import data
data_madge = pd.read_csv(filepath_or_buffer = 'data\songs_madonna.csv', encoding = 'mbcs')
# display data
data_madge.head() | _____no_output_____ | Unlicense | DataImport.ipynb | avisionh/Sorting-Madonna-Songs |
In the code below, are following a naive method for creating a column of distinct random numbers. This will be in steps:1. Store the number of rows in a variable.1. Generate a random sample without replacement using the number of rows as our region of interest.1. Bind this random sample onto our `data_madge` dataframe. | # import package for random-sampling
import random
# set random seed
seed_random = np.random.RandomState(123)
# 1. store number of rows in a variable
n_rows = len(data_madge.index)
# 2. generate random sample without replacement
# note: using try-catch logic to ensure we generate a sample
try:
sample_random = ran... | _____no_output_____ | Unlicense | DataImport.ipynb | avisionh/Sorting-Madonna-Songs |
Specific preferencesWhilst broadly indifferent between the vast majority of Madge's discology, two songs stand out to the author:- Material Girl- La Isla BonitaWhat one wants to do is thus ensure that these two songs have the highest two preference rankings, `0` and `1`. | # 1. find songs randomly classified as favourites
value_top_preferences_random = [0, 1]
data_top_random = data_madge[data_madge.Preference_Avision.isin(value_top_preferences_random)]
# 2. find 'Material Girl' and 'La Isla Bonita'
songs_top_own = ['Material Girl', 'La Isla Bonita']
data_top_own = data_madge[data_madge.S... | _____no_output_____ | Unlicense | DataImport.ipynb | avisionh/Sorting-Madonna-Songs |
Data ExportNow that we have the dataframe in a suitable format and reflective of the author's preferences, can export it as a .csv file for use in Java when we will apply assorted sorting algorithms on it. | data_preference.to_csv(path_or_buf = 'output\output_preference.csv',
sep = ',', encoding =
) | _____no_output_____ | Unlicense | DataImport.ipynb | avisionh/Sorting-Madonna-Songs |
Homework (16 pts) - Hypothesis Testing | import numpy as np
import scipy.stats as st
import matplotlib.pyplot as plt | _____no_output_____ | Unlicense | homework/key-hypothesis_testing.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
1. You measure the duration of high frequency bursts of action potentials under two different experimental conditions (call them conditions A and B). Based on your measured data below, determine if the conditions affect the mean burst duration or if differences are just due to random fluctuations? See 1a-d below. | burstDurationsA_ms = np.array([180.38809356, 118.54316518, 47.36070342, 258.43152543,
157.58441772, 53.00241256, 97.87549106, 98.58339172,
3.82151168, 149.63437886, 78.36434292, 207.1499196 ,
249.99308288, 52.33575872, 177.16295745, 20.90902826,
355.53831638, 17.14676607, 194.82448... | _____no_output_____ | Unlicense | homework/key-hypothesis_testing.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
1a. (1 pt) State the null and alternative hypotheses. H0: Conditions have no affect on mean burst durations.Ha: Mean burst duration differs between conditions. 1b. (3 ps) Plot the burst distributions for conditions A and B overlaid with your best estimate for the probability density function that describes them. | distA = st.expon(loc=0, scale=burstDurationsA_ms.mean())
distB = st.expon(loc=0, scale=burstDurationsB_ms.mean())
plt.hist(burstDurationsA_ms, bins=20, density=True, alpha=0.25, label='A')
plt.hist(burstDurationsB_ms, bins=20, density=True, alpha=0.25, label='B')
dur_ms = np.linspace(0, 500, 100)
plt.plot(dur_ms, dist... | _____no_output_____ | Unlicense | homework/key-hypothesis_testing.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
1c. (3 pts) Use a permutation test with 1000 permutations to test your null hypothesis. Compute the difference between mean burst durations for all 1000 permutations of the datasets. | nA = len(burstDurationsA_ms)
nB = len(burstDurationsB_ms)
allBurstDurations = np.zeros((nA + nB,))
allBurstDurations[:nA] = burstDurationsA_ms
allBurstDurations[-nB:] = burstDurationsB_ms
numPermutations = 1000
permutedMeanBurstDurationDiffs = np.zeros((numPermutations,))
for i in range(numPermutations):
np.rand... | _____no_output_____ | Unlicense | homework/key-hypothesis_testing.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
1d. (3 pts) Plot the distribtuion of mean burst time differences from each permutation and use vertical dashed lines ot indicate the 95% confidence interval and a vertical solid line to indicate the measured mean burst time difference between the actual datasets. Finally, answer the original question, do the conditions... | # plot the distribution differences between taus for each permutation
plt.hist(permutedMeanBurstDurationDiffs, bins=50, alpha=0.25, label='Expected under H0');
plt.xlabel('Mean Burst Duration Diff B - A (ms)')
plt.ylabel('# Permutations');
# add 95% confidence intervals to the plot
lb, ub = np.quantile(permutedMeanBur... | _____no_output_____ | Unlicense | homework/key-hypothesis_testing.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
Reject H0 as measured difference falls outside of 95% confidence interval for expected differenece if H0 was true.Thus, we infer that condition B did affect the mean burst duration as compared to condition A. 2. You record the resting potential of a cell (see below). See 2a-c below. | restingPotential_mV = np.array([-85.06885608, -68.0333149 , -77.04147864, -70.82636201,
-73.11516394, -70.87124656, -69.8945143 , -71.35017797,
-78.97700081, -76.06762065, -80.16301496, -75.53757879,
-66.29208026, -84.46635021, -74.99594162, -81.64926101,
-69.43971079, -60.09946296, -66.7982... | _____no_output_____ | Unlicense | homework/key-hypothesis_testing.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
2a. (3 pts) You only have one sample (above) with a single mean. Use the Central Limit Theorem to estimate the distribution of mean resting potentials were you to collect a bunch more samples. Plot this distribution and indicate its 95% confidence interval with vertical lines on the plot. | mu = restingPotential_mV.mean()
sem = restingPotential_mV.std() / np.sqrt(len(restingPotential_mV))
meanDist = st.norm(mu, sem)
mV = np.linspace(-77, -71, 101)
plt.plot(mV, meanDist.pdf(mV))
plt.xlabel('Mean Resting Potential (mV)')
plt.ylabel('pdf')
plt.title('Central Limit Theorem')
lb, ub = meanDist.ppf([0.025, 0.9... | _____no_output_____ | Unlicense | homework/key-hypothesis_testing.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
2b. (3 pts) Use 1000 bootstrapped samples to estimate the 95% confidence interval for the mean resting potential. Plot the distribution of bootstrap mean resting potentials and indicate the 95% confidence intervals with vertical lines. How do these compare to that obtained by the Central Limit Theorem? | numBootstraps = 1000
bootstrappedMeans = np.zeros((numBootstraps,))
for i in range(numBootstraps):
bootstrappedRestingPotentials_mV = \
np.random.choice(restingPotential_mV, size=restingPotential_mV.shape, replace=True)
bootstrappedMeans[i] = bootstrappedRestingPotentials_mV.mean()
bootstrappedMeansCI ... | _____no_output_____ | Unlicense | homework/key-hypothesis_testing.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
Bootstrap confidence interval is very similar to that based on Central Limit Theorem. | 2c. (3 pts) Use a t-Test to determine whether this cell belongs to a set of cells that you previously determined have a resting potential of -60 mV? | _____no_output_____ | Unlicense | homework/key-hypothesis_testing.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
I didn't specifically ask for the normality test, so it is ok if it was not included. But you should do some sort of check for normality if you are using a t-Test.stat, pvalue = st.normaltest(restingPotential_mV)isNormallyDistributed = pvalue >= 0.05isNormallyDistributed t, pvalue = st.ttest_1samp(restingPotential_mV,... | p-value < 0.025, so reject null hypothesis that cell has a resting potential of -60 mV. Thus, we infer that this cell differs from the previous set of cells. This is also what we would infer from the plots in 2a-b. | _____no_output_____ | Unlicense | homework/key-hypothesis_testing.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
TDD for data with pytestTDD is great for software engineering, but did you know TDD can add a lot of speed and quality to Data Science projects too?We'll learn how we can use TDD to save you time - and quickly improve functions which extract and process data. About me**Chris Brousseau***Surface Owl - Founder & Data S... | # setup - thank you Moshe!
import unittest
def test(klass):
loader = unittest.TestLoader()
# suite=loader.loadTestsFromTestCase(klass) # original
suite=loader.loadTestsFromModule(klass) # to work with datatest example
runner = unittest.TextTestRunner()
runner.run(suite)
# other helpful setup
# ipy... | ..... | MIT | TDD_for_data_cleaning_with_pytest.ipynb | surfaceowl/pythontalk_tdd_for_data |
2 - TDD for data engineering Example 1 - finding urls in excel- url test case- multiple url test case which breaks prior tests- regex101.com illustration (edit function to make tests pass) https://regex101.com/- final regex to rule them all Sample data (under /data/test_cais) - needs transformation|example 1 |~ |exa... | # %load tests/test_02_cais_find_single_url
"""
test functions to find url in cell content from an excel worksheet
functions below have "do_this_later_" prefix to prevent tests from running during early part of talk
remove prefix as we walk through examples, and re-run tests
"""
from src.excel_find_url import find_url
... | _____no_output_____ | MIT | TDD_for_data_cleaning_with_pytest.ipynb | surfaceowl/pythontalk_tdd_for_data |
[regex101](https://regex101.com) w{3}.* (http|https):\/\/.* ((http|https):\/\/)?[a-zA-Z0-9.\/?::-_=]+\.([a-zA-Z]){2,6}([a-zA-Z0-9..\/&\/\-_=])* www.prioryca.org http://www.prioryca.org https://prioryca.org Switch to PyCharm or your IDE to edit code and run multiple tests Example 2 - finding name... | """
tests focused on ability to pull all the names from a cais excel file
"""
def test_find_2013_cais_name_table10():
"""
test finding names in first member schools tab
test function to dynamically look up names vs. expected result from separate file
:return: True or False
"""
test_file = "Scho... | _____no_output_____ | MIT | TDD_for_data_cleaning_with_pytest.ipynb | surfaceowl/pythontalk_tdd_for_data |
Information FlowIn this chapter, we detail how to track information flows in python by tainting input strings, and tracking the taint across string operations. Some material on `eval` exploitation is adapted from the excellent [blog post](https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) by Ned Batc... | import fuzzingbook_utils
from ExpectError import ExpectError
import inspect
import enum
%%html
<div>
<style>
div.todo {
color:red;
font-weight: bold;
}
div.todo::before {
content: "TODO: ";
}
div.done {
color:blue;
font-weight: bold;
}
div.done::after {
content: " :DONE";
}
</style>
<script>
... | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
Say we want to implement a calculator service in Python. A really simple way to do that is to rely on the `eval()` function in Python. Since we do not want our users to be able to execute arbitrary commands on our server, we use `eval()` with empty `locals` and `globals` | def my_calculator(my_input):
result = eval(my_input, {}, {})
print("The result of %s was %d" % (my_input, result)) | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
It wors as expected: | my_calculator('1+2') | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
Does it? | with ExpectError():
my_calculator('__import__("os").popen("ls").read()') | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
As you can see from the error, `eval()` completed successfully, with the system command `ls` executing successfully. It is easy enough for the user to see the output if needed. | my_calculator("1 if __builtins__['print'](__import__('os').popen('ls').read()) else 0") | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
The problem is that the Python `__builtins__` is [inserted by default](https://docs.python.org/3/library/functions.htmleval) when one uses `eval()`. We can avoid this by restricting `__builtins__` in `eval` explicitly. | def my_calculator(my_input):
result = eval(my_input, {"__builtins__":None}, {})
print("The result of %s was %d" % (my_input, result)) | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
Does it help? | with ExpectError():
my_calculator("1 if __builtins__['print'](__import__('os').popen('ls').read()) else 0") | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
But does it actually? | my_calculator("1 if [x['print'](x['__import__']('os').popen('ls').read()) for x in ([x for x in (1).__class__.__base__.__subclasses__() if x.__name__ == 'Sized'][0].__len__.__globals__['__builtins__'],)] else 0") | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
The problem here is that when the user has a way to inject **uninterpreted strings** that can reach a dangerous routine such as `eval()` or an `exec()`, it makes it possible for them to inject dangerous code. What we need is a way to restrict the ability of uninterpreted input string fragments from reaching dangerous ... | class tstr_(str):
def __new__(cls, value, *args, **kw):
return super(tstr_, cls).__new__(cls, value)
class tstr(tstr_):
def __init__(self, value, taint=None, parent=None, **kwargs):
self.parent = parent
l = len(self)
if taint:
if isinstance(taint, int):
... | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
By default, when we wrap a string, it is tainted. Hence we also need a way to `untaint` the string. | class tstr(tstr):
def untaint(self):
self._taint = [-1] * len(self)
return self
t = tstr('hello world')
t.untaint()
t.has_taint() | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
However, the taint does not transition from the whole string to parts. | with ExpectError():
t = tstr('hello world')
t[0:5].has_taint() | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
Slice The Python `slice` operator `[n:m]` relies on the object being an `iterator`. Hence, we define the `__iter__()` method. | class tstr(tstr):
def __iter__(self):
return tstr_iterator(self)
def create(self, res, taint):
return tstr(res, taint, self)
def __getitem__(self, key):
res = super().__getitem__(key)
if type(key) == int:
key = len(self) + key if key < 0 else key
... | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
The Python `slice` operator `[n:m]` relies on the object being an `iterator`. Hence, we define the `__iter__()` method. The iterator classThe `__iter__()` method requires a supporting `iterator` object. | class tstr_iterator():
def __init__(self, tstr):
self._tstr = tstr
self._str_idx = 0
def __next__(self):
if self._str_idx == len(self._tstr): raise StopIteration
# calls tstr getitem should be tstr
c = self._tstr[self._str_idx]
assert type(c) is tstr
self... | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
Helper MethodsWe define a few helper methods that deals with the mapped taint index. | class tstr(tstr):
class TaintException(Exception):
pass
def x(self, i=0):
v = self._x(i)
if v < 0:
raise taint.TaintException('Invalid mapped char idx in tstr')
return v
def _x(self, i=0):
return self.get_mapped_char_idx(i)
def get_mapped_char_idx(s... | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
Concatenation Implementing concatenation is straight forward: | class tstr(tstr):
def __add__(self, other):
if type(other) is tstr:
return self.create(str.__add__(self, other), (self._taint + other._taint))
else:
return self.create(str.__add__(self, other), (self._taint + [-1 for i in other])) | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
Testing concatenations | my_str1 = tstr("hello")
my_str2 = tstr("world", taint=6)
my_str3 = "bye"
v = my_str1 + my_str2
print(v._taint)
w = my_str1 + my_str3 + my_str2
print(w._taint)
class tstr(tstr):
def __radd__(self, other): #concatenation (+) -- other is not tstr
if type(other) is tstr:
return self.create(str.__a... | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
Replace | class tstr(tstr):
def replace(self, a, b, n=None):
old_taint = self._taint
b_taint = b._taint if type(b) is tstr else [-1] * len(b)
mystr = str(self)
i = 0
while True:
if n and i >= n: break
idx = mystr.find(a)
if idx == -1: break
... | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
Split We essentially have to re-implement split operations, and split by space is slightly different from other splits. | class tstr(tstr):
def _split_helper(self, sep, splitted):
result_list = []
last_idx = 0
first_idx = 0
sep_len = len(sep)
for s in splitted:
last_idx = first_idx + len(s)
item = self[first_idx:last_idx]
result_list.append(item)
... | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
Strip | class tstr(tstr):
def strip(self, cl=None):
return self.lstrip(cl).rstrip(cl)
def lstrip(self, cl=None):
res = super().lstrip(cl)
i = self.find(res)
return self[i:]
def rstrip(self, cl=None):
res = super().rstrip(cl)
return self[0:len(res)]
my_str1 = tstr("... | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
Expand Tabs | class tstr(tstr):
def expandtabs(self, n=8):
parts = self.split('\t')
res = super().expandtabs(n)
all_parts = []
for i, p in enumerate(parts):
all_parts.extend(p._taint)
if i < len(parts) - 1:
l = len(all_parts) % n
all_parts.ex... | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
Partitions | class tstr(tstr):
def partition(self, sep):
partA, sep, partB = super().partition(sep)
return (
self.create(partA, self._taint[0:len(partA)]), self.create(sep, self._taint[len(partA): len(partA) + len(sep)]), self.create(partB, self._taint[len(partA) + len(sep):]))
def rpartition(se... | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
Justify | class tstr(tstr):
def ljust(self, width, fillchar=' '):
res = super().ljust(width, fillchar)
initial = len(res) - len(self)
if type(fillchar) is tstr:
t = fillchar.x()
else:
t = -1
return self.create(res, [t] * initial + self._taint)
def rjust(sel... | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
String methods that do not change taint | def make_str_wrapper_eq_taint(fun):
def proxy(*args, **kwargs):
res = fun(*args, **kwargs)
return args[0].create(res, args[0]._taint)
return proxy
for name, fn in inspect.getmembers(str, callable):
if name in ['swapcase', 'upper', 'lower', 'capitalize', 'title']:
setattr(tstr, name,... | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
General wrappers These are not strictly needed for operation, but can be useful for tracing | def make_str_wrapper(fun):
def proxy(*args, **kwargs):
res = fun(*args, **kwargs)
return res
return proxy
import types
tstr_members = [name for name, fn in inspect.getmembers(tstr,callable)
if type(fn) == types.FunctionType and fn.__qualname__.startswith('tstr')]
for name, fn in inspect.getmem... | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
Methods yet to be translated These methods generate strings from other strings. However, we do not have the right implementations for any of these. Hence these are marked as dangerous until we can generate the right translations. | def make_str_abort_wrapper(fun):
def proxy(*args, **kwargs):
raise TaintException('%s Not implemented in TSTR' % fun.__name__)
return proxy
for name, fn in inspect.getmembers(str, callable):
if name in ['__format__', '__rmod__', '__mod__', 'format_map', 'format',
'__mul__','__rmul__'... | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
EOF Tracker Sometimes we want to know where an empty string came from. That is, if an empty string is the result of operations on a tainted string, we want to know the best guess as to what the taint index of the preceding character is. Slice For detecting EOF, we need to carry the cursor. The main idea is the cursor... | class eoftstr(tstr):
def create(self, res, taint):
return eoftstr(res, taint, self)
def __getitem__(self, key):
def get_interval(key):
return ((0 if key.start is None else key.start),
(len(res) if key.stop is None else key.stop))
res = super().__geti... | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
A Comparison Tracker Sometimes, we also want to know what each character in an input was compared to. Operators | class Op(enum.Enum):
LT = 0
LE = enum.auto()
EQ = enum.auto()
NE = enum.auto()
GT = enum.auto()
GE = enum.auto()
IN = enum.auto()
NOT_IN = enum.auto()
IS = enum.auto()
IS_NOT = enum.auto()
FIND_STR = enum.auto()
COMPARE_OPERATORS = {
Op.EQ: lambda x, y: x == y,
Op.N... | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
Instructions | class Instr:
def __init__(self, o, a, b):
self.opA = a
self.opB = b
self.op = o
def o(self):
if self.op == Op.EQ:
return 'eq'
elif self.op == Op.NE:
return 'ne'
else:
return '?'
def opS(self):
if not self.opA.has_t... | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
Equivalance | class ctstr(eoftstr):
def create(self, res, taint):
o = ctstr(res, taint, self)
o.comparisons = self.comparisons
return o
def with_comparisons(self, comparisons):
self.comparisons = comparisons
return self
class ctstr(ctstr):
def __eq__(self, other):
if l... | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
Lessons Learned* One can track the information flow form input to the internals of a system. Next Steps_Link to subsequent chapters (notebooks) here:_ Background\cite{Lin2008} Exercises_Close the chapter with a few exercises such that people have things to do. To make the solutions hidden (to be revealed by the us... | # Some code that is part of the exercise
pass | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
_Some more text for the exercise_ **Solution.** _Some text for the solution_ | # Some code for the solution
2 + 2 | _____no_output_____ | MIT | notebooks/InformationFlow.ipynb | R3dFruitRollUp/fuzzingbook |
Face and Facial Keypoint detectionAfter you've trained a neural network to detect facial keypoints, you can then apply this network to *any* image that includes faces. The neural network expects a Tensor of a certain size as input and, so, to detect any face, you'll first have to do some pre-processing.1. Detect all t... | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
%matplotlib inline | _____no_output_____ | MIT | .ipynb_checkpoints/3. Facial Keypoint Detection, Complete Pipeline-checkpoint.ipynb | adjanni/Facial_Keypoints_Detection_w_CNN--Pytorch |
Select an image Select an image to perform facial keypoint detection on; you can select any image of faces in the `images/` directory. | import cv2
# load in color image for face detection
image = cv2.imread('images/michelle_detected.png')
# switch red and blue color channels
# --> by default OpenCV assumes BLUE comes first, not RED as in many images
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# plot the image
fig = plt.figure(figsize=(9,9))
plt.i... | _____no_output_____ | MIT | .ipynb_checkpoints/3. Facial Keypoint Detection, Complete Pipeline-checkpoint.ipynb | adjanni/Facial_Keypoints_Detection_w_CNN--Pytorch |
Detect all faces in an imageNext, you'll use one of OpenCV's pre-trained Haar Cascade classifiers, all of which can be found in the `detector_architectures/` directory, to find any faces in your selected image.In the code below, we loop over each face in the original image and draw a red square on each face (in a copy... | # load in a haar cascade classifier for detecting frontal faces
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_eye.xml')
# run the detector
# the output here is an array of detections; the corner... | _____no_output_____ | MIT | .ipynb_checkpoints/3. Facial Keypoint Detection, Complete Pipeline-checkpoint.ipynb | adjanni/Facial_Keypoints_Detection_w_CNN--Pytorch |
Loading in a trained modelOnce you have an image to work with (and, again, you can select any image of faces in the `images/` directory), the next step is to pre-process that image and feed it into your CNN facial keypoint detector.First, load your best model by its filename. | import torch
from models import Net
net = Net()
#keypoints_model_BachSize32_Relu_NaimishNet.pt
## TODO: load the best saved model parameters (by your path name)
## You'll need to un-comment the line below and add the correct name for *your* saved model
net.load_state_dict(torch.load('saved_models/keypoints_model_Bach... | _____no_output_____ | MIT | .ipynb_checkpoints/3. Facial Keypoint Detection, Complete Pipeline-checkpoint.ipynb | adjanni/Facial_Keypoints_Detection_w_CNN--Pytorch |
Keypoint detectionNow, we'll loop over each detected face in an image (again!) only this time, you'll transform those faces in Tensors that your CNN can accept as input images. TODO: Transform each detected face into an input TensorYou'll need to perform the following steps for each detected face:1. Convert the face f... | image_copy = np.copy(image)
# loop over the detected faces from your haar cascade
for (x,y,w,h) in faces:
# Select the region of interest that is the face in the image
#NOTE: The faces in the datasets in the training set are not as zoomed in as the ones Haar Cascade detects.
# That s why I HAVE to gr... | Original size (908, 916) Resize image (224, 224)
| MIT | .ipynb_checkpoints/3. Facial Keypoint Detection, Complete Pipeline-checkpoint.ipynb | adjanni/Facial_Keypoints_Detection_w_CNN--Pytorch |
Reinforcement Learning Tutorial -1: Q Learning MD Muhaimin Rahmansezan92[at]gmail[dot]com Q learning , can be said one of the most famous -and kind of intuitive- of all Reinforcement learning algorithms. In fact ,the recent all algorithms using Deep learning , are based on the Q learning algorithms. So, to work on re... | import gym
import numpy as np | _____no_output_____ | MIT | .ipynb_checkpoints/RL_Tutorial_1-checkpoint.ipynb | sezan92/RLTutorialKeras |
Initialization of Environments I will use the Mountaincar environment by Open AI gym. It is a classic problem invented from 90s. I intend to use this environment for all algorithms .  In this game, your task is to get the car reach that green flag. For every step you will get -1 .So , your job is to reach th... | env = gym.make('MountainCar-v0')
s = env.reset() #Reset the car | _____no_output_____ | MIT | .ipynb_checkpoints/RL_Tutorial_1-checkpoint.ipynb | sezan92/RLTutorialKeras |
```env.reset()``` gives the initial state. State is the position and velocity of the car in a given time This game's actions can be 0,1,2 . 0 for left, 1 for doing nothing, 2 for right```env.step(action)``` returns four arguments - next state- reward- terminal , it means if game is over or not- info , for now , it is u... | legal_actions=env.action_space.n
actions = [0,1,2]
gamma =0.99
lr =0.5
num_episodes =30000
epsilon =0.5
epsilon_decay =0.99 | _____no_output_____ | MIT | .ipynb_checkpoints/RL_Tutorial_1-checkpoint.ipynb | sezan92/RLTutorialKeras |
Codeblock to discretize the state. Because ***Q learning*** doesnt work on continuous state space, we have to convert states into 10 discrete states | N_BINS = [10,10]
MIN_VALUES = [0.6,0.07]
MAX_VALUES = [-1.2,-.07]
BINS = [np.linspace(MIN_VALUES[i], MAX_VALUES[i], N_BINS[i]) for i in range(len(N_BINS))]
rList =[]
def discretize(obs):
return tuple([int(np.digitize(obs[i], BINS[i])) for i in range(len(N_BINS))]) | _____no_output_____ | MIT | .ipynb_checkpoints/RL_Tutorial_1-checkpoint.ipynb | sezan92/RLTutorialKeras |
Q Learning CLass | class QL:
def __init__(self,Q,policy,
legal_actions,
actions,
gamma,
lr):
self.Q = Q #Q matrix
self.policy =policy
self.legal_actions=legal_actions
self.actions = actions
self.gamma =gamma
self.lr =lr
... | _____no_output_____ | MIT | .ipynb_checkpoints/RL_Tutorial_1-checkpoint.ipynb | sezan92/RLTutorialKeras |
Q Matrix Parameters - ```Q``` - Q table. We will use dictionary data structure.- ```policy``` - policy table , it will give us the action for given state | Q = {}
policy ={}
legal_actions =3
QL = QL(Q,policy,legal_actions,actions,gamma,lr) | _____no_output_____ | MIT | .ipynb_checkpoints/RL_Tutorial_1-checkpoint.ipynb | sezan92/RLTutorialKeras |
Training Psuedocode - get initial state $s_{raw}$- discretize initial state , $s \gets discretize(s_{raw})$- set total reward to zero , $r_{total} \gets 0$- set terminal $d$ to false , $d \gets False$- for each step- - choose action based on epsilon greedy policy- - get next state $s1_{raw} $, reward , $r$, terminal $... | for i in range(num_episodes):
s_raw= env.reset() #initialize
s = discretize(s_raw) #discretize the state
rAll =0 #total reward
d = False
j = 0
for j in range(200):
#epsilon greedy. to choose random actions initially when Q is all zeros
if np.random.random()< epsilon:
... | _____no_output_____ | MIT | .ipynb_checkpoints/RL_Tutorial_1-checkpoint.ipynb | sezan92/RLTutorialKeras |
RPLIB CardThis notebook displays the results of a RPLIB analysis (i.e., an RPLIB Card).Find your dataset ID by visiting https://birg.dev/rplib/, and then enter it below. | #@title Dataset ID and Card Type
dataset_id = 636#@param {type:"number"}
card_type = 'lop' #@param ["lop", "hillside", "massey", "colley"]
RPLIB_DATA_PREFIX='https://raw.githubusercontent.com/IGARDS/RPLib/main/data'
#@title Includes and Dependencies
from IPython.display import display, Markdown, Latex
try:
import ... | _____no_output_____ | MIT | notebooks/RPLIB_Card.ipynb | IGARDS/structured_artificial |
Dataset | unprocessed_dataset | _____no_output_____ | MIT | notebooks/RPLIB_Card.ipynb | IGARDS/structured_artificial |
Processed Dataset | processed_dataset | _____no_output_____ | MIT | notebooks/RPLIB_Card.ipynb | IGARDS/structured_artificial |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.