{"metadata":{"kernelspec":{"name":"ir","display_name":"R","language":"R"},"language_info":{"name":"R","codemirror_mode":"r","pygments_lexer":"r","mimetype":"text/x-r-source","file_extension":".r","version":"4.0.5"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# ML Olympiad - QUALITY EDUCATION\n\n**ML Olympiad – Previsão das notas da prova do ENEM**\n\n---\n\n\n## Definição do problema de negócio\n\n**Objetivo:** Prever as notas dos alunos(as) nas provas: Ciências da Natureza, Ciências Humanas, Linguagens e Códigos, Matemática e Redação\n\nApesar das notas serem calculadas de maneira idependente, a partir de modelos de TRI ([Teoria de Resposta ao Item](http://portal.mec.gov.br/ebserh-governo/418-noticias/enem-946573306/84461-entenda-como-e-calculada-a-nota-do-enem)) que levam em consideração a performance em um caderno específico e na dificuldade de cada questão, o *mesmo* aluno realiza todas as provas em um período curto de intervalo. \n\nPortanto esta tarefa pode ser enquadrado como um problema supervisionado de regressão com múltiplos *outputs* na qual as previsões são, de certa forma, dependentes da entrada umas das outras. \n\nA validação da solução apresentada será realizada utilizando a métrica *Mean Columnwise Root Mean Squared Error – MCRMSE*, que é basicamente a média do RMSE calculado sobre as previsões de cada nota.\n\n\n<p style=\"color:red\">Se gostou não esqueça do voto! 🤘</p>","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19"}},{"cell_type":"markdown","source":"<center><img src=\"https://conteudo.imguol.com.br/c/noticias/f6/2020/06/26/imagem-de-prova-do-enem-1593183331646_v2_615x300.jpg\"/></center>","metadata":{}},{"cell_type":"code","source":"# Carregar dependencias\nlibrary(tidyverse)\nlibrary(ggplot2)\nlibrary(patchwork)\n\ntheme_set(theme_bw()+theme(text = element_text(size=20)))\n\n# Funcao auxiliar para exibir plot\nfig <- function(width, heigth){\n    # borrowed from https://www.kaggle.com/getting-started/105201\n    options(repr.plot.width = width, repr.plot.height = heigth)\n}\n\n# Carregar dados\ntrain <- data.table::fread('../input/qualityeducation//train.csv')\n\n# Carregar e tratar dicionario de dados \ndic <- readxl::read_xlsx(\"../input/qualityeducation//Dicionario_Microdados_Enem.xlsx\", skip = 2) %>% \n  janitor::clean_names() %>% \n  rename(categoria = variaveis_categoricas, \n         descricao_cat = x4) %>% \n  fill(nome_da_variavel, descricao, .direction = \"down\") %>% \n  filter(!str_detect(nome_da_variavel, \"^DADOS\"))","metadata":{"_kg_hide-output":true,"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T03:32:04.228797Z","iopub.execute_input":"2022-02-25T03:32:04.231071Z","iopub.status.idle":"2022-02-25T03:32:27.701205Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Visão Geral dos dados ","metadata":{}},{"cell_type":"code","source":"fig(8, 10)\n\ncount_by_uf <- train %>% \n  count(SG_UF_PROVA) %>% \n  mutate(prop = n/sum(n),\n         lab = glue::glue(\"{scales::comma(n, big.mark='.', decimal.mark=',')} ({round(prop*100, 2)}%)\"),\n         SG_UF_PROVA = reorder(SG_UF_PROVA, n))\n\ncount_by_uf_test = chisq.test(count_by_uf$n)\n\nggplot(count_by_uf, aes(y=SG_UF_PROVA, x=n))+\n  geom_bar(stat='identity', width = 0.1)+\n  geom_label(aes(label = lab), hjust='inward', size=6)+\n  theme_bw()+\n  theme(text = element_text(size=20))+\n  scale_x_continuous(labels = scales::comma)+\n  labs(caption = glue::glue(\"{count_by_uf_test$method}: p-value < 2.2e-16\"),\n      x = glue::glue(\"Frequência\\nNúmero total de dados na base de treino:{scales::comma(nrow(train)) }\"))\n","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T04:15:44.993686Z","iopub.execute_input":"2022-02-25T04:15:44.995533Z","iopub.status.idle":"2022-02-25T04:15:45.491086Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-info\"> \n<strong>📌  Interpretação:</strong> <br>\n\n<div style=\"color: rgb(0, 0, 0);\">→ São Paulo possui a maior porcentagem do volume total de dados;</div>\n<div style=\"color: rgb(0, 0, 0);\">→ Existem dados para todos os estados brasileiros;</div>\n<div style=\"color: rgb(0, 0, 0);\">→ O número total de instâncias na base é (razoavelmente) alto.</div>\n    \n</div>","metadata":{}},{"cell_type":"markdown","source":"## Amostragem Estratificada por UF","metadata":{}},{"cell_type":"markdown","source":"Como nossa amostra contém mais de 3 milhões de observações, uma amostra estratificada por UF será realizada a fim de tornar a base em um tamanho mais facilmente gerenciável.","metadata":{}},{"cell_type":"code","source":"# Filtrar apenas alunos que fizeram todas as provas \n#train <- train %>% \n#  filter(TP_PRESENCA_CN==1, \n#         TP_PRESENCA_CH==1,\n#         TP_PRESENCA_LC==1,\n#         TP_PRESENCA_MT==1, \n#         TP_STATUS_REDACAO==1) %>% \n#  select(-starts_with(\"TP_PRESENCA_\"), -TP_STATUS_REDACAO)\n\n# Remover colunas de codigos de identificacao\ntrain <- train %>% \n  select(-starts_with(\"CO_\"), -NU_INSCRICAO)\n\n# Substituir rotulo por legenda do dicionario -----------------------------\n\n# Substituir os valores das colunas com prefixo TP_\nfor(feature in colnames(train) %>% .[str_detect(., \"^TP_\")]){\n  train[, feature] <- train %>%\n    select(to_join = all_of(feature)) %>%\n    mutate(to_join = as.character(to_join)) %>%\n    left_join(dic %>%\n                filter(nome_da_variavel == feature) %>%\n                select(to_join = categoria, descricao_cat),\n              by = \"to_join\"\n    ) %>%\n    select(descricao_cat)\n}\n  \n# Substituir os valores das colunas com prefixo IN_\ntrain <- train %>%\n  mutate_at(colnames(train) %>% .[str_detect(., \"^IN_\")], ~ case_when(\n    .x == 0 ~ \"Não\",\n    .x == 1 ~ \"Sim\",\n  ))\n  \n# Amostragem --------------------------------------------------------------\n\ndf <- train %>% \n  group_by(SG_UF_PROVA) %>% \n  sample_frac(0.2) %>% \n  ungroup()\n\nrm(train, count_by_uf, count_by_uf_test, dic)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T03:32:31.059916Z","iopub.execute_input":"2022-02-25T03:32:31.061307Z","iopub.status.idle":"2022-02-25T03:33:30.382251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ndf <- df %>% \n  mutate(FE_REGIAO_RESIDENCIA= case_when(\n    SG_UF_RESIDENCIA %in% c('AM', 'RR', 'AP', 'PA', 'TO', 'RO', 'AC') ~ \"Norte\",\n    SG_UF_RESIDENCIA %in% c('MA', 'PI', 'CE', 'RN', 'PE', 'PB', 'SE', 'AL', 'BA') ~ \"Nordeste\",\n    SG_UF_RESIDENCIA %in% c('MT', 'MS', 'GO', 'DF') ~ \"Centro-Oeste\",\n    SG_UF_RESIDENCIA %in% c('SP', 'RJ', 'ES', 'MG') ~ \"Sudeste\",\n    SG_UF_RESIDENCIA %in% c('PR', 'RS', 'SC') ~ \"Sul\"\n  )) \n\ndf <- df %>% \n  mutate(renda_mensal_familia = case_when(\n    Q006==\"A\" ~ 0,\n    Q006==\"B\" ~ 1000,\n    Q006==\"C\" ~ 1500,\n    Q006==\"D\" ~ 2000,\n    Q006==\"E\" ~ 2500,\n    Q006==\"F\" ~ 3000,\n    Q006==\"G\" ~ 4000,\n    Q006==\"H\" ~ 5000,\n    Q006==\"I\" ~ 6000,\n    Q006==\"J\" ~ 7000,\n    Q006==\"K\" ~ 8000,\n    Q006==\"L\" ~ 9000,\n    Q006==\"M\" ~ 10000,\n    Q006==\"N\" ~ 12000,\n    Q006==\"O\" ~ 15000,\n    Q006==\"P\" ~ 20000,\n    Q006==\"Q\" ~ 50000\n  ))\n\ndf <- df %>% \n  mutate(TP_ESTADO_CIVIL = factor(TP_ESTADO_CIVIL, c(\"Não informado\",\n                                                     \"Solteiro(a)\",\n                                                     \"Divorciado(a)/Desquitado(a)/Separado(a)\",\n                                                     \"Casado(a)/Mora com companheiro(a)\",\n                                                     \"Viúvo(a)\")))\n\ndf <- df %>% \n  mutate(TP_ANO_CONCLUIU = factor(TP_ANO_CONCLUIU, c(\"Não informado\", \"Antes de 2007\", 2007:2018)))\n\ndf <- df %>% \n  mutate(TP_COR_RACA = factor(TP_COR_RACA, levels = c(\"Não declarado\", \"Parda\", \"Branca\", \"Preta\", \"Amarela\", \"Indígena\" )))\n","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T03:33:30.38463Z","iopub.execute_input":"2022-02-25T03:33:30.385958Z","iopub.status.idle":"2022-02-25T03:33:30.916612Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig(14, 6)\nDataExplorer::plot_intro(df, ggtheme = theme_bw(), theme_config = list(text = element_text(size=20)))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T04:16:26.92095Z","iopub.execute_input":"2022-02-25T04:16:26.922787Z","iopub.status.idle":"2022-02-25T04:16:30.193817Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-info\"> \n<strong>📌  Interpretação:</strong> <br>\n\n<div style=\"color: rgb(0, 0, 0);\">→ A maioria de nossos atributos é categórico;</div>\n<div style=\"color: rgb(0, 0, 0);\">→ Poucas linhas (17.8%) possuem instâncias totalmente sem dados ausentes;</div>\n<div style=\"color: rgb(0, 0, 0);\">→ praticamente 4% de nosso dataset é composto por dados faltantes.</div>\n    \n</div>","metadata":{}},{"cell_type":"code","source":"fig(20, 6)\ndf %>% sample_n(1000) %>% visdat::vis_dat() + theme(text = element_text(size=14))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T03:33:34.200459Z","iopub.execute_input":"2022-02-25T03:33:34.202119Z","iopub.status.idle":"2022-02-25T03:33:35.39449Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-info\"> \n<strong>📌  Interpretação:</strong> <br>\n\n<div style=\"color: rgb(0, 0, 0);\">→ A maioria dos dados missing se encontram nas features relacionadas a escola;</div>\n<div style=\"color: rgb(0, 0, 0);\">→ Parece haver um padrão nos dados faltantes.</div>\n    \n</div>","metadata":{}},{"cell_type":"markdown","source":"Dando um pouco mais de atenção às colunas com dados missing:","metadata":{}},{"cell_type":"code","source":"DataExplorer::plot_missing(df, missing_only = T, ggtheme = theme_bw(), theme_config = list(text = element_text(size=20)))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T03:33:35.396939Z","iopub.execute_input":"2022-02-25T03:33:35.398373Z","iopub.status.idle":"2022-02-25T03:33:36.381527Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-info\"> \n<strong>📌  Interpretação:</strong> <br>\n\n<div style=\"color: rgb(0, 0, 0);\">→ A informação da idade possui poucos dados faltantes;</div>\n<div style=\"color: rgb(0, 0, 0);\">→ Existem dados faltantes nas notas (nossa target);</div>\n<div style=\"color: rgb(0, 0, 0);\">→ Features relacionadas à escola possuem altóssimo número de missings</div>\n    \n</div>","metadata":{}},{"cell_type":"markdown","source":"# Dados do participante\n\nVamos conhecer o perfil dos participantes!\n","metadata":{}},{"cell_type":"markdown","source":"### Sobre município e UF de prova, residência e nascimento:","metadata":{}},{"cell_type":"code","source":"fig(16, 6)\ndf %>% \n  select(starts_with(\"NO_\"), starts_with(\"SG_\")) %>% \n  sample_n(1000) %>% \n  inspectdf::inspect_cat() %>% \n  inspectdf::show_plot() + \n  theme(text = element_text(size=20))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T03:33:36.384053Z","iopub.execute_input":"2022-02-25T03:33:36.385517Z","iopub.status.idle":"2022-02-25T03:33:37.294517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-info\"> \n<strong>📌  Interpretação:</strong> <br>\n\n<div style=\"color: rgb(0, 0, 0);\">→ Features categóricas sobre municípios são muito fragmentadas;</div>\n<div style=\"color: rgb(0, 0, 0);\">→ Maioria dos dados vêm dos estados de SP e MG;</div>\n<div style=\"color: rgb(0, 0, 0);\">→ Alto número de missings em features relacionadas a escola.</div>\n    \n</div>","metadata":{}},{"cell_type":"markdown","source":"### Quantidade de alunos por Estado/UF:","metadata":{}},{"cell_type":"code","source":"fig(11, 12)\ndf %>% \n  count(SG_UF_RESIDENCIA, FE_REGIAO_RESIDENCIA) %>% \n  group_by(FE_REGIAO_RESIDENCIA) %>% \n  mutate(prop = n/sum(n),\n         label = glue::glue(\"{n} ({round(prop*100,2)}%)\")) %>% \n  ggplot(aes(x = SG_UF_RESIDENCIA, y=n))+\n  geom_bar(stat = \"identity\", width = 0.2)+\n  geom_label(aes(label = label), hjust=\"inward\", size=4.5)+\n  facet_wrap(~FE_REGIAO_RESIDENCIA, scales = \"free_y\", nrow=5)+\n  labs(x = \"UF\", y=\"Frequência\")+\n  coord_flip()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T03:33:37.296966Z","iopub.execute_input":"2022-02-25T03:33:37.298352Z","iopub.status.idle":"2022-02-25T03:33:38.073723Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Sobre a idade","metadata":{}},{"cell_type":"markdown","source":"### Distribuição geral da idade","metadata":{}},{"cell_type":"code","source":"fig(12, 4)\n{\n  g1 <- df %>%\n    filter(!is.na(NU_IDADE)) %>%\n    ggplot(aes(x=NU_IDADE)) + \n    geom_histogram(aes(y=..density..), colour=\"black\", fill=\"white\", bins = 30)+\n    geom_density(alpha=.2, fill=\"#FF6666\")+ \n    labs(x = \"\", y = \"\")+\n    scale_x_continuous(breaks=seq(0, 100, 10))\n  \n  g2 <- df %>%\n    filter(!is.na(NU_IDADE)) %>%\n    ggplot(aes(y=NU_IDADE)) + \n    geom_boxplot(aes(x=\"\"), colour=\"black\", fill=\"white\")+\n    coord_flip()+ \n    labs(x = \"\", y = \"\")+\n    scale_y_continuous(breaks=seq(0, 100, 10))\n    \n  g3 <- df %>%\n    filter(!is.na(NU_IDADE)) %>%\n    ggplot(aes(NU_IDADE)) +\n    stat_ecdf(geom = \"step\")+\n    labs(y=\"\")+\n    scale_x_continuous(breaks=seq(0, 100, 5))\n  \n  (g1 / g2 + \n    plot_layout(heights = c(4, 1)) | g3)\n}","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T03:33:38.076223Z","iopub.execute_input":"2022-02-25T03:33:38.077701Z","iopub.status.idle":"2022-02-25T03:33:43.266033Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-info\"> \n<strong>📌  Interpretação:</strong> <br>\n\n<div style=\"color: rgb(0, 0, 0);\">→ Distribuição muito assimétrica;</div>\n<div style=\"color: rgb(0, 0, 0);\">→ Elevado número de outliers;</div>\n<div style=\"color: rgb(0, 0, 0);\">→ Idades são concentradas entre 17 e 22 anos.</div>\n<div style=\"color: rgb(0, 0, 0);\">→ Alunos com 10 anos fazendo enem, realmente impressionante!</div>\n    \n</div>","metadata":{"execution":{"iopub.status.busy":"2022-02-25T02:07:33.690232Z","iopub.execute_input":"2022-02-25T02:07:33.692099Z","iopub.status.idle":"2022-02-25T02:07:33.703986Z"}}},{"cell_type":"markdown","source":"### Idade pelo estado civil:","metadata":{}},{"cell_type":"code","source":"df %>%\n  filter(!is.na(NU_IDADE)) %>% \n  ggplot(aes(x = TP_ESTADO_CIVIL, y = NU_IDADE))+\n  geom_boxplot()+\n  coord_flip()+\n  geom_point(data = df %>%\n               group_by(TP_ESTADO_CIVIL) %>% \n               summarise(NU_IDADE = mean(NU_IDADE, na.rm = T)),\n             color=\"red\", shape=4, size=3)+\n  scale_y_continuous(breaks = seq(0, 100, 10))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T03:33:43.268336Z","iopub.execute_input":"2022-02-25T03:33:43.269743Z","iopub.status.idle":"2022-02-25T03:33:46.752602Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-info\"> \n<strong>📌  Interpretação:</strong> <br>\n\n<div style=\"color: rgb(0, 0, 0);\">→ Naturalmente, viúvos são mais velhos, em média;</div>\n<div style=\"color: rgb(0, 0, 0);\">→ Solteiros mais novos que casados;</div>\n<div style=\"color: rgb(0, 0, 0);\">→ Existem solteiros de até 80 anos, será que não não viúvos que informaram errado?</div>\n<div style=\"color: rgb(0, 0, 0);\">→ Surpreso de que aproximadamente 25% dos divorciados tem menos de 20 anos</div>\n    \n</div>","metadata":{}},{"cell_type":"markdown","source":"### Idade pelo Ano que concluiu:","metadata":{}},{"cell_type":"code","source":"fig(12, 6)\n\ndf %>%\n  filter(!is.na(NU_IDADE)) %>% \n  ggplot(aes(x = TP_ANO_CONCLUIU, y = NU_IDADE))+\n  geom_boxplot()+\n  coord_flip()+\n  geom_point(data = df %>%\n               group_by(TP_ANO_CONCLUIU) %>% \n               summarise(NU_IDADE = mean(NU_IDADE, na.rm = T)),\n             color=\"red\", shape=4, size=3)+\n  scale_y_continuous(breaks = seq(0, 100, 10))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T03:33:46.755043Z","iopub.execute_input":"2022-02-25T03:33:46.756451Z","iopub.status.idle":"2022-02-25T03:33:51.338078Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-info\"> \n<strong>📌  Interpretação:</strong> <br>\n\n<div style=\"color: rgb(0, 0, 0);\">→ Naturalmente, a idade média aumenta conforme diminui o ano de conclusão do ensino médio;</div>\n    \n</div>","metadata":{}},{"cell_type":"markdown","source":"<div class=\"alert alert-warning\"> \n<strong>💡 Insights!</strong> \n    \n<div style=\"color: rgb(0, 0, 0);\">→ Atenção aos outliers: É no mínimo estranho uma pessoa que formou em 2007 ter 17 anos</div>\n</div>","metadata":{}},{"cell_type":"markdown","source":"### Idade pelo tipo de ensino:","metadata":{}},{"cell_type":"code","source":"fig(12, 3)\ndf %>%\n  filter(!is.na(NU_IDADE)) %>% \n  ggplot(aes(x = TP_ENSINO, y = NU_IDADE))+\n  geom_boxplot()+\n  geom_point(data = df %>%\n               group_by(TP_ENSINO) %>% \n               summarise(NU_IDADE = mean(NU_IDADE, na.rm = T)),\n             color=\"red\", shape=4, size=3)+\n  scale_y_continuous(breaks = seq(0, 100, 10))+\ncoord_flip()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T03:33:51.340541Z","iopub.execute_input":"2022-02-25T03:33:51.34196Z","iopub.status.idle":"2022-02-25T03:33:54.964436Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-info\"> \n<strong>📌  Interpretação:</strong> <br>\n\n<div style=\"color: rgb(0, 0, 0);\">→ Na base existe a classe \"Educação de Jovens e Adultos\", que não aparece no gráfico;</div>\n<div style=\"color: rgb(0, 0, 0);\">→ Talvel considerar aqueles alunos com mais de 21 anos como esssa classe.</div>\n    \n</div>","metadata":{}},{"cell_type":"markdown","source":"### Idade por localização:","metadata":{}},{"cell_type":"code","source":"fig(12, 4)\ndf %>%\n  filter(!is.na(NU_IDADE))%>% \n  ggplot(aes(x = TP_LOCALIZACAO_ESC, y = NU_IDADE))+\n  geom_boxplot()+\n  geom_point(data = df %>%\n               group_by(TP_LOCALIZACAO_ESC) %>% \n               summarise(NU_IDADE = mean(NU_IDADE, na.rm = T)),\n             color=\"red\", shape=4, size=3)+\n  scale_y_continuous(breaks = seq(0, 100, 10))+\ncoord_flip()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T03:33:54.968537Z","iopub.execute_input":"2022-02-25T03:33:54.971069Z","iopub.status.idle":"2022-02-25T03:33:58.662197Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-warning\"> \n<strong>💡 Insights!</strong> \n    \n<div style=\"color: rgb(0, 0, 0);\">→ Curioso como a idade média é maior naqueles que nao informaram a localizacao da escola, sera que é ensino a distância? Ou alunos que ja formaram a algum tempo?</div>\n</div>\n","metadata":{}},{"cell_type":"markdown","source":"### Por último (mas não menos importante) nota por idade:","metadata":{}},{"cell_type":"code","source":"set.seed(314)\n\ndf %>% \n  sample_n(10000) %>% \n  filter_at(c(\"NU_NOTA_LC\", \"NU_NOTA_CH\", \"NU_NOTA_CN\", \"NU_NOTA_MT\", \"NU_NOTA_REDACAO\"),\n            ~.x!=0) %>% \n  select(NU_IDADE, NU_NOTA_LC, NU_NOTA_CH, NU_NOTA_CN, NU_NOTA_MT, NU_NOTA_REDACAO) %>% \n  gather(Prova, Nota, -NU_IDADE) %>% \n  ggplot(aes(x=Nota, y=NU_IDADE))+\n  geom_point(alpha=0.4)+\n  facet_wrap(~Prova, nrow=1)+\n  scale_y_continuous(breaks = seq(0, 100, 10))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T03:33:58.664879Z","iopub.execute_input":"2022-02-25T03:33:58.666324Z","iopub.status.idle":"2022-02-25T03:34:01.809605Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-info\"> \n<strong>📌  Interpretação:</strong> <br>\n\n<div style=\"color: rgb(0, 0, 0);\">→ A idade não parece ter forte relação com nenhumas das notas</div>\n    \n</div>","metadata":{}},{"cell_type":"markdown","source":"## Sobre Raça","metadata":{}},{"cell_type":"markdown","source":"### Raça pelo tipo de escola","metadata":{}},{"cell_type":"code","source":"fig(14, 6)\ndf %>% \n  mutate(TP_DEPENDENCIA_ADM_ESC = ifelse(TP_DEPENDENCIA_ADM_ESC==\"Privada\", \n                                         \"Privada\", \"Pública\")) %>% \n  filter(!is.na(TP_DEPENDENCIA_ADM_ESC)) %>% \n  count(TP_DEPENDENCIA_ADM_ESC, TP_COR_RACA) %>% \n  mutate(label = glue::glue(\"{n} ({round(n/sum(n)*100, 2)}%)\")) %>% \n  ggplot(aes(x = TP_COR_RACA, y=n))+\n  geom_bar(stat = \"identity\")+\n  geom_label(aes(label = label), vjust='inward')+\n  facet_wrap(~TP_DEPENDENCIA_ADM_ESC)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T04:19:17.598916Z","iopub.execute_input":"2022-02-25T04:19:17.600562Z","iopub.status.idle":"2022-02-25T04:19:18.195802Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-info\"> \n<strong>📌  Interpretação:</strong> <br>\n\n<div style=\"color: rgb(0, 0, 0);\">→ Brancos estão mais presentes em escolas privadas;</div>\n    \n</div>","metadata":{}},{"cell_type":"markdown","source":"<div class=\"alert alert-warning\"> \n<strong>💡 Insights!</strong> \n    \n<div style=\"color: rgb(0, 0, 0);\">→ No mínimo estranho a porcentagem de negros aparecer tão baixa no geral já que 54% da população brasileira se reconhece como negra;</div>\n</div>\n\nFonte: [54% da população brasileira se reconhece como negra](https://economia.uol.com.br/noticias/redacao/2015/12/04/negros-representam-54-da-populacao-do-pais-mas-sao-so-17-dos-mais-ricos.htm)","metadata":{}},{"cell_type":"markdown","source":"### Rentabilidade por raça","metadata":{}},{"cell_type":"code","source":"df %>% \n  group_by(TP_COR_RACA) %>% \n  summarise(Minimo = min(renda_mensal_familia, na.rm=T),\n            Q1 = quantile(renda_mensal_familia,0.25, na.rm=T),\n            Media = mean(renda_mensal_familia, na.rm=T),\n            #            Desv.Pad = std(renda_mensal_familia, na.rm=T),\n            Mediana = median(renda_mensal_familia, na.rm=T),\n            Q3 = quantile(renda_mensal_familia,0.75, na.rm=T),\n            Maximo = max(renda_mensal_familia, na.rm=T))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T03:34:02.350342Z","iopub.execute_input":"2022-02-25T03:34:02.351773Z","iopub.status.idle":"2022-02-25T03:34:02.47134Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-info\"> \n<strong>📌  Interpretação:</strong> <br>\n\n<div style=\"color: rgb(0, 0, 0);\">→ Brancos possuem maior renda no geral;</div>\n<div style=\"color: rgb(0, 0, 0);\">→ Quase todas as raças possuem a mesma mediana, porém a dos brancos é maior</div>\n\n    \n</div>","metadata":{}},{"cell_type":"code","source":"fig(13, 6)\ndf %>% \n  select(TP_COR_RACA, renda_mensal_familia) %>% \n  ggplot(aes(x = TP_COR_RACA, y = renda_mensal_familia))+\n  geom_boxplot()+\n  coord_flip()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T04:19:34.199558Z","iopub.execute_input":"2022-02-25T04:19:34.201377Z","iopub.status.idle":"2022-02-25T04:19:37.402134Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-info\"> \n<strong>📌  Interpretação:</strong> <br>\n\n<div style=\"color: rgb(0, 0, 0);\">→ Indigenas possuem renda muito inferior</div>\n\n    \n</div>","metadata":{}},{"cell_type":"markdown","source":"### Numero de zeros é maior para alguma raça?","metadata":{}},{"cell_type":"code","source":"fig(17, 6)\ndf %>% \n  group_by(TP_COR_RACA) %>% \n  summarise(n_zeros_lc = sum(NU_NOTA_LC==0, na.rm=T),\n            n_zeros_ch = sum(NU_NOTA_CH==0, na.rm=T),\n            n_zeros_cn = sum(NU_NOTA_CN==0, na.rm=T),\n            n_zeros_mt = sum(NU_NOTA_MT==0, na.rm=T),\n            n_zeros_rd = sum(NU_NOTA_REDACAO==0, na.rm=T),\n  ) %>% \n  gather(Prova, N_Zeros, -TP_COR_RACA) %>% \n  ggplot(aes(y = N_Zeros, x=TP_COR_RACA))+\n  geom_bar(stat = 'identity')+\n  facet_wrap(~Prova, nrow = 1, scales='free')+\ncoord_flip()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T03:34:05.688797Z","iopub.execute_input":"2022-02-25T03:34:05.690224Z","iopub.status.idle":"2022-02-25T03:34:06.317219Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-info\"> \n<strong>📌  Interpretação:</strong> <br>\n\n<div style=\"color: rgb(0, 0, 0);\">→ Pardos foram os que mais tiraram zero (pode ter haver com ser a raça mais predominantes também);</div>\n<div style=\"color: rgb(0, 0, 0);\">→ Brancos com maior número de zeros para o caderno de ciências da natureza.</div>\n\n    \n</div>","metadata":{}},{"cell_type":"markdown","source":"### Lingua por raça:","metadata":{}},{"cell_type":"code","source":"df %>% \n  count(TP_COR_RACA, TP_LINGUA)  %>% \n  ggplot(aes(x = TP_COR_RACA, y=n))+\n  geom_bar(stat = \"identity\")+\n  facet_wrap(~TP_LINGUA)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T03:34:06.319597Z","iopub.execute_input":"2022-02-25T03:34:06.32104Z","iopub.status.idle":"2022-02-25T03:34:06.641091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-info\"> \n<strong>📌  Interpretação:</strong> <br>\n\n<div style=\"color: rgb(0, 0, 0);\">→ Maioria de brancos optou por inglês;</div>\n<div style=\"color: rgb(0, 0, 0);\">→ Maioria de pardos escolhe espanhol.</div>\n\n    \n</div>","metadata":{}},{"cell_type":"markdown","source":"<div class=\"alert alert-warning\"> \n<strong>💡 Insights!</strong> \n    \n<div style=\"color: rgb(0, 0, 0);\">→ Será que os que não falam inglês preferem optar por espanhol?;</div>\n<div style=\"color: rgb(0, 0, 0);\">→ Será que, por ter maior renda média, pagam curso de inglês além do ensino na escola?;</div>\n</div>\n","metadata":{}},{"cell_type":"markdown","source":"### Notas por raça:","metadata":{}},{"cell_type":"code","source":"fig(12, 6)\ndf %>%\n  filter_at(c(\"NU_NOTA_CN\", \"NU_NOTA_CH\", \"NU_NOTA_LC\", \"NU_NOTA_MT\", \"NU_NOTA_REDACAO\"), ~!is.na(.x)) %>%\n  mutate(TP_DEPENDENCIA_ADM_ESC = ifelse(TP_DEPENDENCIA_ADM_ESC==\"Privada\", \n                                         \"Privada\", \"Pública\")) %>% \n  filter(!is.na(TP_DEPENDENCIA_ADM_ESC)) %>% \n  select(TP_DEPENDENCIA_ADM_ESC, TP_COR_RACA, starts_with(\"NU_NOTA\")) %>% \n  gather(Prova, Nota, -TP_DEPENDENCIA_ADM_ESC, -TP_COR_RACA) %>% \n  ggplot(aes(x = Prova, y=Nota, col = TP_COR_RACA))+\n  geom_boxplot()+\n  facet_wrap(~TP_DEPENDENCIA_ADM_ESC)+\n  theme(legend.position = \"bottom\")+\n  scale_color_manual(values = c(\"blue\", \"orange\", \"lightgrey\", \"black\", \"yellow\", \"brown\"))+\n  theme(axis.text.x = element_text(angle = 30, hjust=1))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T03:34:06.643522Z","iopub.execute_input":"2022-02-25T03:34:06.645012Z","iopub.status.idle":"2022-02-25T03:34:09.339981Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Tipo de escola","metadata":{}},{"cell_type":"markdown","source":"### Numero de zeros por tipo de escola","metadata":{}},{"cell_type":"code","source":"fig(12, 3)\ndf %>% \n  filter_at(c(\"NU_NOTA_CN\", \"NU_NOTA_CH\", \"NU_NOTA_LC\", \"NU_NOTA_MT\", \"NU_NOTA_REDACAO\"), ~!is.na(.x)) %>%\n  mutate(TP_DEPENDENCIA_ADM_ESC = ifelse(TP_DEPENDENCIA_ADM_ESC==\"Privada\", \n                                         \"Privada\", \"Pública\")) %>% \n  filter(!is.na(TP_DEPENDENCIA_ADM_ESC)) %>% \n  group_by(TP_DEPENDENCIA_ADM_ESC) %>% \n  summarise(n_zeros_lc = sum(NU_NOTA_LC==0),\n            n_zeros_ch = sum(NU_NOTA_CH==0),\n            n_zeros_cn = sum(NU_NOTA_CN==0),\n            n_zeros_mt = sum(NU_NOTA_MT==0),\n            n_zeros_rd = sum(NU_NOTA_REDACAO==0),\n  ) %>% \n  gather(Prova, N_Zeros, -TP_DEPENDENCIA_ADM_ESC) %>% \n  ggplot(aes(y = N_Zeros, x=TP_DEPENDENCIA_ADM_ESC))+\n  geom_bar(stat = 'identity')+\n  facet_wrap(~Prova, nrow = 1)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T03:34:09.342163Z","iopub.execute_input":"2022-02-25T03:34:09.343517Z","iopub.status.idle":"2022-02-25T03:34:10.215706Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-info\"> \n<strong>📌  Interpretação:</strong> <br>\n\n<div style=\"color: rgb(0, 0, 0);\">→ O número de zeros é maior para as escolas públicas, especialmente na redação.</div>\n\n    \n</div>","metadata":{}},{"cell_type":"markdown","source":"### Notas por tipo de escola","metadata":{"execution":{"iopub.status.busy":"2022-02-25T03:07:18.70099Z","iopub.execute_input":"2022-02-25T03:07:18.702717Z","iopub.status.idle":"2022-02-25T03:07:18.713821Z"}}},{"cell_type":"code","source":"fig(16, 6)\ndf %>% \n  filter_at(c(\"NU_NOTA_CN\", \"NU_NOTA_CH\", \"NU_NOTA_LC\", \"NU_NOTA_MT\", \"NU_NOTA_REDACAO\"), ~!is.na(.x)) %>%\n  mutate(TP_DEPENDENCIA_ADM_ESC = ifelse(TP_DEPENDENCIA_ADM_ESC==\"Privada\", \n                                         \"Privada\", \"Pública\")) %>% \n  filter(!is.na(TP_DEPENDENCIA_ADM_ESC))  %>% \n  select(TP_DEPENDENCIA_ADM_ESC, starts_with(\"NU_NOTA\")) %>% \n  gather(Prova, Nota, -TP_DEPENDENCIA_ADM_ESC) %>% \n  ggplot(aes(y = TP_DEPENDENCIA_ADM_ESC, x = Nota)) + \n  ggridges::geom_density_ridges()+\n  scale_x_continuous(breaks = seq(0, 1000, 200))+\n  facet_wrap(TP_DEPENDENCIA_ADM_ESC~Prova, nrow=2)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T04:21:11.792016Z","iopub.execute_input":"2022-02-25T04:21:11.793633Z","iopub.status.idle":"2022-02-25T04:21:16.922261Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-info\"> \n<strong>📌  Interpretação:</strong> <br>\n\n<div style=\"color: rgb(0, 0, 0);\">→ A maior diferença pode ser observada (pelo menos de maneira visual) na nora de ciências da natureza e suas tenologias e matemática</div>\n\n    \n</div>","metadata":{}},{"cell_type":"markdown","source":"### TODO ...\n\n(Em desenvolvimento)","metadata":{}},{"cell_type":"markdown","source":"# Dados dos pedidos de atendimento especializado\n---","metadata":{}},{"cell_type":"code","source":"fig(12, 10)\n\ncols = c(\"IN_BAIXA_VISAO\", \"IN_CEGUEIRA\", \"IN_SURDEZ\", \"IN_DEFICIENCIA_AUDITIVA\",\n\"IN_SURDO_CEGUEIRA\", \"IN_DEFICIENCIA_FISICA\", \"IN_DEFICIENCIA_MENTAL\",\n\"IN_DEFICIT_ATENCAO\", \"IN_DISLEXIA\", \"IN_DISCALCULIA\", \"IN_AUTISMO\",\n\"IN_VISAO_MONOCULAR\", \"IN_OUTRA_DEF\")\n\ndf %>% \n  select(starts_with(\"NU_NOTA\"), all_of(cols)) %>% \n  filter_at(c(\"NU_NOTA_CN\", \"NU_NOTA_CH\", \"NU_NOTA_LC\", \"NU_NOTA_MT\", \"NU_NOTA_REDACAO\"), ~!is.na(.x)) %>% \n  gather(prova, nota, -all_of(cols)) %>% \n  gather(atd_espec, value, -prova, -nota) %>% \n  mutate(prova = str_remove_all(prova, \"NU_NOTA_\"),\n         atd_espec = str_remove_all(atd_espec, \"IN_\")) %>% \n  ggplot(aes(x=prova, y=nota, fill=value))+\n  geom_boxplot(show.legend = F)+\n  theme_bw()+\n  labs(x=\"\", y=\"\")+\n  facet_wrap(~atd_espec)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T03:35:13.412338Z","iopub.execute_input":"2022-02-25T03:35:13.413925Z","iopub.status.idle":"2022-02-25T03:36:57.000494Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-info\"> \n<strong>📌  Interpretação:</strong> <br>\n\n<div style=\"color: rgb(0, 0, 0);\">→ Nota na redação de quem tem dislexia e discalculia foi maior;</div>\n<div style=\"color: rgb(0, 0, 0);\">→ No geral, a nota dos alunos que tiveram atendimento especializado foram menores</div>\n\n    \n</div>","metadata":{}},{"cell_type":"markdown","source":"<div class=\"alert alert-warning\"> \n<strong>💡 Insights!</strong> \n    \n<div style=\"color: rgb(0, 0, 0);\">→ Alunos com deficit de atenção tiveram notas maiores no geral, será que é pelo uso de algum medicamento ou por que alguns tem direito a mais tempo de prova?</div>\n\n</div>\n","metadata":{}},{"cell_type":"markdown","source":"# Dados de pedidos de atendimento especifico\n\nTODO","metadata":{}},{"cell_type":"markdown","source":"# Dados dos pedidos de atendimento específicos para realização da prova\n\nTODO\n\n<!--Nao testei mas imagino que todas essas features possuem correlacao altissima com o atendimento especializado-->","metadata":{}},{"cell_type":"markdown","source":"# Dados do local de aplicação da prova\n\nTODO","metadata":{}},{"cell_type":"markdown","source":"# Dados de questionario sócio econômico\n\nTODO","metadata":{}},{"cell_type":"markdown","source":"# Dados da prova objetiva e da redação\n\n---","metadata":{}},{"cell_type":"markdown","source":"### Districuição das notas","metadata":{}},{"cell_type":"code","source":"fig(12, 4)\ndf %>% \n  filter_at(c(\"NU_NOTA_CN\", \"NU_NOTA_CH\", \"NU_NOTA_LC\", \"NU_NOTA_MT\", \"NU_NOTA_REDACAO\"), ~!is.na(.x)) %>% \n  select(starts_with(\"NU_NOTA\")) %>% \n  gather(Prova, Nota) %>% \n  ggplot(aes(y = Prova, x = Nota)) + \n  ggridges::geom_density_ridges()+\n  scale_x_continuous(breaks = seq(0, 1000, 50))","metadata":{"execution":{"iopub.status.busy":"2022-02-25T03:41:44.708626Z","iopub.execute_input":"2022-02-25T03:41:44.710246Z","iopub.status.idle":"2022-02-25T03:41:47.304821Z"},"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-info\"> \n<strong>📌  Interpretação:</strong> <br>\n\n<div style=\"color: rgb(0, 0, 0);\">→ As notas do caderno de linguas e códigos foi a maior, no geral;</div>\n<div style=\"color: rgb(0, 0, 0);\">→ A nota de redação é a que tem o comportamento mais ruidoso e maior número de zeros;</div>\n<div style=\"color: rgb(0, 0, 0);\">→ Ciências da natureza e matemática foram os que apresentaram menor nota, no geral.</div>\n\n    \n</div>","metadata":{}},{"cell_type":"markdown","source":"### Correlação entre as notas","metadata":{}},{"cell_type":"code","source":"fig(14, 8)\ndf %>% \n  filter_at(c(\"NU_NOTA_CN\", \"NU_NOTA_CH\", \"NU_NOTA_LC\", \"NU_NOTA_MT\", \"NU_NOTA_REDACAO\"), ~!is.na(.x)) %>% \n  group_by(SG_UF_RESIDENCIA) %>% \n  sample_frac(0.1) %>% \n  ungroup() %>% \n  select(starts_with(\"NU_NOTA\")) %>% \n  GGally::ggpairs(upper = list(continuous = GGally::wrap(\"cor\", size = 9)))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-25T04:02:32.978118Z","iopub.execute_input":"2022-02-25T04:02:32.979773Z","iopub.status.idle":"2022-02-25T04:02:59.946764Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-info\"> \n<strong>📌  Interpretação:</strong> <br>\n\n<div style=\"color: rgb(0, 0, 0);\">→ A maior correlação observada foi entre as notas de Linguas e Códigos e e Ciências Humanas;</div>\n<div style=\"color: rgb(0, 0, 0);\">→ Redação é a nota que possui menor correlação com as demais.</div>\n\n    \n</div>","metadata":{}},{"cell_type":"markdown","source":"# Conclusão\n---\n\nPelo menos do que venho analisando até o momento, esta base acaba sendo um retrato da grave desigualdade no brasil.. 🙁","metadata":{}},{"cell_type":"markdown","source":"\n\n<div class=\"alert alert-success\"> \n<strong>👏 Parabéns!</strong> \n    \n<div style=\"color: rgb(0, 0, 0);\">Para finalizar, obrigado e parabéns aos organizadores da competição e também aos demais participantes que estão se esforçando e proporcionado uma competição bem disputada!!</div>\n</div>","metadata":{}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}