Introdução a Ciência de Dados

100
DESMISTIFICANDO A CIÊNCIA DE DADOS

Transcript of Introdução a Ciência de Dados

DESMISTIFICANDO A CIÊNCIA DE DADOS

NAUBER GOISAluno de Doutorado em Informática Aplicada da Unifor

Área de Estudo: Reinforcement Learning e metaheurísticas aplicadas a testes de performance.

Analista de Desenvolvimento do Serpro

AGENDA

DEFINIÇÃO DE DATA SCIENCE TIPOS DE MODELOS EXEMPLOS DE APLICAÇÃO RELATÓRIOS TESTES A/B

O QUE É CIÊNCIA DE DADOS?

DATA SCIENCE É MAIS UM TERMO USADO PARA DESCREVER O PROCESSO DE TRANSFORMAÇÃO DE DADOS EM CONHECIMENTO.(LOUKIDES, 2016)

5

CIENTISTA DE DADOS

Matemática e estatística

Banco de Dados e Programação

Conhecimento de Negócio

Comunicação

Data scientist: Person who is better at statistics than any

software engineer and better at software engineering than

any statistician – Josh Wills

Data scientist: Pessoa que é melhor em estatística que quaisquer engenheiros de software e melhor em engenharia de software que quaisquer estatístico – Josh Wills

Usar (coletar, armazenar, publicar) dados não é data science. É preciso agregar valor aos dados e permitir novas formas de uso.

7

DESMISTIFICANDO A CIÊNCIA DE DADOS

DATA SCIENCE VENN DIAGRAM

9

DESMISTIFICANDO A CIÊNCIA DE DADOS

DESMISTIFICANDO A CIÊNCIA DE DADOS

U.M.Fayyad, G.Patetsky-Shapiro and P.Smyth (1995)

Seleção de Features e Redução de Dimensionalidade

PROCESSO?

DESMISTIFICANDO A CIÊNCIA DE DADOS

COLETAR E PROCESSAR OS DADOS

Conduzir experimento de pesquisa.

Coletar amostras de uma população.

Transformar , filtrar e sumarizar os dados.

Preparar os dados para o modelo escolhido

13

DESMISTIFICANDO A CIÊNCIA DE DADOS

FORMULAÇÃO DE UM PROBLEMAIdentificação de uma área de interesse e o tipo de modelo

Clustering

14

DESMISTIFICANDO A CIÊNCIA DE DADOS

ESCOLHA DO TIPO DE MODELO A SER APLICADO15

■ k-th Nearest Neighbour

■ Parzen Window ■ Unfolding, Conjoint Analysis,

Cat-PCA

Clustering Classificação Regressão

■ Linear Discriminant Analysis, QDA

■ Logistic Regression (Logit)

■ Decision Trees, LSSVM, NN, VS

■ Classical Linear Regression

■ Ridge Regression

■ NN, CART

+

+

+

+ ++

++

++

+++

+

++

++

++

+

+

--

--

-

-

++

+

++

+++

+

X 1X 1X 1

X 2 X 2

Common Data Mining tasks

TIPOS DE MODELOS

19

REGRESSÃO CLASSIFICAÇÃO AGRUPAMENTO

DESMISTIFICANDO A CIÊNCIA DE DADOS

CLASSIFICAÇÃO VS REGRESSÃO

20

O QUE É REGRESSÃO?

21

DESMISTIFICANDO A CIÊNCIA DE DADOS

REGRESSÃO https://plot.ly/pandas/line-and-scatter/

DESMISTIFICANDO A CIÊNCIA DE DADOS

REGRESSÃO https://plot.ly ('Coefficients: \n', array([ 0.00118801])) Mean squared error: 9.71 Variance score: -2.38

DESMISTIFICANDO A CIÊNCIA DE DADOS

REGRESSÃO

24

DESMISTIFICANDO A CIÊNCIA DE DADOS

QUAL A MELHOR PREDIÇÃO

25

DESMISTIFICANDO A CIÊNCIA DE DADOS

REGRESSION ERROR

26

DESMISTIFICANDO A CIÊNCIA DE DADOS

BIAS E OVERFITTING

27

OCCAM'S RAZOR

DESMISTIFICANDO A CIÊNCIA DE DADOS

• Se os resultados forem semelhantes escolha a solução mais simples.

• Em Data Science prefira sempre o modelo mais simples

DESMISTIFICANDO A CIÊNCIA DE DADOS

CORRELAÇÃO DOS DADOS

29

O QUE É CLASSIFICAÇÃO?

30

DESMISTIFICANDO A CIÊNCIA DE DADOS

CLASSIFICAÇÃO

A

B

B

A

A

B

?

31

DESMISTIFICANDO A CIÊNCIA DE DADOS

CLASSIFICADORES

DESMISTIFICANDO A CIÊNCIA DE DADOS

?

QUAL A TAG A APLICAR?

?

DESMISTIFICANDO A CIÊNCIA DE DADOS

QUAL A TAG A APLICAR?

A

A

B

B

C

?

DADOS DE TREINO VS DADOS DE TESTE

• Dados de Treino • Usados para treinar um

modelo • Exemplos

• Dados de Teste • Usados para testar a

performance do modelo • Dados de validação.

DESMISTIFICANDO A CIÊNCIA DE DADOS

Classificação

Nome Idade Renda Profissão ClasseDaniel ≤ 30 Média Estudante SimJoão 31..50 Média-Alta Professor Sim

Carlos 31..50 Média-Alta Engenheiro Sim

Maria 31..50 Baixa Vendedora Não

Paulo ≤ 30 Baixa Porteiro NãoOtavio > 60 Média-Alta Aposentado Não

SE. Idade ≤ 30 Renda é Média Compra-Produto-Eletrônico = SIM. E ENTÃO

DESMISTIFICANDO A CIÊNCIA DE DADOS

APRENDIZADO SUPERVISIONADO VS NÃO SUPERVISIONADO

38

APRENDIZADO SUPERVISIONADO VS NÃO SUPERVISIONADO• Supervisionado

• Conhecimento das entradas e saídas de dados

• Os dados possuem um label • O objetivo é predizer a classe

ou o label do dado

• Não Supervisionado • Sem conhecimento prévio

dos dados • O objetivo é determinar

padrões

DESMISTIFICANDO A CIÊNCIA DE DADOS

O QUE É AGRUPAMENTO?

40

DESMISTIFICANDO A CIÊNCIA DE DADOS

AGRUPAMENTOProcesso de agrupar objetos com características semelhantes

CLUSTER

DESMISTIFICANDO A CIÊNCIA DE DADOS

COMO AGRUPAR?

DESMISTIFICANDO A CIÊNCIA DE DADOS

DISTÂNCIA

DESMISTIFICANDO A CIÊNCIA DE DADOS

MODELOS DE AGRUPAMENTO

DESMISTIFICANDO A CIÊNCIA DE DADOS

ANÁLISE DE TEXTO

47

DESMISTIFICANDO A CIÊNCIA DE DADOS

ANALISANDO TEXTOPassados quase três meses do final dos Jogos, o Comitê

Rio-2016 ainda deve reembolso a

8.000 torcedores que utilizaram sua plataforma online para revender ingressos.

A entidade reduziu o contingente de consumidores a quem devia pagamentos, que chegou a 140 mil em 19 de outubro, data até a qual prometeu quitar os débitos. Mas ainda não deu fim ao problema.

A entidade afirmou que tem dificuldades para ressarcir o restante. Alega problemas para encontrar os credores e inconsistência nos dados bancários fornecidos —muitos depósitos não foram completados.

De acordo com o comitê, 3.500 pessoas foram procuradas mas não responderam às mensagens eletrônicas, 2.500 até deram retorno, porém as informações repassadas continham algum erro e 2.000 devem receber o reembolso até esta segunda (12), após terem dados checados.

Uma mutação aparentemente insignificante no

DNA dos ancestrais da humanidade pode ter contribuído para que nosso cérebro alcançasse o tamanho descomunal que tem hoje (três vezes maior que o dos grandes macacos).

Bastou inserir o gene que contém essa mutação em fetos de camundongo para que dobrasse o número de células que dão origem aos neurônios do córtex, a área cerebral mais "nobre".

A pesquisa, conduzida por

cientistas do Instituto Max Planck (Alemanha), é um dos primeiros frutos da tentativa de usar o genoma para entender como a evolução humana se desenrolou. Por enquanto, isso não tem sido fácil –tanto que o gene analisado pelos pesquisadores no novo estudo, designado pela indigesta sigla ARHGAP11B, é o único específico da linhagem humana a ser associado com a proliferação das tais células do córtex cerebral.

DESMISTIFICANDO A CIÊNCIA DE DADOS

ANÁLISE DE SENTIMENTO

>>> docs_new = ['God is love', 'OpenGL on the GPU is fast']>>> X_new_counts = count_vect.transform(docs_new)>>> X_new_tfidf = tfidf_transformer.transform(X_new_counts)

>>> predicted = clf.predict(X_new_tfidf)

>>> for doc, category in zip(docs_new, predicted):... print('%r => %s' % (doc, twenty_train.target_names[category]))...'God is love' => soc.religion.christian'OpenGL on the GPU is fast' => comp.graphics

DESMISTIFICANDO A CIÊNCIA DE DADOS

REPRESENTAÇÃO DE TEXTO

ANALISANDO A PERFORMANCE DE UM MODELO

51

DESMISTIFICANDO A CIÊNCIA DE DADOS

ACURÁCIA

DESMISTIFICANDO A CIÊNCIA DE DADOS

PERFORMANCE DE UM CLASSIFICADOR• Acuracia = classificados corretamente /total de exemplos • Erro = 1-Acuracia

PERFORMANCE DE UMA REGRESSÃOUma das formas de avaliar a qualidade do ajuste do modelo é através do coeficiente de determinação. Basicamente, este coeficiente indica quanto o modelo foi capaz de explicar os dados coletados. O coeficiente de determinação é dado pela expressão

Razão entre a soma de quadrados da regressão e a soma de quadrados total.

TABELA CONFUSÃO

DESMISTIFICANDO A CIÊNCIA DE DADOS

MEAN SQUARE ERROR

FERRAMENTAS E LINGUAGENS

56

NUMPY PANDAS SKLEARN R STUDIO

NUMPYBiblioteca em python para manipulação de arrays e matrizes

PANDASBiblioteca de Manipulação de dados e analise em python

DESMISTIFICANDO A CIÊNCIA DE DADOS

NUMPY E PANDAS- LENDO ARQUIVO CSV

import numpy as npimport pandas as pdimport visuals as vs # Supplementary codefrom sklearn.cross_validation import ShuffleSplit

# Load the Boston housing datasetdata = pd.read_csv('housing.csv')prices = data['MEDV']features = data.drop('MEDV', axis = 1)

DESMISTIFICANDO A CIÊNCIA DE DADOS

NUMPY E PANDAS- MÉDIA, MEDIANA E DESVIO PADRÃO

# TODO: Mean price of the datamean_price = np.mean(prices)

# TODO: Median price of the datamedian_price = np.median(prices)

# TODO: Standard deviation of prices of the datastd_price = np.std(prices)

# Show the calculated statisticsprint "Statistics for Boston housing dataset:\n"print "Mean price: ${:,.2f}".format(mean_price)print "Median price ${:,.2f}".format(median_price)print "Standard deviation of prices: ${:,.2f}".format(std_price)

SKLEARN• Aplicação simples e eficiente para data mining e data analysis • Feito com NumPy, SciPy, e matplotlib • Open source, commercially usable - BSD license

ALGORITMOS DE AGRUPAMENTO DO SKLEARN

DESMISTIFICANDO A CIÊNCIA DE DADOS

CLASSIFICAÇÃO NO SKLEARN# Create a classifier: a support vector classifierclassifier = svm.SVC(gamma=0.001)

# We learn the digits on the first half of the digitsclassifier.fit(data[:n_samples / 2], digits.target[:n_samples / 2])

DESMISTIFICANDO A CIÊNCIA DE DADOS

CLASSIFICANDO EMAILSDESMISTIFICANDO A CIÊNCIA DE DADOS

from sklearn.naive_bayes import MultinomialNB

classifier = MultinomialNB()…classifier.fit(counts, targets)

examples = ['Free Viagra call today!', "I'm going to attend the Linux users group tomorrow."]….predictions = classifier.predict(example_counts)predictions # [1, 0]

HTTP://SCIKIT-LEARN.ORG/STABLE/

LINGUAGEM RR é uma linguagem e também um ambiente de desenvolvimento integrado para cálculos estatísticos e gráficos. Foi criada originalmente por Ross Ihaka e por Robert Gentleman no departamento de Estatística da universidade de Auckland, Nova Zelândia.

EXEMPLOS DE APLICAÇÃO

ID SEXO CORAÇÃO PESO

1 F 2.0 7.0

2 F 2.0 7.4

3 F 2.0 9.5

4 F 2.1 7.2

5 F 2.1 7.3

6 F 2.1 7.6

7 F 2.1 8.1

8 F 2.1 8.2

library(“MASS")

data(cats)

EXEMPLO DE PROBLEMA - ÁREA (BIOLOGIA) - TIPO: REGRESSÃO

R is a free software environment for statistical computing and graphics. It compiles and runs on a wide variety of UNIX platforms, Windows and MacOS. To download R, please choose your preferred CRAN mirror.

67

PESO

CO

RAÇÃ

O

Peso

ggplot(a,aes(a$Bwt,a$Hwt))+geom_point()

EXEMPLO DE PROBLEMA - ÁREA (BIOLOGIA) - TIPO: REGRESSÃO

68

Peso

PESO

CO

RAÇÃ

OEXEMPLO DE PROBLEMA - ÁREA (BIOLOGIA) - TIPO: REGRESSÃO

69ggplot(a,aes(a$Bwt,a$Hwt))+geom_point()+geom_smooth()

70

EXEMPLO PREDIZER PREÇOS DE CASAS EM BOSTON

RM LMRATIO PTRATIO PREÇO

6.575 4.98 15.3 504000

6.421 9.14 17.8 453600

7.185 4.03 17.8 728700

6.998 2.94 18.7 701400

7.147 5.33 18.7 760200

6.43 5.21 18.7 602700

6.012 12.43 15.2 480900

6.172 19.15 15.2 569100

5.631 29.93 15.2 346500

6.004 17.1 15.2 396900

6.377 20.45 15.2 315000

6.009 13.27 15.2 396900

5.889 15.71 15.2 455700

5.949 8.26 21 428400

6.096 10.26 21 382200

• RM' -Média do número de quartos •'LSTAT' percentual de proprietários considerados "lower class" (working poor). •'PTRATIO' razão do número de estudantes por professor no bairro

EXEMPLO DE PROBLEMA - PREÇO DE IMÓVEIS EM BOSTON

EXEMPLO DE PROBLEMA - PREÇO DE IMÓVEIS EM BOSTON

ARVORES DE DECISÃO

EXEMPLO DE PROBLEMA - PREÇO DE IMÓVEIS EM BOSTON

PREÇOS DAS CASAS EM BOSTON

EXEMPLO DE PROBLEMA - PREÇO DE IMÓVEIS EM BOSTON

CÓDIGO DE REGRESSÃO NO SKLEARN

regressor = DecisionTreeRegressor(random_state=42)

params = {"max_depth": [1,2,3,4,5,6,7,8,9,10]}

# TODO: Create the grid search object grid = GridSearchCV(regressor, param_grid=params, scoring = scoring_fnc, cv = cv_sets)

# Fit the grid search object to the data to compute the optimal model grid = grid.fit(X, y)

EXEMPLO DE PROBLEMA - PREÇO DE IMÓVEIS EM BOSTON

PREDICTING

# Produce a matrix for client dataclient_data = [[5, 17, 15], # Client 1 [4, 32, 22], # Client 2 [8, 3, 12]] # Client 3

# Show predictionsfor i, price in enumerate(reg.predict(client_data)):

Predicted selling price for Client 1's home: $414,473.68Predicted selling price for Client 2's home: $214,302.44Predicted selling price for Client 3's home: $910,700.00

EXEMPLO INTERVENÇÃO DE ESTUDANTES

INTERVENÇÃO DE ESTUDANTES

INTERVENÇÃO DE ESTUDANTESFeature values: school sex age address famsize Pstatus Medu Fedu Mjob Fjob \0 GP F 18 U GT3 A 4 4 at_home teacher 1 GP F 17 U GT3 T 1 1 at_home other 2 GP F 15 U LE3 T 1 1 at_home other 3 GP F 15 U GT3 T 4 2 health services 4 GP F 16 U GT3 T 3 3 other other

... higher internet romantic famrel freetime goout Dalc Walc health \0 ... yes no no 4 3 4 1 1 3 1 ... yes yes no 5 3 3 1 1 3 2 ... yes yes no 4 3 2 2 3 3 3 ... yes yes yes 3 2 2 1 1 5 4 ... yes no no 4 3 2 1 2 5

absences 0 6 1 4 2 10 3 2 4 4

INTERVENÇÃO DE ESTUDANTES

PREPARANDO OS DADOS

# If data type is non-numeric, replace all yes/no values with 1/0

if col_data.dtype == object:

col_data = col_data.replace(['yes', 'no'], [1, 0])

X_train, X_test, y_train, y_test = train_test_split(X_all, y_all, stratify=y_all, train_size=train_size,test_size=0.24)

SEPARANDO DADOS DE TREINO E TESTE

INTERVENÇÃO DE ESTUDANTES

INICIALIZANDO MODELOS

clf_A = svm.SVC(random_state=42)

clf_B = tree.DecisionTreeClassifier(random_state=42)

clf_C = AdaBoostClassifier(tree.DecisionTreeClassifier(max_depth=1),

algorithm="SAMME",

n_estimators=300,random_state=42)

clf_D=KNeighborsClassifier(n_neighbors=3)

clf_E= GaussianNB()

clf_F=RandomForestClassifier(n_estimators=100,random_state=42)

clf_G=LogisticRegression(random_state=42)

INTERVENÇÃO DE ESTUDANTES

COMPARAÇÃO DE MODELOSLogistic Regression Pros:• Implementação eficiente

Logistic Regression Cons:• Não é performático com muitas features

Decision Trees Pros:• Regras de decisão intuitivas• Pode utilizar campos não lineares

Decision Trees Cons:• Alto Bias [Random Forests pode ser a solução]• Sem ranking score

COMPARAÇÃO DE MODELOS

INTERVENÇÃO DE ESTUDANTES

COMPARAÇÃO DE MODELOSSVM Pros:

• Pode lidar com um grande número de featuresSVM Cons:

• Não é performático em um dataset com um maior número de linhas

INTERVENÇÃO DE ESTUDANTES

PERFORMANCE DOS CLASSIFICADORES

INTERVENÇÃO DE ESTUDANTES

SEGMENTANDO FORNECEDORES

BANCO DE DADOS DE PRODUTOS

SEGMENTANDO FORNECEDORES

VERIFICANDO CORRELACIONAMENTO

SEGMENTANDO FORNECEDORES

PCA -REDUZINDO DIMENSÕES

clusterer = KMeans(n_clusters=i, random_state=29).fit(reduced_data)

preds = clusterer.predict(reduced_data)

GERANDO OS CLUSTERS

SITES ONDE CONSEGUIR INFORMAÇÃO

DESMISTIFICANDO A CIÊNCIA DE DADOS

HTTPS://ENSINANDOMAQUINASBLOG.WORDPRESS.COM

ONDE DESCOBRIR NOVAS INFORMAÇÕES

KAGGLE

RELATÓRIOS

RELATÓRIOS

▸ Notebooks online: iPython, Jupyter

▸ permitem a criação de documentos

▸ interativos em várias linguagens de análise.

▸ ¨ Reproducible Research!

TESTE A/B

TESTE A/B

TESTE A/BTeste A/B é um método de teste onde se comparam duas práticas, A e B, em que estes são o controle e o tratamento de uma experiência controlada, com o objetivo de melhorar a percentagem de aprovação.

TESTE A/B

LIVROS

Dúvidas: [email protected]