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 |
|---|---|---|---|---|---|
ComentáriosOs resultados da variável dose tem a maior distância do valor médio (sum_sq) e portanto a maior variância relatica (F-Score). Isto pode ser comprovado pelo Eta-Squared e Omega-Squared (definição abaixo). Mais sobre Eta-Squared e Omega-SquaredOutro conjunto de medidas de tamanho de efeito para variáveis inde... | formula = 'len ~ C(supp) + C(dose) + C(supp):C(dose)'
model = ols(formula, data).fit()
aov_table = anova_lm(model, typ=2)
eta_squared(aov_table)
omega_squared(aov_table)
print(aov_table) | _____no_output_____ | MIT | 01-python-EDA-stat-univariada/07 Inferência 2/inferencia_2_anova.ipynb | sn3fru/datascience_course |
Quantile-Quantile (QQplot) | res = model.resid
fig = sm.qqplot(res, line='s')
plt.show() | _____no_output_____ | MIT | 01-python-EDA-stat-univariada/07 Inferência 2/inferencia_2_anova.ipynb | sn3fru/datascience_course |
Import development libraries | import bw2data as bd
import bw2calc as bc
import bw_processing as bwp
import numpy as np
import matrix_utils as mu | _____no_output_____ | BSD-3-Clause | dev/Multifunctionality with Brightway 2.5.ipynb | mixib/matrix_utils |
Create new project | bd.projects.set_current("Multifunctionality") | _____no_output_____ | BSD-3-Clause | dev/Multifunctionality with Brightway 2.5.ipynb | mixib/matrix_utils |
Our existing implementation allows us to distinguish activities and prodducts, though not everyone does this. | db = bd.Database("background")
db.write({
("background", "1"): {
"type": "process",
"name": "1",
"exchanges": [{
"input": ("background", "bio"),
"amount": 1,
"type": "biosphere",
}]
},
("background", "2"): {
"type": "process",
... | _____no_output_____ | BSD-3-Clause | dev/Multifunctionality with Brightway 2.5.ipynb | mixib/matrix_utils |
LCA of background systemThis database is fine and normal. It work the way we expect.Here we use the preferred calling convention for Brightway 2.5, with the convenience function `prepare_lca_inputs`. | fu, data_objs, _ = bd.prepare_lca_inputs(demand={("background", "4"): 1}, method=("something",))
lca = bc.LCA(fu, data_objs=data_objs)
lca.lci()
lca.lcia()
lca.score | _____no_output_____ | BSD-3-Clause | dev/Multifunctionality with Brightway 2.5.ipynb | mixib/matrix_utils |
Multifunctional activitiesWhat happens when we have an activity that produces multiple products? | db = bd.Database("example mf")
db.write({
# Activity
("example mf", "1"): {
"type": "process",
"name": "mf 1",
"exchanges": [
{
"input": ("example mf", "2"),
"amount": 2,
"type": "production",
}, {
"i... | Writing activities to SQLite3 database:
0% [###] 100% | ETA: 00:00:00
Total time elapsed: 00:00:00
| BSD-3-Clause | dev/Multifunctionality with Brightway 2.5.ipynb | mixib/matrix_utils |
We can do an LCA of one of the products, but we will get a warning about a non-square matrix: | fu, data_objs, _ = bd.prepare_lca_inputs(demand={("example mf", "1"): 1}, method=("something",))
lca = bc.LCA(fu, data_objs=data_objs)
lca.lci() | _____no_output_____ | BSD-3-Clause | dev/Multifunctionality with Brightway 2.5.ipynb | mixib/matrix_utils |
If we look at the technosphere matrix, we can see our background database (upper left quadrant), and the two production exchanges in the lower right: | lca.technosphere_matrix.toarray() | _____no_output_____ | BSD-3-Clause | dev/Multifunctionality with Brightway 2.5.ipynb | mixib/matrix_utils |
Handling multifunctionalityThere are many ways to do this. This notebook is an illustration of how such approaches can be madde easier using the helper libraries [bw_processing](https://github.com/brightway-lca/bw_processing) and [matrix_utils](https://github.com/brightway-lca/matrix_utils), not a statement that one a... | def economic_allocation(dataset):
assert isinstance(dataset, bd.backends.Activity)
# Split exchanges into functional and non-functional
functions = [exc for exc in dataset.exchanges() if exc.input.get('type') in {'good', 'waste'}]
others = [exc for exc in dataset.exchanges() if exc.input.get('type'... | _____no_output_____ | BSD-3-Clause | dev/Multifunctionality with Brightway 2.5.ipynb | mixib/matrix_utils |
Note that the last two columns, when summed together, form the unallocated activity (column 4): | lca.technosphere_matrix.toarray() | _____no_output_____ | BSD-3-Clause | dev/Multifunctionality with Brightway 2.5.ipynb | mixib/matrix_utils |
To make sure what we have done is clear, we can create the matrix just for the "delta" data package: | mu.MappedMatrix(packages=[dp], matrix="technosphere_matrix").matrix.toarray() | _____no_output_____ | BSD-3-Clause | dev/Multifunctionality with Brightway 2.5.ipynb | mixib/matrix_utils |
And we can now do LCAs of both allocated products: | lca.lcia()
lca.score
lca = bc.LCA({bd.get_id(("example mf", "3")): 1}, data_objs=data_objs + [dp])
lca.lci()
lca.lcia()
lca.score | _____no_output_____ | BSD-3-Clause | dev/Multifunctionality with Brightway 2.5.ipynb | mixib/matrix_utils |
Reported crimes per Community Area by Primary Type | crime_org= pd.DataFrame(crimes.pivot_table(crimes,index=["Community Area", "Primary Type"]))
crime_org
crime_data = pd.DataFrame(crimes.pivot_table(values=["ID"], index=["Community Area", "Primary Type", "Date"], aggfunc=np.sum))
crime_data | _____no_output_____ | MIT | jupyter_notebooks/Crime Data.ipynb | jessicagtz/Project-2-Chicago-Communities |
Number of Reported Crimes per Commuity Area | #1) group by community area
#2) get numbers of crime type per community area
crime_area= pd.DataFrame(crimes.groupby("Community Area")["ID"].count())
crime_area | _____no_output_____ | MIT | jupyter_notebooks/Crime Data.ipynb | jessicagtz/Project-2-Chicago-Communities |
Number of Reported Crimes per Primary Type | crime_type= pd.DataFrame(crimes.groupby("Primary Type")["ID"].count())
crime_type | _____no_output_____ | MIT | jupyter_notebooks/Crime Data.ipynb | jessicagtz/Project-2-Chicago-Communities |
______Copyright Pierian DataFor more information, visit us at www.pieriandata.com DataFramesDataFrames are the workhorse of pandas and are directly inspired by the R programming language. We can think of a DataFrame as a bunch of Series objects put together to share the same index. Let's use pandas to explore this top... | import pandas as pd
import numpy as np
from numpy.random import randint
columns= ['W', 'X', 'Y', 'Z'] # four columns
index= ['A', 'B', 'C', 'D', 'E'] # five rows
np.random.seed(42)
data = randint(-100,100,(5,4))
data
df = pd.DataFrame(data,index,columns)
df | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/01-Pandas-Crash-Course/02-DataFrames.ipynb | tanuja333/Tensorflow_Keras |
Selection and IndexingLet's learn the various methods to grab data from a DataFrame COLUMNS Grab a single column | df['W'] | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/01-Pandas-Crash-Course/02-DataFrames.ipynb | tanuja333/Tensorflow_Keras |
Grab multiple columns | # Pass a list of column names
df[['W','Z']] | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/01-Pandas-Crash-Course/02-DataFrames.ipynb | tanuja333/Tensorflow_Keras |
DataFrame Columns are just Series | type(df['W']) | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/01-Pandas-Crash-Course/02-DataFrames.ipynb | tanuja333/Tensorflow_Keras |
Creating a new column: | df['new'] = df['W'] + df['Y']
df | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/01-Pandas-Crash-Course/02-DataFrames.ipynb | tanuja333/Tensorflow_Keras |
Removing Columns | # axis=1 because its a column
df.drop('new',axis=1)
# Not inplace unless reassigned!
df
df = df.drop('new',axis=1)
df | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/01-Pandas-Crash-Course/02-DataFrames.ipynb | tanuja333/Tensorflow_Keras |
Working with Rows Selecting one row by name | df.loc['A'] | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/01-Pandas-Crash-Course/02-DataFrames.ipynb | tanuja333/Tensorflow_Keras |
Selecting multiple rows by name | df.loc[['A','C']] | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/01-Pandas-Crash-Course/02-DataFrames.ipynb | tanuja333/Tensorflow_Keras |
Select single row by integer index location | df.iloc[0] | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/01-Pandas-Crash-Course/02-DataFrames.ipynb | tanuja333/Tensorflow_Keras |
Select multiple rows by integer index location | df.iloc[0:2] | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/01-Pandas-Crash-Course/02-DataFrames.ipynb | tanuja333/Tensorflow_Keras |
Remove row by name | df.drop('C',axis=0)
# NOT IN PLACE!
df | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/01-Pandas-Crash-Course/02-DataFrames.ipynb | tanuja333/Tensorflow_Keras |
Selecting subset of rows and columns at same time | df.loc[['A','C'],['W','Y']] | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/01-Pandas-Crash-Course/02-DataFrames.ipynb | tanuja333/Tensorflow_Keras |
Conditional SelectionAn important feature of pandas is conditional selection using bracket notation, very similar to numpy: | df
df>0
df[df>0]
df['X']>0
df[df['X']>0]
df[df['X']>0]['Y']
df[df['X']>0][['Y','Z']] | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/01-Pandas-Crash-Course/02-DataFrames.ipynb | tanuja333/Tensorflow_Keras |
For two conditions you can use | and & with parenthesis: | df[(df['W']>0) & (df['Y'] > 1)] | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/01-Pandas-Crash-Course/02-DataFrames.ipynb | tanuja333/Tensorflow_Keras |
More Index DetailsLet's discuss some more features of indexing, including resetting the index or setting it something else. We'll also talk about index hierarchy! | df
# Reset to default 0,1...n index
df.reset_index()
df
newind = 'CA NY WY OR CO'.split()
newind
df['States'] = newind
df
df.set_index('States')
df
df = df.set_index('States')
df | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/01-Pandas-Crash-Course/02-DataFrames.ipynb | tanuja333/Tensorflow_Keras |
DataFrame SummariesThere are a couple of ways to obtain summary data on DataFrames.df.describe() provides summary statistics on all numerical columns.df.info and df.dtypes displays the data type of all columns. | df.describe()
df.dtypes
df.info() | <class 'pandas.core.frame.DataFrame'>
Index: 5 entries, CA to CO
Data columns (total 4 columns):
W 5 non-null int32
X 5 non-null int32
Y 5 non-null int32
Z 5 non-null int32
dtypes: int32(4)
memory usage: 120.0+ bytes
| Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/01-Pandas-Crash-Course/02-DataFrames.ipynb | tanuja333/Tensorflow_Keras |
From this point, we will perform a round of exploration and visualization regarding the newfound external data. | traffic_exit = pd.read_hdf('../data/raw/traffic_exit_features.hdf', key='exit', mode='r')
traffic_entry = pd.read_hdf('../data/raw/traffic_entry_features.hdf', key='entry', mode='r')
traffic_entry.shape, traffic_exit.shape
traffic_entry.head(4).T | _____no_output_____ | MIT | notebooks/07_exploring_external_data.ipynb | vtoliveira/ey-nextwave-competition |
- AADT: Annual Average Daily Traffic (AADT), is the total volume of vehicle traffic. of a roadway for a year divided by 365 days.- K_FACTOR: is defined as the proportion of annual average daily traffic occurring in an hour. This factor is used for designing and analyzing the flow of traffic on highways.- ROUTE_ID: Inte... | 29.8% red, 74.1% green and 74.9% blue
fig, ax = plt.subplots(2, 1, figsize=(18, 15))
sns.set_style("whitegrid")
sns.distplot(traffic_entry.AADT_entry.dropna().values,
kde=False,
hist_kws={"linewidth": 3,
"alpha": 1,
"color": "coral"},
... | _____no_output_____ | MIT | notebooks/07_exploring_external_data.ipynb | vtoliveira/ey-nextwave-competition |
Intro to Hidden Markov Models (optional)--- IntroductionIn this notebook, you'll use the [Pomegranate](http://pomegranate.readthedocs.io/en/latest/index.html) library to build a simple Hidden Markov Model and explore the Pomegranate API.**Note:** You are not required to complete this notebook and it will not be submit... | # Jupyter "magic methods" -- only need to be run once per kernel restart
%load_ext autoreload
%aimport helpers
%autoreload 1
# import python modules -- this cell needs to be run again if you make changes to any of the files
import matplotlib.pyplot as plt
import numpy as np
from helpers import show_model
from pomegran... | _____no_output_____ | MIT | HMM warmup (optional).ipynb | umeshpai/parts_of_speech_tagging |
Build a Simple HMM---You will start by building a simple HMM network based on an example from the textbook [Artificial Intelligence: A Modern Approach](http://aima.cs.berkeley.edu/).> You are the security guard stationed at a secret under-ground installation. Each day, you try to guess whether it’s raining today, but ... | # create the HMM model
model = HiddenMarkovModel(name="Example Model") | _____no_output_____ | MIT | HMM warmup (optional).ipynb | umeshpai/parts_of_speech_tagging |
**IMPLEMENTATION**: Add the Hidden StatesWhen the HMM model is specified line-by-line, the object starts as an empty container. The first step is to name each state and attach an emission distribution. Observation Emission Probabilities: $P(Y_t | X_t)$We need to assume that we have some prior knowledge (possibly from ... | # create the HMM model
model = HiddenMarkovModel(name="Example Model")
# emission probability distributions, P(umbrella | weather)
sunny_emissions = DiscreteDistribution({"yes": 0.1, "no": 0.9})
sunny_state = State(sunny_emissions, name="Sunny")
# TODO: create a discrete distribution for the rainy emissions from the ... | Looks good so far!
| MIT | HMM warmup (optional).ipynb | umeshpai/parts_of_speech_tagging |
**IMPLEMENTATION:** Adding TransitionsOnce the states are added to the model, we can build up the desired topology of individual state transitions. Initial Probability $P(X_0)$:We will assume that we don't know anything useful about the likelihood of a sequence starting in either state. If the sequences start each wee... | # create edges for each possible state transition in the model
# equal probability of a sequence starting on either a rainy or sunny day
model.add_transition(model.start, sunny_state, 0.5)
model.add_transition(model.start, rainy_state, 0.5)
# add sunny day transitions (we already know estimates of these probabilities
... | Great! You've finished the model.
| MIT | HMM warmup (optional).ipynb | umeshpai/parts_of_speech_tagging |
Visualize the Network---We have provided a helper function called `show_model()` that generates a PNG image from a Pomegranate HMM network. You can specify an optional filename to save the file to disk. Setting the "show_ends" argument True will add the model start & end states that are included in every Pomegranate n... | show_model(model, figsize=(5, 5), filename="example.png", overwrite=True, show_ends=False) | _____no_output_____ | MIT | HMM warmup (optional).ipynb | umeshpai/parts_of_speech_tagging |
Checking the ModelThe states of the model can be accessed using array syntax on the `HMM.states` attribute, and the transition matrix can be accessed by calling `HMM.dense_transition_matrix()`. Element $(i, j)$ encodes the probability of transitioning from state $i$ to state $j$. For example, with the default column o... | column_order = ["Example Model-start", "Sunny", "Rainy", "Example Model-end"] # Override the Pomegranate default order
column_names = [s.name for s in model.states]
order_index = [column_names.index(c) for c in column_order]
# re-order the rows/columns to match the specified column order
transitions = model.dense_tra... | The state transition matrix, P(Xt|Xt-1):
[[ 0. 0.5 0.5 0. ]
[ 0. 0.8 0.2 0. ]
[ 0. 0.4 0.6 0. ]
[ 0. 0. 0. 0. ]]
The transition probability from Rainy to Sunny is 40%
| MIT | HMM warmup (optional).ipynb | umeshpai/parts_of_speech_tagging |
Inference in Hidden Markov Models---Before moving on, we'll use this simple network to quickly go over the Pomegranate API to perform the three most common HMM tasks:**Likelihood Evaluation**Given a model $\lambda=(A,B)$ and a set of observations $Y$, determine $P(Y|\lambda)$, the likelihood of observing that sequence... | # TODO: input a sequence of 'yes'/'no' values in the list below for testing
observations = ['yes', 'no', 'yes']
assert len(observations) > 0, "You need to choose a sequence of 'yes'/'no' observations to test"
# TODO: use model.forward() to calculate the forward matrix of the observed sequence,
# and then use np.exp()... | Rainy Sunny Example Model-start Example Model-end
<start> 0% 0% 100% 0%
yes 40% 5% 0% 0%
no 5% 18% 0% 0%
... | MIT | HMM warmup (optional).ipynb | umeshpai/parts_of_speech_tagging |
IMPLEMENTATION: Decoding the Most Likely Hidden State SequenceThe [Viterbi algorithm](https://en.wikipedia.org/wiki/Viterbi_algorithm) calculates the single path with the highest likelihood to produce a specific observation sequence. Pomegranate provides the `HMM.viterbi()` method to calculate both the hidden state se... | # TODO: input a sequence of 'yes'/'no' values in the list below for testing
observations = ['yes', 'no', 'yes']
# TODO: use model.viterbi to find the sequence likelihood & the most likely path
viterbi_likelihood, viterbi_path = model.viterbi(observations)
print("The most likely weather sequence to have generated " + ... | The most likely weather sequence to have generated these observations is ['Rainy', 'Sunny', 'Rainy'] at 2.30%.
| MIT | HMM warmup (optional).ipynb | umeshpai/parts_of_speech_tagging |
Forward likelihood vs Viterbi likelihoodRun the cells below to see the likelihood of each sequence of observations with length 3, and compare with the viterbi path. | from itertools import product
observations = ['no', 'no', 'yes']
p = {'Sunny': {'Sunny': np.log(.8), 'Rainy': np.log(.2)}, 'Rainy': {'Sunny': np.log(.4), 'Rainy': np.log(.6)}}
e = {'Sunny': {'yes': np.log(.1), 'no': np.log(.9)}, 'Rainy':{'yes':np.log(.8), 'no':np.log(.2)}}
o = observations
k = []
vprob = np.exp(model... | The likelihood of observing ['no', 'no', 'yes'] if the weather sequence is...
('Sunny', 'Sunny', 'Sunny') is 2.59%
('Sunny', 'Sunny', 'Rainy') is 5.18% <-- Viterbi path
('Sunny', 'Rainy', 'Sunny') is 0.07%
('Sunny', 'Rainy', 'Rainy') is 0.86%
('Rainy', 'Sunny', 'Sunny') is 0.29%
('Rainy', 'Sunny', 'Rainy') i... | MIT | HMM warmup (optional).ipynb | umeshpai/parts_of_speech_tagging |
Teste Técnico para Ciência de Dados da Keyrus 1ª parte: Análise Exploratória- [x] Tipos de variáveis- [x] Medidas de posição- [x] Medidas de dispersão- [x] Tratamento de Missing Values- [x] Gráficos- [x] Análise de Outliers 2ª parte: Estatística- [x] Estatística descritiva- [x] Identificação das distribuições das var... | # Data analysis and data wrangling
import numpy as np
import pandas as pd
# Plotting
import seaborn as sns
import matplotlib.pyplot as plt
import missingno as msno # missing values
# Preprocessing
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import PolynomialFeatures
# Machine Learning
f... | _____no_output_____ | MIT | notebooks/3-modelagem.ipynb | Srekin/Auto_Insurance |
Preparação do Diretório Principal | def prepare_directory_work(end_directory: str='notebooks'):
# Current path
curr_dir = os.path.dirname (os.path.realpath ("__file__"))
if curr_dir.endswith(end_directory):
os.chdir('..')
return curr_dir
return f'Current working directory: {curr_dir}'
prepare_directory_work(end_... | _____no_output_____ | MIT | notebooks/3-modelagem.ipynb | Srekin/Auto_Insurance |
Cell Format | config = configparser.ConfigParser()
config.read('src/visualization/plot_config.ini')
figure_titlesize = config['figure']['figure_titlesize']
figure_figsize_large = int(config['figure']['figure_figsize_large'])
figure_figsize_width = int(config['figure']['figure_figsize_width'])
figure_dpi = int(config['figure']['figu... | _____no_output_____ | MIT | notebooks/3-modelagem.ipynb | Srekin/Auto_Insurance |
Carregamento dos Dados | %%time
df_callcenter = pd.read_csv('data/cleansing/callcenter_marketing_clenning.csv',
encoding='utf8',
delimiter=',',
verbose=True)
df_callcenter.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 41167 entries, 0 to 41166
Data columns (total 15 columns):
idade 41167 non-null int64
profissao 41167 non-null int64
educacao 41167 non-null int64
meio_contato 41167 non-null int64
mes... | MIT | notebooks/3-modelagem.ipynb | Srekin/Auto_Insurance |
OBS: carragamento em quase metade do tempo em realação a versão original do arquivo csv. --- Variáveis Globais | # Lists that will be manipulated in the data processing
list_columns = []
list_categorical_col = []
list_numerical_col = []
list_without_target_col = []
def get_col(df: 'dataframe' = None,
type_descr: 'numpy' = np.number) -> list:
"""
Function get list columns
Args:
type_descr
... | Dataframe not contains <class 'object'> columns !
<class 'list'>
| MIT | notebooks/3-modelagem.ipynb | Srekin/Auto_Insurance |
Training and Testing Dataset- métrica: cross score | def cross_val_model(X,y, model, n_splits=3):
'Do split dataset and calculate cross_score'
print("Begin training", end='\n\n')
start = time.time()
X = np.array(X)
y = np.array(y)
folds = list(StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=2017).split(X, y))
for j, (train_... | _____no_output_____ | MIT | notebooks/3-modelagem.ipynb | Srekin/Auto_Insurance |
--- Modelos de Previsão- Modelo Baseline- Benckmarks Modelo Baseline- Vou começar com um baseline, sendo o mais simples possível. Linear Regression | # training model
X = df_callcenter[list_without_target_col]
y = df_callcenter['resultado']
print(X.shape)
print(y.shape)
# Visualize params
LinearRegression(n_jobs=-1)
# create model
lr_model = LinearRegression(n_jobs=-1, normalize=False)
# split dataset and calculate cross_score
cross_val_model(X, y, lr_model) | Begin training
Fit LinearRegression fold 1
cross_score: 0.81122
Fit LinearRegression fold 2
cross_score: 0.82172
Fit LinearRegression fold 3
cross_score: 0.82711
Training done! Time Elapsed: 0.32276058197021484 seconds.
| MIT | notebooks/3-modelagem.ipynb | Srekin/Auto_Insurance |
Linear Regression with Regularization | # create model
lr_ridge_model = Ridge()
# split dataset and calculate cross_score
cross_val_model(X, y, lr_ridge_model) | Begin training
Fit Ridge fold 1
cross_score: 0.81217
Fit Ridge fold 2
cross_score: 0.82215
Fit Ridge fold 3
cross_score: 0.82968
Training done! Time Elapsed: 0.17592835426330566 seconds.
| MIT | notebooks/3-modelagem.ipynb | Srekin/Auto_Insurance |
Polynomial Regression | poly = PolynomialFeatures(degree=2)
X_poly = poly.fit_transform(X)
print(X_poly.shape)
# split dataset and calculate cross_score
cross_val_model(X_poly, y, lr_model) | Begin training
Fit LinearRegression fold 1
cross_score: 0.80062
Fit LinearRegression fold 2
cross_score: 0.75551
Fit LinearRegression fold 3
cross_score: 0.56845
Training done! Time Elapsed: 4.029158353805542 seconds.
| MIT | notebooks/3-modelagem.ipynb | Srekin/Auto_Insurance |
Benckmarks RandomForest | # Visualize params
RandomForestClassifier()
# RandomForest params dict
rf_params_one = {}
rf_params_one['n_estimators'] = 10
rf_params_one['max_depth'] = 10
rf_params_one['min_samples_split'] = 10
rf_params_one['min_samples_leaf'] = 10 # end tree necessary 30 leaf
rf_params_one['n_jobs'] = -1 # run all process
# crea... | Begin training
Fit RandomForestClassifier fold 1
cross_score: 0.30151
Fit RandomForestClassifier fold 2
cross_score: 0.46162
Fit RandomForestClassifier fold 3
cross_score: 0.28610
Training done! Time Elapsed: 0.47094202041625977 seconds.
| MIT | notebooks/3-modelagem.ipynb | Srekin/Auto_Insurance |
Random Forest Regressor | # Visualize params
RandomForestRegressor()
# 1st model Random Forest
rf_regressor_one = RandomForestRegressor(n_jobs = -1,
verbose = 0)
# split dataset and calculate cross_score
cross_val_model(X, y, rf_regressor_one)
# 2st model Random Forest
rf_regressor_two = RandomForestReg... | Begin training
Fit RandomForestRegressor fold 1
cross_score: 0.77778
Fit RandomForestRegressor fold 2
cross_score: 0.82433
Fit RandomForestRegressor fold 3
cross_score: 0.84885
Training done! Time Elapsed: 37.298661947250366 seconds.
| MIT | notebooks/3-modelagem.ipynb | Srekin/Auto_Insurance |
Testing Web ApplicationsIn this chapter, we explore how to generate tests for Graphical User Interfaces (GUIs), notably on Web interfaces. We set up a (vulnerable) Web server and demonstrate how to systematically explore its behavior – first with hand-written grammars, then with grammars automatically inferred from t... | from bookutils import YouTubeVideo
YouTubeVideo('5agY5kg8Pvk') | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
**Prerequisites*** The techniques in this chapter make use of [grammars for fuzzing](Grammars.ipynb).* Basic knowledge of HTML and HTTP is required.* Knowledge of SQL databases is helpful. SynopsisTo [use the code provided in this chapter](Importing.ipynb), write```python>>> from fuzzingbook.WebFuzzer import ```and th... | from http.server import HTTPServer, BaseHTTPRequestHandler
from http.server import HTTPStatus # type: ignore
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
"""A simple HTTP server"""
pass | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
Taking OrdersFor our Web server, we need a number of Web pages:* We want one page where customers can place an order.* We want one page where they see their order confirmed. * Additionally, we need pages display error messages such as "Page Not Found". We start with the order form. The dictionary `FUZZINGBOOK_SWAG` ... | import bookutils
from typing import NoReturn, Tuple, Dict, List, Optional, Union
FUZZINGBOOK_SWAG = {
"tshirt": "One FuzzingBook T-Shirt",
"drill": "One FuzzingBook Rotary Hammer",
"lockset": "One FuzzingBook Lock Set"
} | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
This is the HTML code for the order form. The menu for selecting the swag to be ordered is created dynamically from `FUZZINGBOOK_SWAG`. We omit plenty of details such as precise shipping address, payment, shopping cart, and more. | HTML_ORDER_FORM = """
<html><body>
<form action="/order" style="border:3px; border-style:solid; border-color:#FF0000; padding: 1em;">
<strong id="title" style="font-size: x-large">Fuzzingbook Swag Order Form</strong>
<p>
Yes! Please send me at your earliest convenience
<select name="item">
"""
# (We don't use... | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
This is what the order form looks like: | from IPython.display import display
from bookutils import HTML
HTML(HTML_ORDER_FORM) | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
This form is not yet functional, as there is no server behind it; pressing "place order" will lead you to a nonexistent page. Order ConfirmationOnce we have gotten an order, we show a confirmation page, which is instantiated with the customer information submitted before. Here is the HTML and the rendering: | HTML_ORDER_RECEIVED = """
<html><body>
<div style="border:3px; border-style:solid; border-color:#FF0000; padding: 1em;">
<strong id="title" style="font-size: x-large">Thank you for your Fuzzingbook Order!</strong>
<p id="confirmation">
We will send <strong>{item_name}</strong> to {name} in {city}, {zip}<br>
A c... | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
Terms and ConditionsA Web site can only be complete if it has the necessary legalese. This page shows some terms and conditions. | HTML_TERMS_AND_CONDITIONS = """
<html><body>
<div style="border:3px; border-style:solid; border-color:#FF0000; padding: 1em;">
<strong id="title" style="font-size: x-large">Fuzzingbook Terms and Conditions</strong>
<p>
The content of this project is licensed under the
<a href="https://creativecommons.org/licens... | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
Storing Orders To store orders, we make use of a *database*, stored in the file `orders.db`. | import sqlite3
import os
ORDERS_DB = "orders.db" | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
To interact with the database, we use *SQL commands*. The following commands create a table with five text columns for item, name, email, city, and zip – the exact same fields we also use in our HTML form. | def init_db():
if os.path.exists(ORDERS_DB):
os.remove(ORDERS_DB)
db_connection = sqlite3.connect(ORDERS_DB)
db_connection.execute("DROP TABLE IF EXISTS orders")
db_connection.execute("CREATE TABLE orders "
"(item text, name text, email text, "
... | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
At this point, the database is still empty: | print(db.execute("SELECT * FROM orders").fetchall()) | []
| MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
We can add entries using the SQL `INSERT` command: | db.execute("INSERT INTO orders " +
"VALUES ('lockset', 'Walter White', "
"'white@jpwynne.edu', 'Albuquerque', '87101')")
db.commit() | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
These values are now in the database: | print(db.execute("SELECT * FROM orders").fetchall()) | [('lockset', 'Walter White', 'white@jpwynne.edu', 'Albuquerque', '87101')]
| MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
We can also delete entries from the table again (say, after completion of the order): | db.execute("DELETE FROM orders WHERE name = 'Walter White'")
db.commit()
print(db.execute("SELECT * FROM orders").fetchall()) | []
| MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
Handling HTTP RequestsWe have an order form and a database; now we need a Web server which brings it all together. The Python `http.server` module provides everything we need to build a simple HTTP server. A `HTTPRequestHandler` is an object that takes and processes HTTP requests – in particular, `GET` requests for ... | class SimpleHTTPRequestHandler(SimpleHTTPRequestHandler):
def do_GET(self):
try:
# print("GET " + self.path)
if self.path == "/":
self.send_order_form()
elif self.path.startswith("/order"):
self.handle_order()
elif self.path.sta... | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
Order FormAccessing the home page (i.e. getting the page at `/`) is simple: We go and serve the `html_order_form` as defined above. | class SimpleHTTPRequestHandler(SimpleHTTPRequestHandler):
def send_order_form(self):
self.send_response(HTTPStatus.OK, "Place your order")
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(HTML_ORDER_FORM.encode("utf8")) | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
Likewise, we can send out the terms and conditions: | class SimpleHTTPRequestHandler(SimpleHTTPRequestHandler):
def send_terms_and_conditions(self):
self.send_response(HTTPStatus.OK, "Terms and Conditions")
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(HTML_TERMS_AND_CONDITIONS.encode("utf8")) | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
Processing Orders When the user clicks `Submit` on the order form, the Web browser creates and retrieves a URL of the form```/order?field_1=value_1&field_2=value_2&field_3=value_3```where each `field_i` is the name of the field in the HTML form, and `value_i` is the value provided by the user. Values use the CGI enco... | import urllib.parse
class SimpleHTTPRequestHandler(SimpleHTTPRequestHandler):
def get_field_values(self):
# Note: this fails to decode non-ASCII characters properly
query_string = urllib.parse.urlparse(self.path).query
# fields is { 'item': ['tshirt'], 'name': ['Jane Doe'], ...}
fie... | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
The method `handle_order()` takes these values from the URL, stores the order, and returns a page confirming the order. If anything goes wrong, it sends an internal server error. | class SimpleHTTPRequestHandler(SimpleHTTPRequestHandler):
def handle_order(self):
values = self.get_field_values()
self.store_order(values)
self.send_order_received(values) | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
Storing the order makes use of the database connection defined above; we create an SQL command instantiated with the values as extracted from the URL. | class SimpleHTTPRequestHandler(SimpleHTTPRequestHandler):
def store_order(self, values):
db = sqlite3.connect(ORDERS_DB)
# The following should be one line
sql_command = "INSERT INTO orders VALUES ('{item}', '{name}', '{email}', '{city}', '{zip}')".format(**values)
self.log_message("... | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
After storing the order, we send the confirmation HTML page, which again is instantiated with the values from the URL. | class SimpleHTTPRequestHandler(SimpleHTTPRequestHandler):
def send_order_received(self, values):
# Should use html.escape()
values["item_name"] = FUZZINGBOOK_SWAG[values["item"]]
confirmation = HTML_ORDER_RECEIVED.format(**values).encode("utf8")
self.send_response(HTTPStatus.OK, "Or... | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
Other HTTP commandsBesides the `GET` command (which does all the heavy lifting), HTTP servers can also support other HTTP commands; we support the `HEAD` command, which returns the head information of a Web page. In our case, this is always empty. | class SimpleHTTPRequestHandler(SimpleHTTPRequestHandler):
def do_HEAD(self):
# print("HEAD " + self.path)
self.send_response(HTTPStatus.OK)
self.send_header("Content-type", "text/html")
self.end_headers() | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
Error HandlingWe have defined pages for submitting and processing orders; now we also need a few pages for errors that might occur. Page Not FoundThis page is displayed if a non-existing page (i.e. anything except `/` or `/order`) is requested. | HTML_NOT_FOUND = """
<html><body>
<div style="border:3px; border-style:solid; border-color:#FF0000; padding: 1em;">
<strong id="title" style="font-size: x-large">Sorry.</strong>
<p>
This page does not exist. Try our <a href="/">order form</a> instead.
</p>
</div>
</body></html>
"""
HTML(HTML_NOT_FOUND) | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
The method `not_found()` takes care of sending this out with the appropriate HTTP status code. | class SimpleHTTPRequestHandler(SimpleHTTPRequestHandler):
def not_found(self):
self.send_response(HTTPStatus.NOT_FOUND, "Not found")
self.send_header("Content-type", "text/html")
self.end_headers()
message = HTML_NOT_FOUND
self.wfile.write(message.encode("utf8")) | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
Internal ErrorsThis page is shown for any internal errors that might occur. For diagnostic purposes, we have it include the traceback of the failing function. | HTML_INTERNAL_SERVER_ERROR = """
<html><body>
<div style="border:3px; border-style:solid; border-color:#FF0000; padding: 1em;">
<strong id="title" style="font-size: x-large">Internal Server Error</strong>
<p>
The server has encountered an internal error. Go to our <a href="/">order form</a>.
<pre>{error_messag... | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
LoggingOur server runs as a separate process in the background, waiting to receive commands at all time. To see what it is doing, we implement a special logging mechanism. The `httpd_message_queue` establishes a queue into which one process (the server) can store Python objects, and in which another process (the not... | from multiprocess import Queue # type: ignore
HTTPD_MESSAGE_QUEUE = Queue() | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
Let us place two messages in the queue: | HTTPD_MESSAGE_QUEUE.put("I am another message")
HTTPD_MESSAGE_QUEUE.put("I am one more message") | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
To distinguish server messages from other parts of the notebook, we format them specially: | from bookutils import rich_output, terminal_escape
def display_httpd_message(message: str) -> None:
if rich_output():
display(
HTML(
'<pre style="background: NavajoWhite;">' +
message +
"</pre>"))
else:
print(terminal_escape(message))
d... | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
The method `print_httpd_messages()` prints all messages accumulated in the queue so far: | def print_httpd_messages():
while not HTTPD_MESSAGE_QUEUE.empty():
message = HTTPD_MESSAGE_QUEUE.get()
display_httpd_message(message)
import time
time.sleep(1)
print_httpd_messages() | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
With `clear_httpd_messages()`, we can silently discard all pending messages: | def clear_httpd_messages() -> None:
while not HTTPD_MESSAGE_QUEUE.empty():
HTTPD_MESSAGE_QUEUE.get() | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
The method `log_message()` in the request handler makes use of the queue to store its messages: | class SimpleHTTPRequestHandler(SimpleHTTPRequestHandler):
def log_message(self, format: str, *args) -> None:
message = ("%s - - [%s] %s\n" %
(self.address_string(),
self.log_date_time_string(),
format % args))
HTTPD_MESSAGE_QUEUE.put(message... | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
In [the chapter on carving](Carver.ipynb), we had introduced a `webbrowser()` method which retrieves the contents of the given URL. We now extend it such that it also prints out any log messages produced by the server: | import requests
def webbrowser(url: str, mute: bool = False) -> str:
"""Download and return the http/https resource given by the URL"""
try:
r = requests.get(url)
contents = r.text
finally:
if not mute:
print_httpd_messages()
else:
clear_httpd_message... | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
With `webbrowser()`, we are now ready to get the Web server up and running. End of Excursion Running the ServerWe run the server on the *local host* – that is, the same machine which also runs this notebook. We check for an accessible port and put the resulting URL in the queue created earlier. | def run_httpd_forever(handler_class: type) -> NoReturn: # type: ignore
host = "127.0.0.1" # localhost IP
for port in range(8800, 9000):
httpd_address = (host, port)
try:
httpd = HTTPServer(httpd_address, handler_class)
break
except OSError:
continue... | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
The function `start_httpd()` starts the server in a separate process, which we start using the `multiprocess` module. It retrieves its URL from the message queue and returns it, such that we can start talking to the server. | from multiprocess import Process
def start_httpd(handler_class: type = SimpleHTTPRequestHandler) \
-> Tuple[Process, str]:
clear_httpd_messages()
httpd_process = Process(target=run_httpd_forever, args=(handler_class,))
httpd_process.start()
httpd_url = HTTPD_MESSAGE_QUEUE.get()
return http... | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
Let us now start the server and save its URL: | httpd_process, httpd_url = start_httpd()
httpd_url | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
Interacting with the ServerLet us now access the server just created. Direct Browser AccessIf you are running the Jupyter notebook server on the local host as well, you can now access the server directly at the given URL. Simply open the address in `httpd_url` by clicking on the link below.**Note**: This only works ... | def print_url(url: str) -> None:
if rich_output():
display(HTML('<pre><a href="%s">%s</a></pre>' % (url, url)))
else:
print(terminal_escape(url))
print_url(httpd_url) | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
Even more convenient, you may be able to interact directly with the server using the window below. **Note**: This only works if you are running the Jupyter notebook server on the local host. | from IPython.display import IFrame
IFrame(httpd_url, '100%', 230) | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
After interaction, you can retrieve the messages produced by the server: | print_httpd_messages() | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
We can also see any orders placed in the `orders` database (`db`): | print(db.execute("SELECT * FROM orders").fetchall()) | []
| MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
And we can clear the order database: | db.execute("DELETE FROM orders")
db.commit() | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
Retrieving the Home PageEven if our browser cannot directly interact with the server, the _notebook_ can. We can, for instance, retrieve the contents of the home page and display them: | contents = webbrowser(httpd_url)
HTML(contents) | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
Placing OrdersTo test this form, we can generate URLs with orders and have the server process them. The method `urljoin()` puts together a base URL (i.e., the URL of our server) and a path – say, the path towards our order. | from urllib.parse import urljoin, urlsplit
urljoin(httpd_url, "/order?foo=bar") | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
With `urljoin()`, we can create a full URL that is the same as the one generated by the browser as we submit the order form. Sending this URL to the browser effectively places the order, as we can see in the server log produced: | contents = webbrowser(urljoin(httpd_url,
"/order?item=tshirt&name=Jane+Doe&email=doe%40example.com&city=Seattle&zip=98104")) | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
The web page returned confirms the order: | HTML(contents) | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
And the order is in the database, too: | print(db.execute("SELECT * FROM orders").fetchall()) | [('tshirt', 'Jane Doe', 'doe@example.com', 'Seattle', '98104')]
| MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
Error MessagesWe can also test whether the server correctly responds to invalid requests. Nonexistent pages, for instance, are correctly handled: | HTML(webbrowser(urljoin(httpd_url, "/some/other/path"))) | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
You may remember we also have a page for internal server errors. Can we get the server to produce this page? To find this out, we have to test the server thoroughly – which we do in the remainder of this chapter. Fuzzing Input FormsAfter setting up and starting the server, let us now go and systematically test it – ... | import string
def cgi_encode(s: str, do_not_encode: str = "") -> str:
ret = ""
for c in s:
if (c in string.ascii_letters or c in string.digits
or c in "$-_.+!*'()," or c in do_not_encode):
ret += c
elif c == ' ':
ret += '+'
else:
ret +=... | _____no_output_____ | MIT | docs/notebooks/WebFuzzer.ipynb | vrthra-forks/fuzzingbook |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.