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 |
|---|---|---|---|---|---|
**Expected Output**: **x.shape**: (4, 3, 3, 2) **x_pad.shape**: (4, 7, 7, 2) **x[1,1]**: [[ 0.90085595 -0.68372786] [-0.12289023 -0.93576943]... | # GRADED FUNCTION: conv_single_step
def conv_single_step(a_slice_prev, W, b):
"""
Apply one filter defined by parameters W on a single slice (a_slice_prev) of the output activation
of the previous layer.
Arguments:
a_slice_prev -- slice of input data of shape (f, f, n_C_prev)
W -- Weight ... | Z = -6.99908945068
| MIT | _posts/DS/Deep-Learning/Deep-Learning-Coursera/4. Convolutional Neural Networks/Convolution model - Step by Step - v2.ipynb | wansook0316/wansook.github.io |
**Expected Output**: **Z** -6.99908945068 3.3 - Convolutional Neural Networks - Forward passIn the forward pass, you will take many filters and convolve them on the input. Each 'convolution' gives you a 2D matrix output. You will then stack these outputs to... | # GRADED FUNCTION: conv_forward
def conv_forward(A_prev, W, b, hparameters):
"""
Implements the forward propagation for a convolution function
Arguments:
A_prev -- output activations of the previous layer, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev)
W -- Weights, numpy array of shap... | Z's mean = 0.0489952035289
Z[3,2,1] = [-0.61490741 -6.7439236 -2.55153897 1.75698377 3.56208902 0.53036437
5.18531798 8.75898442]
cache_conv[0][1][2][3] = [-0.20075807 0.18656139 0.41005165]
| MIT | _posts/DS/Deep-Learning/Deep-Learning-Coursera/4. Convolutional Neural Networks/Convolution model - Step by Step - v2.ipynb | wansook0316/wansook.github.io |
**Expected Output**: **Z's mean** 0.0489952035289 **Z[3,2,1]** [-0.61490741 -6.7439236 -2.55153897 1.75698377 3.56208902 0.53036437 5.18531798 8.75898442] **cache_conv... | # GRADED FUNCTION: pool_forward
def pool_forward(A_prev, hparameters, mode = "max"):
"""
Implements the forward pass of the pooling layer
Arguments:
A_prev -- Input data, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev)
hparameters -- python dictionary containing "f" and "stride"
mod... | mode = max
A = [[[[ 1.74481176 0.86540763 1.13376944]]]
[[[ 1.13162939 1.51981682 2.18557541]]]]
mode = average
A = [[[[ 0.02105773 -0.20328806 -0.40389855]]]
[[[-0.22154621 0.51716526 0.48155844]]]]
| MIT | _posts/DS/Deep-Learning/Deep-Learning-Coursera/4. Convolutional Neural Networks/Convolution model - Step by Step - v2.ipynb | wansook0316/wansook.github.io |
**Expected Output:** A = [[[[ 1.74481176 0.86540763 1.13376944]]] [[[ 1.13162939 1.51981682 2.18557541]]]] A = [[[[ 0.02105773 -0.20328806 -0.40389855]]] [[[-0.22154621 0.51716526 0.48155844]]]] Congratulations! You have now i... | def conv_backward(dZ, cache):
"""
Implement the backward propagation for a convolution function
Arguments:
dZ -- gradient of the cost with respect to the output of the conv layer (Z), numpy array of shape (m, n_H, n_W, n_C)
cache -- cache of values needed for the conv_backward(), output of conv... | dA_mean = 1.45243777754
dW_mean = 1.72699145831
db_mean = 7.83923256462
| MIT | _posts/DS/Deep-Learning/Deep-Learning-Coursera/4. Convolutional Neural Networks/Convolution model - Step by Step - v2.ipynb | wansook0316/wansook.github.io |
** Expected Output: ** **dA_mean** 1.45243777754 **dW_mean** 1.72699145831 **db_mean** 7.83923256462 5.2 Pooling layer - backward pas... | def create_mask_from_window(x):
"""
Creates a mask from an input matrix x, to identify the max entry of x.
Arguments:
x -- Array of shape (f, f)
Returns:
mask -- Array of the same shape as window, contains a True at the position corresponding to the max entry of x.
"""
###... | x = [[ 1.62434536 -0.61175641 -0.52817175]
[-1.07296862 0.86540763 -2.3015387 ]]
mask = [[ True False False]
[False False False]]
| MIT | _posts/DS/Deep-Learning/Deep-Learning-Coursera/4. Convolutional Neural Networks/Convolution model - Step by Step - v2.ipynb | wansook0316/wansook.github.io |
**Expected Output:** **x =**[[ 1.62434536 -0.61175641 -0.52817175] [-1.07296862 0.86540763 -2.3015387 ]] **mask =**[[ True False False] [False False False]] Why do we keep track of the position of the max? It's because this is the input value that ultimately influenced the output, and therefore the cost. Backpro... | def distribute_value(dz, shape):
"""
Distributes the input value in the matrix of dimension shape
Arguments:
dz -- input scalar
shape -- the shape (n_H, n_W) of the output matrix for which we want to distribute the value of dz
Returns:
a -- Array of size (n_H, n_W) for which we dis... | distributed value = [[ 0.5 0.5]
[ 0.5 0.5]]
| MIT | _posts/DS/Deep-Learning/Deep-Learning-Coursera/4. Convolutional Neural Networks/Convolution model - Step by Step - v2.ipynb | wansook0316/wansook.github.io |
**Expected Output**: distributed_value =[[ 0.5 0.5] [ 0.5 0.5]] 5.2.3 Putting it together: Pooling backward You now have everything you need to compute backward propagation on a pooling layer.**Exercise**: Implement the `pool_backward` function in both modes (`"max"` and `"average"`). You will once again use 4 for... | def pool_backward(dA, cache, mode = "max"):
"""
Implements the backward pass of the pooling layer
Arguments:
dA -- gradient of cost with respect to the output of the pooling layer, same shape as A
cache -- cache output from the forward pass of the pooling layer, contains the layer's input and h... | mode = max
mean of dA = 0.145713902729
dA_prev[1,1] = [[ 0. 0. ]
[ 5.05844394 -1.68282702]
[ 0. 0. ]]
mode = average
mean of dA = 0.145713902729
dA_prev[1,1] = [[ 0.08485462 0.2787552 ]
[ 1.26461098 -0.25749373]
[ 1.17975636 -0.53624893]]
| MIT | _posts/DS/Deep-Learning/Deep-Learning-Coursera/4. Convolutional Neural Networks/Convolution model - Step by Step - v2.ipynb | wansook0316/wansook.github.io |
**Expected Output**: mode = max: **mean of dA =**0.145713902729 **dA_prev[1,1] =** [[ 0. 0. ] [ 5.05844394 -1.68282702] [ 0. 0. ]]mode = average **mean of dA =**0.145713902729 **dA_prev[1,1] =** [[ 0.08485462 0.2787552 ] [ 1.26461098 -0.25749373] [ 1.17975636 -0.53624893]] Co... | !tar cvfz notebook.tar.gz *
!tar cvfz notebook.tar.gz * | Convolution model - Application - v1-Copy1.ipynb
Convolution model - Application - v1.ipynb
Convolution model - Step by Step - v1.ipynb
Convolution model - Step by Step - v2-Copy1.ipynb
Convolution model - Step by Step - v2.ipynb
__pycache__/
__pycache__/cnn_utils.cpython-36.pyc
cnn_utils.py
datasets/
datasets/train_si... | MIT | _posts/DS/Deep-Learning/Deep-Learning-Coursera/4. Convolutional Neural Networks/Convolution model - Step by Step - v2.ipynb | wansook0316/wansook.github.io |
Ciência de dados - Unidade 3*Por: Débora Azevedo, Eliseu Jayro, Francisco de Paiva e Igor Brandão* ObjetivosO objetivo desse projeto é explorar os [datasets da UFRN](http://dados.ufrn.br/group/despesas-e-orcamento) contendo informações sobre requisições de material, requisições de manutenção e empenhos sob o contexto ... | !pip install pandas
!pip install numpy
!pip install matplotlib
!pip install wordcloud | Requirement already satisfied: pandas in c:\users\usuario\anaconda3\envs\tfp36\lib\site-packages (0.23.4)
Requirement already satisfied: python-dateutil>=2.5.0 in c:\users\usuario\anaconda3\envs\tfp36\lib\site-packages (from pandas) (2.7.5)
Requirement already satisfied: pytz>=2011k in c:\users\usuario\anaconda3\envs\t... | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
1 - Lendo os datasetsNessa seção nós iremos importar os datasets contendo informações sobre requisiçoes de manutenção, requisições de material de serviço e empenhos, todos disponíveis no site de dados da UFRN.Na célula abaixo nós definimos uma lista com os arquivos que iremos precisar, lemos todos eles e os guardamos ... | import pandas as pd
from os import path
# Lista com o nome dos arquivos de todos os datasets que iremos utilizar
dataset_names = ['requisicaomanutencao.csv', 'requisicaomaterialservico.csv', 'empenhos.csv']
# Pasta em que os datasets se encontram
dataset_path = 'datasets'
# Dicionário onde eles serão armazenados
dat... | _____no_output_____ | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
2 - Explorando e limpando os datasetsNessa seção é feita a análise das diferentes colunas dos datasets para identificar seus significados e suas utilidades para os problemas que iremos analisar. Sendo feita essa análise, nós então limpamos os datasets para que eles se tornem mais legíveis e mais fáceis de manusear. 2... | maintenance_data = data['requisicaomanutencao']
print(maintenance_data.head())
print(maintenance_data.divisao.unique()) | numero ano divisao \
0 7075 2018 Serviços Gerais
1 7074 2018 Serviços Gerais
2 7073 2018 Serviços Gerais
3 7072 2018 Serviços Gerais
4 7071 2018... | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
2.11 - Descrevendo as colunas e valoresObservando o resultado da célula acima, podemos fazer as seguintes conclusões sobre as colunas:- numero: ID da requisição, não é relevante para o problema.- **ano**: Ano em que foi feita requisição de manutenção- **divisão**: Diz a divisão para qual a manutenção foi requisitada, ... | def remove_cols(df_input, dropped_columns):
'''
This functions receives a dataframe and a list of column names as input. It checks if each column exist,
and if they do, they're removed.
'''
for dropped_column in dropped_columns:
if dropped_column in df_input:
df_input = df_input.... | _____no_output_____ | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
2.13 - Removendo outliers e valores desnecessáriosAqui iremos analisar os valores do nosso dataset e determinar quais podemos remover ou modificar de modo a facilitar a nossa análise. | print(maintenance_data.status.value_counts()) | FINALIZADA 67211
AGUARDANDO_EXECUCAO 3649
ATENDIDA 1471
NEGADA 1383
AUTORIZADA 957
CADASTRADA 794
EM ROTA VISITA 759
ESTOR... | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
**Observação:**Checando os status, podemos perceber que a maioria dos valores ocorrem um número muito pequeno de vezes e não precisamos deles para nossa análise, portanto iremos eliminar os valores com 800 ocorrências ou menos | maintenance_data = maintenance_data.groupby('status').filter(lambda x: len(x) > 800)
maintenance_data.status.value_counts() | _____no_output_____ | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
**Observação:**Sobram portanto 5 valores possíveis para a coluna **status**. Porém, para nossa análise de custos, precisamos saber apenas se a requisição foi negada ou autorizada. Analisando os status restantes, podemos considerar que toda requisição que tiver valor diferente de negada pode ser considerada como autoriz... | def convert_status(status_val):
'''Converts the value of all strings in the status column to AUTORIZADA, unless their value is NEGADA.'''
if status_val == 'NEGADA':
return status_val
else:
return 'AUTORIZADA'
maintenance_data['status'] = maintenance_data['status'].apply(convert_status)
main... | <class 'pandas.core.frame.DataFrame'>
Int64Index: 74671 entries, 13 to 80339
Data columns (total 10 columns):
ano 74671 non-null int64
divisao 74652 non-null object
id_unidade_requisitante 74671 non-null int64
nome_unidade_requisitante 74671 non-null object
id_unida... | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
2.14 - Lidando com valores nulosAqui nós utilizaremos o método [pandas.DataFrame.info](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.info.html) para verificar quais os valores nulos das colunas de nosso dataset. A partir disso, dependendo da quantidade de colunas com valores nulos e do tipo d... | maintenance_data.info()
maintenance_data.divisao.value_counts() | <class 'pandas.core.frame.DataFrame'>
Int64Index: 74671 entries, 13 to 80339
Data columns (total 10 columns):
ano 74671 non-null int64
divisao 74652 non-null object
id_unidade_requisitante 74671 non-null int64
nome_unidade_requisitante 74671 non-null object
id_unida... | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
**Observação**Utilizando o método [pandas.DataFrame.info](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.info.html) percebemos que existem muitos valores **NULL** na coluna *local* e alguns poucos na coluna *divisao*. Para a coluna *local*, iremos preencher as linhas **nulas** com seus valores ... | import numpy as np
maintenance_data['local'] = np.where(maintenance_data.local.isnull(), maintenance_data.nome_unidade_custo, maintenance_data.local)
maintenance_data['divisao'] = maintenance_data['divisao'].fillna('Outros')
maintenance_data.info()
# Resultado final da limpeza
maintenance_data.head() | _____no_output_____ | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
2.2 - Requisição de material de serviçoEsse dataset lista todas as requisições de materiais e serviços contratados pela UFRN desde 2008. | material_request_data = data['requisicaomaterialservico']
print('===== Primeiras linhas =====')
print(material_request_data.head())
print('===== Contagem de valores de natureza_despesa =====')
print(material_request_data.natureza_despesa.value_counts())
print('===== Contagem de valores de status =====')
print(material_... | ===== Primeiras linhas =====
numero ano id_unidade_requisitante \
0 1786 2018 160
1 1785 2018 2640
2 1784 2018 1481
3 1783 2018 6799
4 1782 2018 4894
nome_unidade... | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
2.21 - Descrevendo as colunas e valoresObservando o resultado da célula acima, podemos fazer as seguintes conclusões sobre as colunas:- numero: ID da requisição, não é relevante.- **ano**: Ano em que foi feita a requisição.- **id_unidade_requisitante**: ID da unidade que fez a requisição, toda unidade tem um ID único.... | material_dropped = ['numero' ,'natureza_despesa', 'numero_contrato']
material_request_data = remove_cols(material_request_data, material_dropped)
print(material_request_data.head()) | ano id_unidade_requisitante nome_unidade_requisitante \
0 2018 160 DEPARTAMENTO DE ECONOMIA - DEPEC
1 2018 2640 SETOR DE COMPRAS E MANUTENÇÃO - CCSA
2 2018 1481 PRÓ-REITORIA DE PESQUISA
3 2018 ... | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
2.23 - Removendo outliers e valores desnecessáriosAqui iremos analisar os dados do nosso dataset e determinar quais podemos remover ou modificar de modo a facilitar a nossa análise. | print(material_request_data.status.value_counts()) | LIQUIDADA 11645
EM_LIQUIDACAO 5988
ENVIADA 5335
ESTORNADA 2856
FINALIZADA 1543
CADASTRADA 695
A_EMPENHAR 144
EMPENHO_ANULADO 139
NEGADA 136
PENDENTE ATENDIMENTO 45
PENDENTE AUTORIZAÇÃO... | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
**Observação:**Verificando a contagem de valores da coluna *status*, percebemos que grande parte dos valores possíveis tem um número muito pequeno de ocorrências no dataset. Esses valores com poucas ocorrências influenciam pouco na nossa análise, portanto iremos eliminá-los. | allowed_status = ['LIQUIDADA', 'EM_LIQUIDACAO', 'ENVIADA', 'ESTORNADA', 'FINALIZADA', 'CADASTRADA']
material_request_data = material_request_data[material_request_data.status.isin(allowed_status)]
print(material_request_data.status.value_counts()) | LIQUIDADA 11645
EM_LIQUIDACAO 5988
ENVIADA 5335
ESTORNADA 2856
FINALIZADA 1543
CADASTRADA 695
Name: status, dtype: int64
| MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
2.24 - Lidando com valores nulosAqui nós utilizaremos o método [pandas.DataFrame.info](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.info.html) para verificar quais os valores nulos das colunas de nosso dataset. A partir disso, dependendo da quantidade de colunas com valores nulos e do tipo d... | material_request_data.info()
material_request_data[material_request_data.data_envio.isnull()].head(n=20) | <class 'pandas.core.frame.DataFrame'>
Int64Index: 28062 entries, 0 to 28599
Data columns (total 10 columns):
ano 28062 non-null int64
id_unidade_requisitante 28062 non-null int64
nome_unidade_requisitante 28062 non-null object
id_unidade_custo 28062 non-null int64
nome_unida... | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
- **data_envio**: Possui vários valores nulos. Como a maioria deles está bem separado um do outro e o dataset está ordenado por data, podemos preenchê-los usando o valor dessa coluna em linhas anteriores.- **observacoes**: Algumas observações também tem valores nulos, iremos simplesmente settar esses para uma string va... | material_request_data.data_envio = material_request_data.data_envio.fillna(method='ffill')
material_request_data.observacoes = material_request_data.observacoes.fillna('')
material_request_data.info() | <class 'pandas.core.frame.DataFrame'>
Int64Index: 28062 entries, 0 to 28599
Data columns (total 10 columns):
ano 28062 non-null int64
id_unidade_requisitante 28062 non-null int64
nome_unidade_requisitante 28062 non-null object
id_unidade_custo 28062 non-null int64
nome_unida... | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
2.3 - EmpenhosDataset contendo a relação de todos os empenhos efetuados pela UFRN desde 2001.O empenho da despesa importa em deduzir do saldo de determinada dotação orçamentária a parcela necessária à execução das atividades do órgão. É a forma de comprometimento de recursos orçamentários. Nenhuma despesa poderá ser r... | empenhos_data = data['empenhos']
print(empenhos_data.head())
print(empenhos_data.data.value_counts()) | cod_empenho ano modalidade id_unidade_gestora \
0 8000116 2018 ordinário 440
1 803463 2018 estimativo 605
2 803457 2018 ordinário 605
3 803449 2018 ordinário 605
4 803448 2018 ordinário ... | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
2.31 - Descrevendo as colunas e valores- cod_empenho: ID do empenho;- **ano**: Ano em que foi solicitado o empenho;- **modalidade**: O empenho da despesa pode assumir três tipos diferentes: - a) Ordinário – a despesa com valor exato deve ser liquidada e paga de uma única vez; - b) Estimativo – O valor total da ... | empenhos_dropped = ['cod_empenho', 'processo', 'documento_associado', 'licitacao', 'convenio', 'observacoes']
empenhos_data = remove_cols(empenhos_data, empenhos_dropped)
print(empenhos_data.head()) | ano modalidade id_unidade_gestora \
4809 2017 global 605
4810 2017 global 605
4811 2017 ordinário 605
4812 2017 ordinário 605
4813 2017 ordinário 605
nome_unidade_gestora... | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
2.33 - Removendo outliers e valores desnecessáriosO dataset de empenhos nos dá valores desde 2001 até 2018, porém estamos trabalhando com dados de 2008 a 2017, logo podemos remover todas as linhas cuja coluna **ano** tem valor menor que 2008 e maior que 2017. | # Defining a vector with the years we'll analyse
years = [2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017]
empenhos_data = empenhos_data[empenhos_data.ano.isin(years)] | _____no_output_____ | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
2.34 - Lidando com valores nulosAqui nós utilizaremos o método [pandas.DataFrame.info](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.info.html) para verificar quais os valores nulos das colunas de nosso dataset. A partir disso, dependendo da quantidade de colunas com valores nulos e do tipo d... | empenhos_data.info()
empenhos_data[empenhos_data.valor_anulado.notnull()].head() | <class 'pandas.core.frame.DataFrame'>
Int64Index: 158860 entries, 4809 to 163668
Data columns (total 16 columns):
ano 158860 non-null int64
modalidade 158860 non-null object
id_unidade_gestora 158860 non-null int64
nome_unidade_gestora 158860 non-null obj... | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
**Observação**:As colunas **valor_anulado**, **valor_reforcado** e **valor_cancelado** todas possuem uma quantidade muito pequena de valores não-nulos. Como as colunas **valor_empenho** e **saldo_empenho** possuem todos os valores, nós não precisamos das outras para fazermos nossa análise, logo podemos dropá-las. | valores_drop = ['valor_reforcado', 'valor_anulado', 'valor_cancelado']
empenhos_data = remove_cols(empenhos_data, valores_drop)
empenhos_data.head() | _____no_output_____ | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
3 - Visualizando os dadosNessa seção iremos utilizar a biblioteca *matplotlib* para plottar gráficos a fim de visualizar nossos dados. 3.1 - Orçamento da UFRNEm nossa análise, iremos utilizar os dados do valor total de repasses do governo federal para a UFRN de 2006 a 2018 para comparar investimentos da universidade ... | import matplotlib.pyplot as plt
%matplotlib inline
years = [2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017]
budget = [62010293, 136021308, 203664331, 172999177, 221801098, 246858171, 228864259, 207579799, 230855480, 186863902]
# Plottagem do orçamento da UFRN de 2008 a 2017, podemos perceber que caiu em to... | _____no_output_____ | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
3.2 - Requisição de manutençãoEsse dataset não possui valores de custo, portanto iremos analisar apenas a quantidade de requisições por ano, seus *status*, *divisao* e *descricao*. | autorized_count_year = []
denied_count_year = []
for year in years:
status_count = maintenance_data[maintenance_data.ano == year].status.value_counts()
autorized_count_year.append(status_count['AUTORIZADA'])
denied_count_year.append(status_count['NEGADA'])
import datetime
from matplotlib.dates import date2... | _____no_output_____ | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
3.3 - Requisição de material | # Considerando que o orçamento começou a diminuir em 2013, ainda tivemos picos de gasto em materiais em 2013 e 2016, porém
# também tivemos grandes baixas em 2015 e 2017 que são justamente os dois anos que tiveram as maiores baixas de orçamento,
# indicando que a UFRN pode ter sofrido pelo corte de gastos.
material_sp... | _____no_output_____ | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
3.4 - Empenhos | valor_year = []
saldo_year = []
for year in years:
valor_year.append(empenhos_data[empenhos_data.ano == year].valor_empenho.sum() / 1000000)
saldo_year.append(empenhos_data[empenhos_data.ano == year].saldo_empenho.sum() / 1000000)
plt.plot(years, valor_year, 'r', label='Valor pedido')
plt.scatter(years, v... | _____no_output_____ | MIT | empenhos_requests_ufrn_budget.ipynb | igorabrandao/UFRN-budget-application |
Deconvolution Tutorial IntroductionThere are several problems with the standard initialization performed in the [Quickstart Guide](../0-quickstart.ipynb):1. The models exist in a frame with a narrow model PSF while the the observed scene will have a much wider PSF. So the initial models will be spread out over a large... | # Import Packages and setup
from functools import partial
import numpy as np
import scarlet
import scarlet.display as display
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
# use a good colormap and don't interpolate the pixels
matplotlib.rc('image', cmap='inferno', interpolation='none', origin=... | _____no_output_____ | MIT | docs/tutorials/deconvolution.ipynb | Majoburo/spaxlet |
Load and Display DataWe load the same example data set used in the quickstart guide. | # Load the sample images
data = np.load("../../data/hsc_cosmos_35.npz")
images = data["images"]
filters = data["filters"]
catalog = data["catalog"]
weights = 1/data["variance"]
# Note that unlike in the quickstart guide,
# we set psfs the data["psfs"] image
# not a scarlet.PSF object.
psfs = data["psfs"] | _____no_output_____ | MIT | docs/tutorials/deconvolution.ipynb | Majoburo/spaxlet |
Generate the PSF modelsUnlike the [Quickstart Guide](../0-quickstart.ipynb), we cannot use the pixel integrated model PSF because the [error function](https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.special.erf.html) in scipy used to integrate the gaussian goes to zero too quickly to match an observe... | py, px = np.array(psfs.shape[1:])//2
model_psf = scarlet.psf.gaussian(py, px, 1/np.sqrt(2), bbox=scarlet.Box(psfs.shape), integrate=False)[0]
model_psf = model_psf/model_psf.sum()
model_psf = np.array([model_psf]*psfs.shape[0])
model_frame = scarlet.Frame(psfs.shape,channels=filters)
psf_observation = scarlet.PsfObser... | _____no_output_____ | MIT | docs/tutorials/deconvolution.ipynb | Majoburo/spaxlet |
Matching the PSFs AlgorithmTo understand how the matching algorithm works it is useful to understand how convolutions are performed in scarlet. We can define the observed PSF $P$ by convolving the model PSF $M$ with the difference kernel $D$, giving us$P = M * D$,where `*` is the convolution operator. The difference k... | # Parameters used to initial and configure the fit.
max_iter = 300
e_rel = 1e-5
morph_step = 1e-2
# We should be able to improve our initial guess if we model the
# width of the observed PSF and calculate an analytic solution
# for the deconvolution kernel, however for now just using the
# observed PSF works well.
init... | _____no_output_____ | MIT | docs/tutorials/deconvolution.ipynb | Majoburo/spaxlet |
The residual is created by convolving the observed PSF with the deconvolution kernel and comparing it to the model PSF. We see that the kernel isn't perfect and that it tends to overshoot the center of the model PSF, but the result is good enough to improve our initialization. One thing that we've noticed is that if we... | # This is the frame for our model
model_psf = scarlet.PSF(partial(scarlet.psf.gaussian, sigma=1/np.sqrt(2)), shape=(None, 11, 11))
model_frame = scarlet.Frame(
images.shape,
psfs=model_psf,
channels=filters)
# This object will perform the deconvolution
deconvolved = scarlet.Deconvol... | _____no_output_____ | MIT | docs/tutorials/deconvolution.ipynb | Majoburo/spaxlet |
Let's take a look at the result: | model = deconvolved.images
fig, ax = plt.subplots(1, 2, figsize=(15,7))
norm = display.AsinhMapping(minimum=np.min(images), stretch=np.max(images)*0.055, Q=10)
rgb = display.img_to_rgb(images, norm=norm)
ax[0].imshow(rgb)
ax[0].set_title("Observed")
for center in catalog:
ax[0].plot(center[1], center[0], "wx")
n... | _____no_output_____ | MIT | docs/tutorials/deconvolution.ipynb | Majoburo/spaxlet |
In the case the result isn't great due to the bright star at the center. We could try to fit the model a bit better to supress the ringing but it turns out this is usually unnecessary and not worth the extra computation time.To see how this is useful lets take a look at the detection coadds for the brightest 3 sources ... | # We just define a rough estimate of the background RMS needed
# for `build_detection_coadd`.
bg_rms=np.zeros((len(images),))
bg_rms[:] = 1e-3
for center in catalog[:4]:
center = (center[1], center[0])
figure, ax = plt.subplots(1, 2, figsize=(10, 5))
# Build the deconvolved coadd
sed = scarlet.source.ge... | _____no_output_____ | MIT | docs/tutorials/deconvolution.ipynb | Majoburo/spaxlet |
We see that the ringing in the PSF doesn't really matter, as it's at the same amplitude as the noise and our initial requirement of monotonicity will trim the model to the inner region that doesn't ring, achieving our goal of making the initial models compact and allowing them to grow if necessary. So next we'll initia... | # Build the sources without deconvolution
sources = []
for k,src in enumerate(catalog):
if k == 1:
new_source = scarlet.MultiComponentSource(model_frame, (src['y'], src['x']), observation)
else:
new_source = scarlet.ExtendedSource(model_frame, (src['y'], src['x']), observation)
sources.appen... | _____no_output_____ | MIT | docs/tutorials/deconvolution.ipynb | Majoburo/spaxlet |
Notice that the deconvovled initial models use much smaller boxes while still capturing all of the features in the true observations. The better initial guess and smaller boxes will make it much faster to deblend: | # Fit the non-deconvolved blend
blend = scarlet.Blend(sources, observation)
%time blend.fit(200)
print("scarlet ran for {0} iterations to logL = {1}".format(len(blend.loss), -blend.loss[-1]))
plt.plot(-np.array(blend.loss))
plt.title("Regular initialization")
plt.xlabel('Iteration')
plt.ylabel('log-Likelihood')
plt.sho... | _____no_output_____ | MIT | docs/tutorials/deconvolution.ipynb | Majoburo/spaxlet |
So we see that using the deconvolved images for initialization cut our runtime in half for this particular blend (this difference might not be as pronounced in the notebook environment because the default initialization is executed first, heating up the processors before the second blend is run). Looking at the residua... | norm = display.AsinhMapping(minimum=np.min(images), stretch=np.max(images)*0.055, Q=10)
# Display the convolved model
scarlet.display.show_scene(blend.sources,
norm=norm,
observation=observation,
show_rendered=True,
... | _____no_output_____ | MIT | docs/tutorials/deconvolution.ipynb | Majoburo/spaxlet |
Fast GP implementations | %matplotlib inline
%config InlineBackend.figure_format = 'retina'
from matplotlib import rcParams
rcParams["figure.dpi"] = 100
rcParams["figure.figsize"] = 12, 4 | _____no_output_____ | MIT | Sessions/Session13/Day2/02-Fast-GPs.ipynb | Messicka/LSSTC-DSFP-Sessions |
Benchmarking GP codesImplemented the right way, GPs can be super fast! Let's compare the time it takes to evaluate our GP likelihood and the time it takes to evaluate the likelihood computed with the snazzy ``george`` and ``celerite`` packages. We'll learn how to use both along the way. Let's create a large, fake data... | import numpy as np
np.random.seed(0)
t = np.linspace(0, 10, 10000)
y = np.random.randn(10000)
sigma = np.ones(10000) | _____no_output_____ | MIT | Sessions/Session13/Day2/02-Fast-GPs.ipynb | Messicka/LSSTC-DSFP-Sessions |
Our GP | def ExpSquaredCovariance(t, A=1.0, l=1.0, tprime=None):
"""
Return the ``N x M`` exponential squared
covariance matrix.
"""
if tprime is None:
tprime = t
TPrime, T = np.meshgrid(tprime, t)
return A ** 2 * np.exp(-0.5 * (T - TPrime) ** 2 / l ** 2)
def ln_gp_likelihood(t, y, sig... | _____no_output_____ | MIT | Sessions/Session13/Day2/02-Fast-GPs.ipynb | Messicka/LSSTC-DSFP-Sessions |
Time to evaluate the GP likelihood: | %%time
ln_gp_likelihood(t, y, sigma) | CPU times: user 1min 41s, sys: 3.82 s, total: 1min 45s
Wall time: 18 s
| MIT | Sessions/Session13/Day2/02-Fast-GPs.ipynb | Messicka/LSSTC-DSFP-Sessions |
george Let's time how long it takes to do the same operation using the ``george`` package (``pip install george``).The kernel we'll use is```pythonkernel = amp ** 2 * george.kernels.ExpSquaredKernel(tau ** 2)```where ``amp = 1`` and ``tau = 1`` in this case.To instantiate a GP using ``george``, simply run```pythongp =... | import george
%%time
kernel = george.kernels.ExpSquaredKernel(1.0)
gp = george.GP(kernel)
gp.compute(t, sigma)
%%time
print(gp.log_likelihood(y)) | -14095.32136897017
CPU times: user 294 ms, sys: 50.5 ms, total: 345 ms
Wall time: 128 ms
| MIT | Sessions/Session13/Day2/02-Fast-GPs.ipynb | Messicka/LSSTC-DSFP-Sessions |
``george`` also offers a fancy GP solver called the HODLR solver, which makes some approximations that dramatically speed up the matrix algebra. Let's instantiate the GP object again by passing the keyword ``solver=george.HODLRSolver`` and re-compute the log likelihood. How long did that take? Did we get the same value... | %%time
gp = george.GP(kernel, solver=george.HODLRSolver)
gp.compute(t, sigma)
%%time
gp.log_likelihood(y) | CPU times: user 6.74 ms, sys: 3.29 ms, total: 10 ms
Wall time: 8.94 ms
| MIT | Sessions/Session13/Day2/02-Fast-GPs.ipynb | Messicka/LSSTC-DSFP-Sessions |
celerite The ``george`` package is super useful for GP modeling, and I recommend you read over the [docs and examples](https://george.readthedocs.io/en/latest/). It implements several different [kernels](https://george.readthedocs.io/en/latest/user/kernels/) that come in handy in different situations, and it has suppo... | import celerite
from celerite import terms
%%time
kernel = terms.Matern32Term(np.log(1), np.log(1))
gp = celerite.GP(kernel)
gp.compute(t, sigma)
%%time
gp.log_likelihood(y) | _____no_output_____ | MIT | Sessions/Session13/Day2/02-Fast-GPs.ipynb | Messicka/LSSTC-DSFP-Sessions |
Exercise (the one and only)Let's use what we've learned about GPs in a real application: fitting an exoplanet transit model in the presence of correlated noise.Here is a (fictitious) light curve for a star with a transiting planet: | import matplotlib.pyplot as plt
t, y, yerr = np.loadtxt("data/sample_transit.txt", unpack=True)
plt.errorbar(t, y, yerr=yerr, fmt=".k", capsize=0)
plt.xlabel("time")
plt.ylabel("relative flux"); | _____no_output_____ | MIT | Sessions/Session13/Day2/02-Fast-GPs.ipynb | Messicka/LSSTC-DSFP-Sessions |
Introduction: Prediction Engineering: Labeling Historical ExamplesIn this notebook, we will develop a method for labeling customer transactions data for a customer churn prediction problem. The objective of labeling is to create a set of historical examples of what we want to predict based on the business need: in thi... | import numpy as np
import pandas as pd | _____no_output_____ | Apache-2.0 | bootcamps/automl/featuretools_predict-customer-churn/churn/2. Prediction Engineering.ipynb | yobibytes/quant_trading |
Data Storage All of the data is stored and written to AWS S3. The work was completed on AWS EC2 instances which makes retrieving and writing data to S3 extremely fast. The data is publicly readable from the bucket but you'll have to configure AWS with your credentials. * For reading, run `aws configure` from the comma... | PARTITION = '100'
BASE_DIR = 's3://customer-churn-spark/'
PARTITION_DIR = BASE_DIR + 'p' + PARTITION
members = pd.read_csv(f'{PARTITION_DIR}/members.csv',
parse_dates=['registration_init_time'], infer_datetime_format = True)
trans = pd.read_csv(f'{PARTITION_DIR}/transactions.csv',
... | _____no_output_____ | Apache-2.0 | bootcamps/automl/featuretools_predict-customer-churn/churn/2. Prediction Engineering.ipynb | yobibytes/quant_trading |
The transactions table is all we will need to make labels. The next cell is needed for writing data back to S3. | import s3fs
# Credentials
with open('/data/credentials.txt', 'r') as f:
info = f.read().strip().split(',')
key = info[0]
secret = info[1]
fs = s3fs.S3FileSystem(key=key, secret=secret) | _____no_output_____ | Apache-2.0 | bootcamps/automl/featuretools_predict-customer-churn/churn/2. Prediction Engineering.ipynb | yobibytes/quant_trading |
Churn for One CustomerThe function below takes in a single customer's transactions along with a number of parameters that define the prediction problem. * `prediction_date`: when we want to make predictions* `churn_days`: the number of days without a membership required for a churn* `lead_time`: how long in advance to... | def label_customer(customer_id, customer_transactions, prediction_date, churn_days,
lead_time = 1, prediction_window = 1, return_trans = False):
"""
Make label times for a single customer. Returns a dataframe of labels with times, the binary label,
and the number of days until the next ... | _____no_output_____ | Apache-2.0 | bootcamps/automl/featuretools_predict-customer-churn/churn/2. Prediction Engineering.ipynb | yobibytes/quant_trading |
Let's take a look at the output of this function for a typical customer. We'll take the use case of making predictions on the first of each month with 31 days required for a churn, a lead time of 1 month, and a prediction window of 1 month. | CUSTOMER_ID = trans.iloc[8, 0]
customer_transactions = trans.loc[trans['msno'] == CUSTOMER_ID].copy()
label_times, cust_transactions = label_customer(CUSTOMER_ID, customer_transactions,
prediction_date = 'MS', churn_days = 31,
... | _____no_output_____ | Apache-2.0 | bootcamps/automl/featuretools_predict-customer-churn/churn/2. Prediction Engineering.ipynb | yobibytes/quant_trading |
To make sure the function worked, we'll want to take a look at the transactions. | cust_transactions.iloc[3:10, -7:] | _____no_output_____ | Apache-2.0 | bootcamps/automl/featuretools_predict-customer-churn/churn/2. Prediction Engineering.ipynb | yobibytes/quant_trading |
We see that the churn occurred on 2016-03-16 as the customer went 98 days between an active membership from 2016-02-14 to 2016-05-22. The actual churn occurs 31 days from when the membership expires. The churn is only associated with one cutoff time, 2016-02-01. This corresponds to the lead time and prediction window a... | CUSTOMER_ID = trans.iloc[100, 0]
customer_transactions = trans.loc[trans['msno'] == CUSTOMER_ID].copy()
label_times, cust_transactions = label_customer(CUSTOMER_ID, customer_transactions,
prediction_date = 'SMS', churn_days = 14,
... | _____no_output_____ | Apache-2.0 | bootcamps/automl/featuretools_predict-customer-churn/churn/2. Prediction Engineering.ipynb | yobibytes/quant_trading |
There are several times when we can't determine if the customer churned or not because of the way the problem has been set up. | cust_transactions.iloc[:10, -7:] | _____no_output_____ | Apache-2.0 | bootcamps/automl/featuretools_predict-customer-churn/churn/2. Prediction Engineering.ipynb | yobibytes/quant_trading |
Looking at the churn on 2016-03-15, it was assigned to the `cutoff_time` of 2016-03-01 as expected with a lead time of two weeks and a prediction window of two weeks. (For churns that occur at the end of one prediction window and the beginning of the next, we assign it to the one where it occurs on the beginning of the... | def make_label_times(transactions, prediction_date, churn_days,
lead_time = 1, prediction_window = 1,):
"""
Make labels for an entire series of transactions.
Params
--------
transactions (dataframe): table of customer transactions
prediction_date (str): time at ... | _____no_output_____ | Apache-2.0 | bootcamps/automl/featuretools_predict-customer-churn/churn/2. Prediction Engineering.ipynb | yobibytes/quant_trading |
Let's look at examples of using this function for both prediction problems. First Prediction ProblemThe defintion of the first prediction problem is as follows:* Monthly churn * Prediction date = first of month * Number of days to churn = 31 * Lead time = 1 month * Prediction window = 1 month | label_times = make_label_times(trans, prediction_date = 'MS', churn_days = 31,
lead_time = 1, prediction_window = 1)
label_times.tail(10)
label_times.shape
label_times['label'].value_counts()
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('fivethirtyeight')
label_times... | _____no_output_____ | Apache-2.0 | bootcamps/automl/featuretools_predict-customer-churn/churn/2. Prediction Engineering.ipynb | yobibytes/quant_trading |
This is an imbalanced classification problem. There are far more instances of customers not churning than of customers churning. This is not necessarily an issue as long as we are smart about the choices of metrics we use for modeling. Second Prediction ProblemTo demonstrate how to quickly change the problem parameter... | label_times = make_label_times(trans, prediction_date = 'SMS', churn_days = 14,
lead_time = 1, prediction_window = 1)
label_times.tail(10)
label_times.shape
label_times['label'].value_counts().plot.bar(color = 'r');
plt.xlabel('Label'); plt.ylabel('Count'); plt.title('Label Distribution w... | _____no_output_____ | Apache-2.0 | bootcamps/automl/featuretools_predict-customer-churn/churn/2. Prediction Engineering.ipynb | yobibytes/quant_trading |
There are quite a few missing labels, which occur when there is no next transaction for the customer (we don't know if the last entry for the customer is a churn or not). We won't be able to use these examples when training a model although we can make predictions for them. Parallelizing LabelingNow that we have a fun... | def partition_to_labels(partition_number, prediction_dates = ['MS', 'SMS'], churn_periods= [31, 14],
lead_times = [1, 1], prediction_windows = [1, 1]):
"""Make labels for all customers in one partition
Either for one month or twice a month
Params
--------
partition (... | _____no_output_____ | Apache-2.0 | bootcamps/automl/featuretools_predict-customer-churn/churn/2. Prediction Engineering.ipynb | yobibytes/quant_trading |
Spark for ParallelizationThe below code uses Spark to parallelize the label making. This particular implementation uses a single machine although the same idea can be extended to a cluster of machines. | import findspark
findspark.init('/usr/local/spark/')
import pyspark
conf = pyspark.SparkConf()
# Enable logging
conf.set('spark.eventLog.enabled', True);
conf.set('spark.eventLog.dir', '/data/churn/tmp/');
# Use all cores on a single machine
conf.set('spark.num.executors', 1)
conf.set('spark.executor.memory', '56g'... | _____no_output_____ | Apache-2.0 | bootcamps/automl/featuretools_predict-customer-churn/churn/2. Prediction Engineering.ipynb | yobibytes/quant_trading |
While Spark is running, you can navigate to localhost:4040 to see the details of the particular job, or to localhost:8080 to see the overview of the cluster. This is useful for diagnosing the state of a spark operation. | print(f'{round(end - start)} seconds elapsed.')
labels = pd.read_csv(f's3://customer-churn-spark/p980/MS-31_labels.csv')
labels.tail(10)
labels = pd.read_csv(f's3://customer-churn-spark/p980/SMS-14_labels.csv')
labels.tail(10) | _____no_output_____ | Apache-2.0 | bootcamps/automl/featuretools_predict-customer-churn/churn/2. Prediction Engineering.ipynb | yobibytes/quant_trading |
ReferenceData Camp course Course Description* A typical organization loses an estimated 5% of its yearly revenue to fraud. * Apply supervised learning algorithms to detect fraudulent behavior similar to past ones,as well as unsupervised learning methods to discover new types of fraud activities. * Deal with highly im... | import pandas as pd
df = pd.read_csv("creditcard_sampledata_3.csv")
#This is dieferent from the data in the course. But it will be corrected
#in the following cells.
occ = df['Class'].value_counts() #good for counting categorical data
print(occ)
print(occ / len(df.index)) | 0 5000
1 50
Name: Class, dtype: int64
0 0.990099
1 0.009901
Name: Class, dtype: float64
| MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
Plotting your dataVisualize the fraud to non-fraud ratio. | import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv("creditcard_sampledata_3.csv")
#print(df.columns) #It is not df.colnames.
df = df.drop(['Unnamed: 0'],axis = 1)
# print(df.head())
y=df['Class'].values
X=df.drop(['Class'],axis = 1).values
def plot_data(X, y):
plt.scatter(X[y == 0, 0], X[y == 0,... | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
Applying SMOTE* Re-balance the data using the Synthetic Minority Over-sampling Technique (SMOTE). * Unlike ROS, SMOTE does not create exact copies of observations, but creates new, synthetic, samples that are quite similar to the existing observations in the minority class. * Visualize the result and compare it to the... | import matplotlib.pyplot as plt
import pandas as pd
from imblearn.over_sampling import SMOTE
df = pd.read_csv("creditcard_sampledata_3.csv")
#print(df.columns) #It is not df.colnames.
df = df.drop(['Unnamed: 0'],axis = 1)
# print(df.head())
y=df['Class'].values
X=df.drop(['Class'],axis = 1).values
#my code above
meth... | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
Compare SMOTE to original data* Compare those results of SMOTE to the original data, to get a good feeling for what has actually happened.* Have a look at the value counts again of our old and new data, and let's plot the two scatter plots of the data side by side. * Use the function compare_plot() (not defined here),... | print(pd.value_counts(pd.Series(y)))
print(pd.value_counts(pd.Series(y_resampled)))
compare_plot(X, y, X_resampled, y_resampled, method='SMOTE')
# This fundtion is not defined here. But the result picture is as below
#The compare_plot should be implemented by the subplot defined on dataframe, or by the subplot way su... | 0 5000
1 50
dtype: int64
1 5000
0 5000
dtype: int64
| MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
 Exploring the traditional way to catch fraud* Try finding fraud cases in our credit card dataset the "old way". First you'll define threshold values using common statistics, to split fraud and non-fraud. Then, use those thresholds on your features to detect fraud. This is common practice wit... | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from imblearn.over_sampling import SMOTE
df = pd.read_csv("creditcard_sampledata_3.csv")
#print(df.columns) #It is not df.colnames.
df = df.drop(['Unnamed: 0'],axis = 1)
#print(df.head())
y=df['Class'].values
X=df.drop(['Class'],axis = 1).values
#m... | Flagged Fraud 0 1
Actual Fraud
0 4984 16
1 28 22
| MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
Not bad, with this rule, we detect 22 out of 50 fraud cases, but can't detect the other 28, and get 16 false positives. In the next exercise, we'll see how this measures up to a machine learning model. Using ML classification to catch fraud* Use a simple machine learning model on our credit card data instead.* Imple... | from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
# Fit a logistic regression m... | C:\Users\ljyan\Anaconda3\lib\site-packages\sklearn\linear_model\logistic.py:433: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.
FutureWarning)
| MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
* We are getting much less false positives, so that's an improvement. * We're catching a higher percentage of fraud cases, so that is also better than before. Logistic regression combined with SMOTE | # This is the pipeline module we need for this from imblearn
from imblearn.pipeline import Pipeline
# Define which resampling method and which ML model to use in the pipeline
resampling = SMOTE(kind='borderline2')
model = LogisticRegression()
# Define the pipeline, tell it to combine SMOTE with the Logistic Regressi... | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
Using a pipelineTreat the pipeline as if it were a single machine learning model. Our data X and y are already defined, and the pipeline is defined in the previous exercise. | # Split your data X and y, into a training and a test set and fit the pipeline onto the training data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
# Fit your pipeline onto your training set and obtain predictions by fitting the model onto the test data
pipeline.fit(X_train,... | Classifcation report:
precision recall f1-score support
0 1.00 1.00 1.00 1505
1 0.67 1.00 0.80 10
micro avg 1.00 1.00 1.00 1515
macro avg 0.83 1.00 0.90 1515
weighted avg 1.00 ... | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
* The SMOTE slightly improves our results. We now manage to find all cases of fraud, but we have a slightly higher number of false positives, albeit only 7 cases.* Remember, not in all cases does resampling necessarily lead to better results. **When the fraud cases are very spread and scattered over the data, using SMO... | import matplotlib.pyplot as plt
import pandas as pd
from imblearn.over_sampling import SMOTE
df = pd.read_csv("creditcard_sampledata_2.csv")
#print(df.columns) #It is not df.colnames.
df = df.drop(['Unnamed: 0'],axis = 1)
# print(df.head())
y=df['Class'].values
X=df.drop(['Class'],axis = 1).values
#extra code above
#... | 95.8904109589041
| MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
This tells us that by doing nothing, we would be correct in 95.9% of the cases. So now you understand, that if we get an accuracy of less than this number, our model does not actually add any value in predicting how many cases are correct. Random Forest Classifier - part 1 | print(X.shape)
print(y.shape)
from sklearn.ensemble import RandomForestClassifier
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
model = RandomForestClassifier(random_state=5) | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
Random Forest Classifier - part 2See how our Random Forest model performs without doing anything special to it. | model.fit(X_train, y_train)
predicted = model.predict(X_test)
from sklearn.metrics import accuracy_score
model.fit(X_train, y_train)
predicted = model.predict(X_test)
print(accuracy_score(y_test, predicted)) | C:\Users\ljyan\Anaconda3\lib\site-packages\sklearn\ensemble\forest.py:246: FutureWarning: The default value of n_estimators will change from 10 in version 0.20 to 100 in 0.22.
"10 in version 0.20 to 100 in 0.22.", FutureWarning)
| MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
Performance metrics for the RF model* In the previous exercises you obtained an accuracy score for your random forest model. This time, we know accuracy can be misleading in the case of fraud detection. * With highly imbalanced fraud data, the AUROC curve is a more reliable performance metric, used to compare differen... | from sklearn.metrics import classification_report, confusion_matrix, roc_auc_score
predicted = model.predict(X_test)
probs = model.predict_proba(X_test)
# Print the ROC curve, classification report and confusion matrix
print(roc_auc_score(y_test, probs[:,1]))
print(classification_report(y_test, predicted))
print(con... | 0.9397777068096268
precision recall f1-score support
0 0.99 1.00 1.00 2099
1 0.97 0.80 0.88 91
micro avg 0.99 0.99 0.99 2190
macro avg 0.98 0.90 0.94 2190
weighted avg 0.99 ... | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
You have now obtained more meaningful performance metrics that tell us how well the model performs, given the highly imbalanced data that you're working with. The model predicts 76 cases of fraud, out of which 73 are actual fraud. You have only 3 false positives. This is really good, and as a result you have a very hig... | from sklearn.metrics import average_precision_score
# Calculate average precision and the PR curve
average_precision = average_precision_score(y_test, predicted)
# Calculate average precision and the PR curve
average_precision = average_precision_score(y_test, predicted)
# Obtain precision and recall
precision, reca... | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
 Model adjustments* A simple way to adjust the random forest model to deal with highly imbalanced fraud data, is to use the **class_weights option **when defining your sklearn model. However, as you will see, it is a bit of a blunt force mechanism and might not work for your very special case... | model = RandomForestClassifier(class_weight='balanced_subsample', random_state=5)
model.fit(X_train, y_train)
# Obtain the predicted values and probabilities from the model
predicted = model.predict(X_test)
probs = model.predict_proba(X_test)
print(roc_auc_score(y_test, probs[:,1]))
print(classification_report(y_te... | 0.9463271364176556
precision recall f1-score support
0 0.99 1.00 1.00 2099
1 0.99 0.80 0.88 91
micro avg 0.99 0.99 0.99 2190
macro avg 0.99 0.90 0.94 2190
weighted avg 0.99 ... | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
* The model results don't improve drastically. We now have 3 less false positives, but now 19 in stead of 18 false negatives, i.e. cases of fraud we are not catching. If we mostly care about catching fraud, and not so much about the false positives, this does actually not improve our model at all, albeit a simple optio... | # Change the model options
model = RandomForestClassifier(bootstrap=True, class_weight={0:1, 1:12}, criterion='entropy',
max_depth=10,
min_samples_leaf=10,
# Change the number of trees to use
n_estimators=20, n_jobs=-1, random_state=5)
#... | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
* By smartly defining more options in the model, you can obtain better predictions. You have effectively reduced the number of false negatives, i.e. you are catching more cases of fraud, whilst keeping the number of false positives low. * In this exercise you've manually changed the options of the model. There is a sma... | from sklearn.model_selection import GridSearchCV
# Define the parameter sets to test
param_grid = {'n_estimators': [1, 30], 'max_features': ['auto', 'log2'], 'max_depth': [4, 8], 'criterion': ['gini', 'entropy']
}
model = RandomForestClassifier(random_state=5)
CV_model = GridSearchCV(estimator=model, param_grid=param... | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
Model results using GridSearchCV* You discovered that the best parameters for your model are that the split criterion should be set to 'gini', the number of estimators (trees) should be 30, the maximum depth of the model should be 8 and the maximum features should be set to "log2".* Let's give this a try and see how w... | # Input the optimal parameters in the model
model = RandomForestClassifier(class_weight={0:1,1:12}, criterion='gini',
max_depth=8, max_features='log2', min_samples_leaf=10, n_estimators=30, n_jobs=-1, random_state=5)
# Get results from your model
# get_model_results(X_train, y_train, X_test, y_test, model) | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
output: precision recall f1-score support 0.0 0.99 1.00 1.00 2099 1.0 0.95 0.84 0.89 91 micro avg 0.99 0.99 0.99 2190 macro avg 0.97 0.92 0.94 2190 weighted avg ... | # Define the Logistic Regression model with weights
model = LogisticRegression(class_weight={0:1, 1:15}, random_state=5)
# Get the model results
# get_model_results(X_train, y_train, X_test, y_test, model) | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
precision recall f1-score support 0.0 0.99 0.98 0.99 2099 1.0 0.63 0.88 0.73 91` micro avg 0.97 0.97 0.97 2190 macro avg 0.81 0.93 0.86 2190weighted avg 0.98 0.97 0.98 2190`... | from sklearn.ensemble import VotingClassifier
from sklearn.tree import DecisionTreeClassifier
# Define the three classifiers to use in the ensemble
clf1 = LogisticRegression(class_weight={0:1, 1:15}, random_state=5)
clf2 = RandomForestClassifier(class_weight={0:1, 1:12}, criterion='gini', max_depth=8, max_features='lo... | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
output: precision recall f1-score support 0.0 0.99 1.00 0.99 2099 1.0 0.90 0.86 0.88 91 micro avg 0.99 0.99 0.99 2190 macro avg 0.95 0.93 0.94 2190 weighted avg ... | ensemble_model = VotingClassifier(estimators=[('lr', clf1), ('rf', clf2), ('gnb', clf3)], voting='soft', weights=[1, 4, 1], flatten_transform=True)
# Get results
# get_model_results(X_train, y_train, X_test, y_test, ensemble_model) | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
output: precision recall f1-score support 0.0 0.99 1.00 1.00 2099 1.0 0.94 0.85 0.89 91 micro avg 0.99 0.99 0.99 2190 macro avg 0.97 0.92 0.94 2190 weighted avg ... | import pandas as pd
df = pd.read_csv('banksim.csv')
df = df.drop(['Unnamed: 0'],axis = 1)
print(df.head())
print(df.groupby('category').mean()) | age gender category amount fraud
0 3 F es_transportation 49.71 0
1 4 F es_health 39.29 0
2 3 F es_transportation 18.76 0
3 4 M es_transportation 13.95 0
4 2 M es_transportation 49.87 0
amount ... | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
Even from simple group by, we can find that the majority of fraud is observed in travel, leisure and sports related transactions. Customer segmentation* Check whether there are any obvious patterns for the clients in this data, thus whether you need to segment your data into groups, or whether the data is rather homo... | # Group by age groups and get the mean
print(df.groupby('age').mean())
# Group by age groups and get the mean
df.groupby('age').mean()
# Count the values of the observations in each age group
print(df['age'].value_counts()) | 2 2333
3 1718
4 1279
5 792
1 713
6 314
0 40
U 11
Name: age, dtype: int64
| MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
* Does it make sense to divide your data into age segments before running a fraud detection algorithm? * No, the age groups who are the largest are relatively similar. As you can see the average amount spent as well as fraud occurrence is rather similar across groups. Age group '0' stands out but since there are only ... | # Create two dataframes with fraud and non-fraud data
df_fraud = df.loc[df.fraud == 1]
df_non_fraud = df.loc[df.fraud == 0]
# Plot histograms of the amounts in fraud and non-fraud data
plt.hist(df_fraud.amount, alpha=0.5, label='fraud')
plt.hist(df_non_fraud.amount, alpha=0.5, label='nonfraud')
plt.legend()
plt.sho... | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
* As the number fraud observations is much smaller, it is difficult to see the full distribution. * Nonetheless, you can see that the fraudulent transactions tend to be on the larger side relative to normal observations.* This helps us later in detecting fraud from non-fraud. In the next chapter you're going to impleme... | import pandas as pd
df = pd.read_csv('banksim_adj.csv')
X = df.drop(['Unnamed: 0'],axis = 1).values
y = df['fraud'].values
print(df.head())
#extra code above. The data might not be same as the DataCamp
from sklearn.preprocessing import MinMaxScaler
X = np.array(df).astype(np.float)
scaler = MinMaxScaler()
X_scaled ... | Unnamed: 0 age amount fraud M es_barsandrestaurants es_contents \
0 0 3 49.71 0 0 0 0
1 1 4 39.29 0 0 0 0
2 2 3 18.76 0 0 0 0
3 3 ... | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
K-means clustering* For fraud detection, K-means clustering is straightforward to implement and relatively powerful in predicting suspicious cases. It is a good algorithm to start with when working on fraud detection problems. * However, fraud data is oftentimes very large, especially when you are working with transac... | # Import MiniBatchKmeans
from sklearn.cluster import MiniBatchKMeans
kmeans = MiniBatchKMeans(n_clusters=8, random_state=0)
kmeans.fit(X_scaled) | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
Elbow method* It is important to get the number of clusters right, especially when you want to **use the outliers of those clusters as fraud predictions**. * Apply the Elbow method and see what the optimal number of clusters should be based on this method. | clustno = range(1, 10)
kmeans = [MiniBatchKMeans(n_clusters=i) for i in clustno]
score = [kmeans[i].fit(X_scaled).score(X_scaled) for i in range(len(kmeans))]
plt.plot(clustno, score)
plt.xlabel('Number of Clusters')
plt.ylabel('Score')
plt.title('Elbow Curve')
plt.show() | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
The optimal number of clusters should probably be at around 3 clusters, as that is where the elbow is in the curve. Detecting outliers* Use the K-means algorithm to predict fraud, and compare those predictions to the actual labels that are saved, to sense check our results.* The fraudulent transactions are typically ... | X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.3, random_state=0)
kmeans = MiniBatchKMeans(n_clusters=3, random_state=42).fit(X_train)
X_test_clusters = kmeans.predict(X_test)
X_test_clusters_centers = kmeans.cluster_centers_
dist = [np.linalg.norm(x-y) for x, y in zip(X_test, X_test_clu... | 2157
2157
[2 1 1 ... 2 2 2]
--------------------
[[0.46208979 0.50503256 0.11993546 0.0071048 1. 0.01243339
0.0017762 0.01420959 0.02664298 0. 0. 0.0017762
0.01243339 0. 0.0017762 0.0053286 0.0017762 0.89520426
0. ]
[0.58159793 0.49215686 0.36850912 0.18823529 0.270588... | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
Checking model resultsIn the previous exercise you've flagged all observations to be fraud, if they are in the top 5th percentile in distance from the cluster centroid. I.e. these are the very outliers of the three clusters. For this exercise you have the scaled data and labels already split into training and test set... | # Obtain the ROC score
print(roc_auc_score(y_test, km_y_pred))
#output: 0.8197704982668266
# Obtain the ROC score
print(roc_auc_score(y_test, km_y_pred))
# Create a confusion matrix
km_cm = confusion_matrix(y_test, km_y_pred)
# Plot the confusion matrix in a figure to visualize results
# plot_confusion_matrix(km_cm) | 0.934936176504411
| MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
 Question If you were to decrease the percentile used as a cutoff point in the previous exercise to 93% instead of 95%, what would that do to your prediction results? The number of fraud cases caught increases, but false positives also increase. DB scan* Explore using a density based clu... | from sklearn.cluster import DBSCAN
# Initialize and fit the DBscan model
db = DBSCAN(eps=0.9, min_samples=10, n_jobs=-1).fit(X_scaled)
# Obtain the predicted labels and calculate number of clusters
pred_labels = db.labels_
n_clusters = len(set(pred_labels)) - (1 if -1 in labels else 0)
# # Print performance metrics ... | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
output: `Estimated number of clusters: 18Homogeneity: 0.633Silhouette Coefficient: 0.707` The number of clusters is much higher than with K-means. For fraud detection this is for now OK, as we are only interested in the smallest clusters, since those are considered as abnormal. Now let's have a look at those clusters... | counts = np.bincount(pred_labels[pred_labels >= 0])
print(counts)
| [3252 105 2714 46 174 119 112 79 52 74 43 24 45 42
11 19 16 13 10 15 35 10 40 19 11]
| MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
output: [3252 145 2714 55 174 119 122 98 54 15 76 15 43 25 51 47 42 15 25 20 19 10] | # Count observations in each cluster number
counts = np.bincount(pred_labels[pred_labels>=0])
# Sort the sample counts of the clusters and take the top 3 smallest clusters
smallest_clusters = np.argsort(counts)[:3]
# Print the results
print("The smallest clusters are clusters:")
print(smallest_clusters) | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
output: The smallest clusters are clusters: [21 17 9] | # Count observations in each cluster number
counts = np.bincount(pred_labels[pred_labels>=0])
# Sort the sample counts of the clusters and take the top 3 smallest clusters
smallest_clusters = np.argsort(counts)[:3]
# Print the counts of the smallest clusters only
print("Their counts are:")
print(counts[smallest... | Their counts are:
[10 10 11]
| MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
output: Their counts are: [10 15 15] So now we know which smallest clusters you could flag as fraud. If you were to take more of the smallest clusters, you cast your net wider and catch more fraud, but most likely also more false positives. It is up to the fraud analyst to find the right amount of cases to... | # Create a dataframe of the predicted cluster numbers and fraud labels
df = pd.DataFrame({'clusternr':pred_labels,'fraud':labels})
# Create a condition flagging fraud for the smallest clusters
df['predicted_fraud'] = np.where((df['clusternr']==21) | (df['clusternr']==17) | (df['clusternr']==9), 1, 0)
# Run a crossta... | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
output: ` Flagged Fraud 0 1 Actual Fraud 0 6973 16 1 176 24 ` How does this compare to the K-means model?* The good thing is: our of all flagged cases, roughly 2/3 are actually fraud! Since you only take the three smallest clusters, by definition you flag le... | import pandas as pd
df = pd.read_csv('enron_emails_clean.csv',index_col = 0)
# Find all cleaned emails that contain 'sell enron stock'
mask = df['clean_content'].str.contains('sell enron stock', na=False)
# Select the data from df that contain the searched for words
print(df.loc[mask]) | From \
Message-ID
<6336501.1075841154311.JavaMail.evans@thyme> ('sarah.palmer@enron.com')
To \
Message-ID ... | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
Using list of terms* Search on more than one term. * Create a full "fraud dictionary" of terms that could potentially flag fraudulent clients and/or transactions. Fraud analysts often will have an idea what should be in such a dictionary. In this exercise you're going to flag a multitude of terms, and in the next exer... | # Create a list of terms to search for
searchfor = ['enron stock', 'sell stock', 'stock bonus', 'sell enron stock']
# Filter cleaned emails on searchfor list and select from df
filtered_emails = df.loc[df['clean_content'].str.contains('|'.join(searchfor), na=False)]
# print(filtered_emails) | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
Creating a flagThis time you are going to create an actual flag variable that gives a 1 when the emails get a hit on the search terms of interest, and 0 otherwise. This is the last step you need to make in order to actually use the text data content as a feature in a machine learning model, or as an actual flag on top... | import numpy as np
# Create flag variable where the emails match the searchfor terms
df['flag'] = np.where((df['clean_content'].str.contains('|'.join(searchfor)) == True), 1, 0)
# Count the values of the flag variable
count = df['flag'].value_counts()
print(count) | 0 1776
1 314
Name: flag, dtype: int64
| MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.