{"id":3117,"date":"2021-05-11T09:28:58","date_gmt":"2021-05-11T12:28:58","guid":{"rendered":"https:\/\/www.ufsm.br\/pet\/sistemas-de-informacao\/?p=3117"},"modified":"2025-09-02T14:16:50","modified_gmt":"2025-09-02T17:16:50","slug":"introducao-a-machine-learning","status":"publish","type":"post","link":"https:\/\/www.ufsm.br\/pet\/sistemas-de-informacao\/2021\/05\/11\/introducao-a-machine-learning","title":{"rendered":"Introdu\u00e7\u00e3o \u00e0 Machine Learning"},"content":{"rendered":"\n<p><span style=\"font-weight: 400\">Fala pessoal, no PET Reda\u00e7\u00e3o desta semana iremos entender mais sobre uma das \u00e1reas mais comentadas e que, ao mesmo tempo, mais leva d\u00favidas a qualquer tipo de programador, estamos falando da Intelig\u00eancia Artificial (IA).<\/span><\/p>\n<p><strong>Introdu\u00e7\u00e3o \u00e0 Intelig\u00eancia Artificial<\/strong><\/p>\n<p><span style=\"font-weight: 400\">N\u00e3o \u00e9 de hoje que o termo Intelig\u00eancia Artificial est\u00e1 sendo discutido, ali\u00e1s desde o fim da segunda guerra mundial esse termo vem sendo utilizado, por\u00e9m com as dificuldades tecnol\u00f3gicas da \u00e9poca, n\u00e3o foi poss\u00edvel desenvolver de forma pr\u00e1tica as ideias inicialmente teorizadas.<\/span><\/p>\n<h3>Diferen\u00e7a de termos&nbsp;<\/h3>\n<p><span style=\"font-weight: 400\">Para iniciar o estudo nesta \u00e1rea \u00e9 necess\u00e1rio o entendimento da diferen\u00e7a de alguns termos. Normalmente, quando \u00e9 feita uma pesquisa sobre o tema, aparecem diversos outros termos, como <\/span><i><span style=\"font-weight: 400\">Machine Learning, Deep Learning, Data Science<\/span><\/i><span style=\"font-weight: 400\"> e a pr\u00f3pria Intelig\u00eancia Artificial. O Machine Learning e o Deep Learning pode-se dizer que s\u00e3o sub\u00e1reas da IA e ambos est\u00e3o relacionados ao aprendizado. O Machine Learning \u00e9 o famoso aprendizado de m\u00e1quina e o Deep Learning, por sua vez, pode ser definido como o aprendizado profundo. A diferen\u00e7a entre eles \u00e9 basicamente que o Deep Learning \u00e9 uma sofistic\u00e7\u00e3o do Machine Learning, tanto em requisitos tecnol\u00f3gicos quanto na quantidade de dados necess\u00e1rios. Ent\u00e3o podemos organizar Intelig\u00eancia Artificial, Machine Learning e Deep Learning como no diagrama abaixo:<\/span><\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter wp-image-3127 size-full\" src=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img1.png\" alt=\"\" width=\"817\" height=\"790\" srcset=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img1.png 817w, https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img1-300x290.png 300w, https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img1-768x743.png 768w\" sizes=\"(max-width: 817px) 100vw, 817px\" \/><\/p>\n<p><span style=\"font-weight: 400\">J\u00e1 o Data Science pode ser colocado como outra \u00e1rea, a parte da Intelig\u00eancia Artificial, mas que, ao mesmo tempo, \u00e9 complementar e fundamental. Data Science est\u00e1 relacionado ao tratamento dos dados que ser\u00e3o futuramente utilizados por Intelig\u00eancia Artificial, que pode ser tanto Machine Learning como Deep Learning.<\/span><\/p>\n<h4><span style=\"font-weight: 400\"><strong>Por onde come\u00e7ar?<\/strong><\/span><\/h4>\n<p><span style=\"font-weight: 400\">Uma das maiores d\u00favidas de quem pesquisa sobre o assunto \u00e9: Por onde come\u00e7ar? Qual linguagem devo aprender? Devo fazer algum curso? Essas perguntas s\u00e3o muito comuns j\u00e1 que a Intelig\u00eancia Artificial, por mais que n\u00e3o seja uma \u00e1rea nova como j\u00e1 vimos, come\u00e7ou a ser realmente popular e vi\u00e1vel h\u00e1 apenas alguns anos. Com uma pesquisa breve, a linguagem que mais aparecer\u00e1 conte\u00fado com certeza ser\u00e1 a linguagem Python e talvez algo sobre a linguagem R, por\u00e9m esta \u00faltima \u00e9 mais utilizada para o estudo de Data Science e a estat\u00edstica por tr\u00e1s dos dados que s\u00e3o utilizados, mais tarde, pela Intelig\u00eancia Artificial. A n\u00e3o ser que voc\u00ea domine outra linguagem que tenha aplica\u00e7\u00e3o dentro da \u00e1rea de IA, o Python realmente \u00e9 a melhor op\u00e7\u00e3o j\u00e1 que possui uma curva de aprendizagem relativamente baixa, tem uma sintaxe muito simples, ao mesmo tempo, que muito poderosa e com tecnologias e bibliotecas, que veremos mais tarde, especificamente aplic\u00e1veis \u00e0 IA.<\/span><\/p>\n<h4><strong>Aplica\u00e7\u00f5es<\/strong><\/h4>\n<p><span style=\"font-weight: 400\">Como existem muitas aplica\u00e7\u00f5es dentro da IA, e muitas delas n\u00f3s nem percebemos quando estamos utilizando, \u00e9 complicado saber por onde come\u00e7ar e o que desenvolver primeiro. Os chatbots ou os pr\u00f3prios bots s\u00e3o um dos mais \u201cvis\u00edveis\u201d para o p\u00fablico em geral, por\u00e9m a maioria j\u00e1 possui uma pr\u00e9-programa\u00e7\u00e3o, al\u00e9m de que possivelmente, caso seja aplicado uma IA nesse bot, torne um problema muito complexo para um primeiro momento. Outra tecnologia que \u00e9 considerada mais complexa e muitas pessoas n\u00e3o associam \u00e0 IA em si \u00e9 a an\u00e1lise de imagens. A an\u00e1lise de imagens pode ser de diversos tipos, como an\u00e1lise de texto em imagens, reconhecimento facial, reconhecimento de objetos em geral, etc. Al\u00e9m disso, existem in\u00fameras outras aplica\u00e7\u00f5es, como sistemas de recomenda\u00e7\u00e3o de conte\u00fado ou produtos, assist\u00eancia pessoal e no pr\u00f3prio ensino, por mais que n\u00e3o seja amplamente utilizado por enquanto. Por\u00e9m, para iniciar os estudos nesse mundo, a melhor forma e mais simples \u00e9 utilizando dados e criando um sistema de predi\u00e7\u00e3o comum, que consegue, a partir dos dados recebidos, aprender com eles e fazer classifica\u00e7\u00f5es e previs\u00f5es. A melhor forma de conseguir dados para usar como exemplo \u00e9 a partir da plataforma <\/span><a href=\"https:\/\/www.kaggle.com\/\"><span style=\"font-weight: 400\">Kaggle<\/span><\/a><span style=\"font-weight: 400\">. A plataforma Kaggle al\u00e9m de possuir diversas bases de dados, sobre os mais diversos assuntos, tamb\u00e9m possui desafios para quem quer aplicar os conhecimentos de IA e Machine Learning e, ao mesmo tempo, competir e concorrer a pr\u00eamios dependendo do desempenho do participante.<\/span><\/p>\n<h4><strong>Desenvolvimento<\/strong><\/h4>\n<p><span style=\"font-weight: 400\">Entrando na parte pr\u00e1tica, desenvolvemos uma aplica\u00e7\u00e3o de Machine Learning simples, utilizando uma base de dados com registro de sal\u00e1rios em rela\u00e7\u00e3o a anos de experi\u00eancia, ent\u00e3o o que iremos fazer \u00e9 criar uma aplica\u00e7\u00e3o que tenta prever o sal\u00e1rio de algu\u00e9m baseado nos anos de experi\u00eancia. Antes de iniciar o desenvolvimento, \u00e9 preciso fazer algumas instala\u00e7\u00f5es e configurar o ambiente. Primeiramente, ser\u00e1 necess\u00e1rio a instala\u00e7\u00e3o do <\/span><a href=\"https:\/\/www.jetbrains.com\/pt-br\/pycharm\/download\/\"><span style=\"font-weight: 400\">Pycharm<\/span><\/a><span style=\"font-weight: 400\">, que ser\u00e1 a IDE utilizada, e o Python, neste <\/span><a href=\"https:\/\/www.python.org\/downloads\/\"><span style=\"font-weight: 400\">link<\/span><\/a><span style=\"font-weight: 400\"> para o Windows e para Linux deve ser executado os seguintes comandos:<\/span><\/p>\n<p><img decoding=\"async\" class=\"aligncenter wp-image-3130 size-full\" src=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img2.png\" alt=\"\" width=\"602\" height=\"51\" srcset=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img2.png 602w, https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img2-300x25.png 300w\" sizes=\"(max-width: 602px) 100vw, 602px\" \/><\/p>\n<p><span style=\"font-weight: 400\">Este comando ir\u00e1 instalar tanto o Python quanto o PIP que \u00e9 o <\/span><i><span style=\"font-weight: 400\">Gerenciador de Pacotes<\/span><\/i><span style=\"font-weight: 400\"> nativo do Python, que serve para instalar depend\u00eancias\/bibliotecas dentro do seu projeto.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Para utilizar os <\/span><i><span style=\"font-weight: 400\">Data sets <\/span><\/i><span style=\"font-weight: 400\">(conjuntos de dados)<\/span> <span style=\"font-weight: 400\">da plataforma Kaggle \u00e9 necess\u00e1rio criar uma conta dentro da plataforma. Ap\u00f3s isso, acesse o Data set Salary a partir deste <\/span><a href=\"https:\/\/www.kaggle.com\/rsadiq\/salary\"><span style=\"font-weight: 400\">link<\/span><\/a><span style=\"font-weight: 400\"> e fa\u00e7a download do arquivo <\/span><i><span style=\"font-weight: 400\">Salary.csv<\/span><\/i><span style=\"font-weight: 400\">. Basicamente, um arquivo <\/span><i><span style=\"font-weight: 400\">csv<\/span><\/i><span style=\"font-weight: 400\"> armazena informa\u00e7\u00f5es separadas por v\u00edrgula e \u00e9 muito utilizado em Data sets para Machine Learning. O arquivo <\/span><i><span style=\"font-weight: 400\">Salary.csv <\/span><\/i><span style=\"font-weight: 400\">possui informa\u00e7\u00f5es do sal\u00e1rio e dos anos de experi\u00eancia de 35 empregados.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Abrindo o Pycharm, deve-se ver algo parecido com a imagem abaixo. Agora, clique no bot\u00e3o <\/span><i><span style=\"font-weight: 400\">New Project<\/span><\/i><span style=\"font-weight: 400\"> e nomeie seu projeto e escolha onde ele ser\u00e1 salvo.<\/span><\/p>\n<p><img decoding=\"async\" class=\"aligncenter wp-image-3129 size-full\" src=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img3.png\" alt=\"\" width=\"799\" height=\"335\" srcset=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img3.png 799w, https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img3-300x126.png 300w, https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img3-768x322.png 768w\" sizes=\"(max-width: 799px) 100vw, 799px\" \/><\/p>\n<p><span style=\"font-weight: 400\">Ap\u00f3s a cria\u00e7\u00e3o do projeto, poder\u00e1 ser visto um c\u00f3digo padr\u00e3o em um arquivo chamado <\/span><i><span style=\"font-weight: 400\">main.py<\/span><\/i><span style=\"font-weight: 400\">, por\u00e9m este c\u00f3digo pode ser totalmente apagado, pois usaremos este arquivo para colocar nosso c\u00f3digo.&nbsp;<\/span><\/p>\n<p><span style=\"font-weight: 400\">O primeiro passo a ser feito \u00e9 instalar algumas depend\u00eancias\/bibliotecas que ser\u00e3o usadas tanto para o Machine Learning quanto para a visualiza\u00e7\u00e3o dos resultados. No canto inferior esquerdo do Pycharm, clique em <\/span><i><span style=\"font-weight: 400\">Terminal<\/span><\/i><span style=\"font-weight: 400\"> e execute os seguintes comandos (para Linux e Windows):<\/span><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-3128 size-full\" src=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img4.png\" alt=\"\" width=\"601\" height=\"100\" srcset=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img4.png 601w, https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img4-300x50.png 300w\" sizes=\"(max-width: 601px) 100vw, 601px\" \/><\/p>\n<p><span style=\"font-weight: 400\">De forma simplificada, <\/span><i><span style=\"font-weight: 400\">Pandas<\/span><\/i><span style=\"font-weight: 400\"> \u00e9 uma biblioteca Python criada para an\u00e1lise e manipula\u00e7\u00e3o de dados, por exemplo, mexer com arquivos <\/span><i><span style=\"font-weight: 400\">csv<\/span><\/i><span style=\"font-weight: 400\">. J\u00e1 o <\/span><i><span style=\"font-weight: 400\">sklearn<\/span><\/i><span style=\"font-weight: 400\"> ou <\/span><i><span style=\"font-weight: 400\">scikit-learn<\/span><\/i><span style=\"font-weight: 400\"> \u00e9 uma biblioteca desenvolvida especificamente para aplicar Machine Learning, possuindo diversas ferramentas\/fun\u00e7\u00f5es para auxiliar e facilitar a implementa\u00e7\u00e3o. Por fim, a <\/span><i><span style=\"font-weight: 400\">matplotlib<\/span><\/i><span style=\"font-weight: 400\"> \u00e9 uma biblioteca que permite uma apresenta\u00e7\u00e3o melhor dos dados a partir da cria\u00e7\u00e3o de gr\u00e1ficos, j\u00e1 que muitas vezes \u00e9 complicado entender os resultados apenas pelos n\u00fameros.&nbsp;<\/span><\/p>\n<p><span style=\"font-weight: 400\">Antes de iniciar o c\u00f3digo \u00e9 importante que o arquivo <\/span><i><span style=\"font-weight: 400\">Salary.csv<\/span><\/i><span style=\"font-weight: 400\">, que foi instalado anteriormente, seja movido para a pasta do projeto. O caminho do projeto pode ser visto ao lado do nome do projeto, copie ou recorte o arquivo e coloque dentro da pasta principal do projeto, como na imagem abaixo:<\/span><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-3126 size-full\" src=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img5.png\" alt=\"\" width=\"318\" height=\"175\" srcset=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img5.png 318w, https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img5-300x165.png 300w\" sizes=\"(max-width: 318px) 100vw, 318px\" \/><\/p>\n<p><span style=\"font-weight: 400\">O primeiro passo no desenvolvimento \u00e9 importar as bibliotecas, que foram instaladas, para serem usadas dentro do c\u00f3digo. A importa\u00e7\u00e3o das depend\u00eancias pode ser feita da seguinte maneira:<\/span><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-3125 size-full\" src=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img6.png\" alt=\"\" width=\"792\" height=\"86\" srcset=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img6.png 792w, https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img6-300x33.png 300w, https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img6-768x83.png 768w\" sizes=\"(max-width: 792px) 100vw, 792px\" \/><\/p>\n<p><span style=\"font-weight: 400\">A cor do texto ficar\u00e1 dessa forma at\u00e9 elas serem utilizadas dentro do c\u00f3digo. O primeiro <\/span><i><span style=\"font-weight: 400\">import <\/span><\/i><span style=\"font-weight: 400\">\u00e9 da biblioteca inteira do <\/span><i><span style=\"font-weight: 400\">pandas <\/span><\/i><span style=\"font-weight: 400\">e podemos acessar as fun\u00e7\u00f5es a partir da vari\u00e1vel pd, que foi definida na imagem acima (pode ser qualquer outro nome). O segundo <\/span><i><span style=\"font-weight: 400\">import<\/span><\/i><span style=\"font-weight: 400\"> \u00e9 de uma das interfaces da biblioteca <\/span><i><span style=\"font-weight: 400\">matplotlib<\/span><\/i><span style=\"font-weight: 400\">, utilizada para casos mais simples, a <\/span><i><span style=\"font-weight: 400\">pyplot<\/span><\/i><span style=\"font-weight: 400\">, que poder\u00e1 sempre acessada a partir da vari\u00e1vel <\/span><i><span style=\"font-weight: 400\">plt<\/span><\/i><span style=\"font-weight: 400\">. O terceiro <\/span><i><span style=\"font-weight: 400\">import<\/span><\/i><span style=\"font-weight: 400\"> \u00e9 de uma classes dos modelos lineares do <\/span><i><span style=\"font-weight: 400\">sklearn<\/span><\/i><span style=\"font-weight: 400\">, o <\/span><i><span style=\"font-weight: 400\">LinearRegression<\/span><\/i><span style=\"font-weight: 400\"> (Regress\u00e3o Linear), que \u00e9 uma das formas mais simples de previs\u00e3o tanto na matem\u00e1tica quanto no Machine Learning. A partir dessa classe pode-se acessar alguns m\u00e9todos\/fun\u00e7\u00f5es importantes para a aplica\u00e7\u00e3o. O \u00faltimo <\/span><i><span style=\"font-weight: 400\">import<\/span><\/i><span style=\"font-weight: 400\"> \u00e9 de uma fun\u00e7\u00e3o chamada <\/span><i><span style=\"font-weight: 400\">train_test_split<\/span><\/i><span style=\"font-weight: 400\">, que serve para dividir os dados do nosso arquivo <\/span><i><span style=\"font-weight: 400\">csv<\/span><\/i><span style=\"font-weight: 400\"> em train (treino) e test (teste), dessa forma pode-se usar uma parte dos dados para treinar nossa aplica\u00e7\u00e3o de Machine Learning e a outra parte para fazer testes, impedindo que o nossa aplica\u00e7\u00e3o fique \u201cviciada\u201d, pois estaria testando sempre com os mesmos dados.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Para iniciar a implementa\u00e7\u00e3o do c\u00f3digo em si podemos come\u00e7ar lendo o arquivo <\/span><i><span style=\"font-weight: 400\">Salary.csv<\/span><\/i><span style=\"font-weight: 400\"> e imprimir todos os dados lidos, como na figura abaixo:<\/span><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-3124 size-full\" src=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img7.png\" alt=\"\" width=\"612\" height=\"80\" srcset=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img7.png 612w, https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img7-300x39.png 300w\" sizes=\"(max-width: 612px) 100vw, 612px\" \/><\/p>\n<p><span style=\"font-weight: 400\">Cria-se a vari\u00e1vel data para armazenar os dados que vem do arquivo <\/span><i><span style=\"font-weight: 400\">csv<\/span><\/i><span style=\"font-weight: 400\"> e para ler o arquivo utiliza-se a vari\u00e1vel da biblioteca <\/span><i><span style=\"font-weight: 400\">pandas<\/span><\/i><span style=\"font-weight: 400\">, que foi definida nos <\/span><i><span style=\"font-weight: 400\">imports<\/span><\/i><span style=\"font-weight: 400\"> acima, para acessar uma fun\u00e7\u00e3o chamada <\/span><i><span style=\"font-weight: 400\">read_csv<\/span><\/i><span style=\"font-weight: 400\">, que faz a leitura de um arquivo csv e retorna um DataFrame (quadro de dados), com o nome das colunas e as informa\u00e7\u00f5es. Depois colocamos um <\/span><i><span style=\"font-weight: 400\">print(data)<\/span><\/i><span style=\"font-weight: 400\"> para mostrar as 35 linhas provenientes da vari\u00e1vel <\/span><i><span style=\"font-weight: 400\">data<\/span><\/i><span style=\"font-weight: 400\">, que cont\u00e9m todos os dados.&nbsp;<\/span><\/p>\n<p><span style=\"font-weight: 400\">Clique <\/span><i><span style=\"font-weight: 400\">Shift + F10<\/span><\/i><span style=\"font-weight: 400\"> ou <\/span><i><span style=\"font-weight: 400\">Shift + Fn + F10<\/span><\/i><span style=\"font-weight: 400\"> para executar o c\u00f3digo e visualizar os dados na parte inferior do <\/span><i><span style=\"font-weight: 400\">Pycharm<\/span><\/i><span style=\"font-weight: 400\">.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Como comentamos anteriormente, teremos que dividir os dados em train (treino) e test (teste), mas tamb\u00e9m \u00e9 importante separar as colunas do sal\u00e1rio e anos de experi\u00eancia, para que possam ser analisados isoladamente. Para isso, escreva o seguinte c\u00f3digo:<\/span><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-3123 size-full\" src=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img8.png\" alt=\"\" width=\"757\" height=\"80\" srcset=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img8.png 757w, https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img8-300x32.png 300w\" sizes=\"(max-width: 757px) 100vw, 757px\" \/><\/p>\n<p><span style=\"font-weight: 400\">Cria-se a vari\u00e1vel <\/span><i><span style=\"font-weight: 400\">x <\/span><\/i><span style=\"font-weight: 400\">para armazenar a coluna dos anos de experi\u00eancia e a vari\u00e1vel y para armazenar a coluna do sal\u00e1rio, utilizando o m\u00e9todo de sele\u00e7\u00e3o <\/span><i><span style=\"font-weight: 400\">iloc<\/span><\/i><span style=\"font-weight: 400\">, que seleciona dados a partir de n\u00fameros e retorna um <\/span><i><span style=\"font-weight: 400\">array<\/span><\/i><span style=\"font-weight: 400\">. Nesse caso, estamos selecionando todos os 35 dados de cada coluna. Ap\u00f3s isso, cria-se 4 vari\u00e1veis, um train e um test para cada coluna, para fazermos a separa\u00e7\u00e3o a partir da fun\u00e7\u00e3o <\/span><i><span style=\"font-weight: 400\">train_test_split()<\/span><\/i><span style=\"font-weight: 400\">, que recebe como par\u00e2metros: o <\/span><i><span style=\"font-weight: 400\">x <\/span><\/i><span style=\"font-weight: 400\">(array dos anos de experi\u00eancia), o <\/span><i><span style=\"font-weight: 400\">y <\/span><\/i><span style=\"font-weight: 400\">(array do sal\u00e1rio), o <\/span><i><span style=\"font-weight: 400\">test_size<\/span><\/i><span style=\"font-weight: 400\"> (porcentagem dos dados que ir\u00e3o para teste) e o <\/span><i><span style=\"font-weight: 400\">random_state<\/span><\/i><span style=\"font-weight: 400\"> (define se a divis\u00e3o vai ser embaralhada toda vez que o programa for executado). No <\/span><i><span style=\"font-weight: 400\">test_size<\/span><\/i><span style=\"font-weight: 400\"> passamos o valor 0.3, que significa que 30% dos dados ser\u00e3o de teste e o resto vai ser treino. J\u00e1 no random_state passamos o valor 0 (ou qualquer outro n\u00famero), isso significa que os valores de teste e treino sempre ser\u00e3o os mesmos, servindo para verificar se a aplica\u00e7\u00e3o est\u00e1 correta, por\u00e9m podemos excluir esse par\u00e2metro depois para deixar totalmente aleat\u00f3rio. Uma observa\u00e7\u00e3o: as vari\u00e1veis de train e test devem estar na ordem mostrada na imagem, pois o valor que elas recebem prov\u00e9m da fun\u00e7\u00e3o <\/span><i><span style=\"font-weight: 400\">train_test_split()<\/span><\/i><span style=\"font-weight: 400\">, que possui essa ordem por padr\u00e3o.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Agora vamos come\u00e7ar a treinar a aplica\u00e7\u00e3o a partir dos dados de treino e criar a previs\u00e3o a partir dos dados de teste, o que \u00e9 extremamente simples utilizando o <\/span><i><span style=\"font-weight: 400\">sklearn<\/span><\/i><span style=\"font-weight: 400\">. Confira o c\u00f3digo abaixo:<\/span><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-3122 size-full\" src=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img9.png\" alt=\"\" width=\"711\" height=\"120\" srcset=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img9.png 711w, https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img9-300x51.png 300w\" sizes=\"(max-width: 711px) 100vw, 711px\" \/><\/p>\n<p><span style=\"font-weight: 400\">Cria-se uma vari\u00e1vel <\/span><i><span style=\"font-weight: 400\">model<\/span><\/i><span style=\"font-weight: 400\">, referente a modelo, que ser\u00e1 do tipo <\/span><i><span style=\"font-weight: 400\">LinearRegression<\/span><\/i><span style=\"font-weight: 400\"> (classe), dessa forma podendo acessar todos os m\u00e9todos desta classe. O <\/span><i><span style=\"font-weight: 400\">fit<\/span><\/i><span style=\"font-weight: 400\"> \u00e9 um m\u00e9todo da classe <\/span><i><span style=\"font-weight: 400\">LinearRegression<\/span><\/i><span style=\"font-weight: 400\">, que recebe os dados de treino e \u201cse adapta\u201d a partir deles, ou seja, o nosso modelo vai tentar aprender com esse conjunto de informa\u00e7\u00f5es, fazendo rela\u00e7\u00f5es entre eles. Ap\u00f3s isso, cria-se uma vari\u00e1vel, chamada <\/span><i><span style=\"font-weight: 400\">predictions<\/span><\/i><span style=\"font-weight: 400\">, para armazenar as previs\u00f5es que esse modelo far\u00e1 a partir do que foi aprendido. Para isso, utiliza-se a fun\u00e7\u00e3o <\/span><i><span style=\"font-weight: 400\">predict<\/span><\/i><span style=\"font-weight: 400\">, que recebe o <\/span><i><span style=\"font-weight: 400\">x_test<\/span><\/i><span style=\"font-weight: 400\"> (anos de experi\u00eancia) e tenta prever qual sal\u00e1rio cada um desses anos de experi\u00eancia teriam, baseado nas an\u00e1lises feitas na fun\u00e7\u00e3o <\/span><i><span style=\"font-weight: 400\">fit<\/span><\/i><span style=\"font-weight: 400\">. Por \u00faltimo, utiliza-se o <\/span><i><span style=\"font-weight: 400\">print<\/span><\/i><span style=\"font-weight: 400\"> para visualizar e comparar os valores que o algoritmo previu com os valores reais dos sal\u00e1rios dos anos de experi\u00eancia informados. Definindo o <\/span><i><span style=\"font-weight: 400\">random_state<\/span><\/i><span style=\"font-weight: 400\"> como 0, os resultados devem ser esses:<\/span><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-3121 size-full\" src=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img10.png\" alt=\"\" width=\"578\" height=\"112\" srcset=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img10.png 578w, https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img10-300x58.png 300w\" sizes=\"(max-width: 578px) 100vw, 578px\" \/><\/p>\n<p><span style=\"font-weight: 400\">Para uma melhor visualiza\u00e7\u00e3o dos resultados, o matplotlib possui algumas fun\u00e7\u00f5es simples para cria\u00e7\u00e3o de gr\u00e1ficos de regress\u00e3o linear. Confira o c\u00f3digo:<\/span><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-3120 size-full\" src=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img11.png\" alt=\"\" width=\"700\" height=\"89\" srcset=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img11.png 700w, https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img11-300x38.png 300w\" sizes=\"(max-width: 700px) 100vw, 700px\" \/><\/p>\n<p><span style=\"font-weight: 400\">Utiliza-se da vari\u00e1vel <\/span><i><span style=\"font-weight: 400\">plt<\/span><\/i><span style=\"font-weight: 400\">, declarada anteriormente nos <\/span><i><span style=\"font-weight: 400\">imports<\/span><\/i><span style=\"font-weight: 400\">, para acessar algumas fun\u00e7\u00f5es b\u00e1sicas da biblioteca, como a <\/span><i><span style=\"font-weight: 400\">scatter<\/span><\/i><span style=\"font-weight: 400\">, que coloca pontos em um plano cartesiano a partir de uma posi\u00e7\u00e3o x e y informada, al\u00e9m da defini\u00e7\u00e3o da colora\u00e7\u00e3o dos pontos (nesse caso vermelho). Na fun\u00e7\u00e3o <\/span><i><span style=\"font-weight: 400\">scatter<\/span><\/i><span style=\"font-weight: 400\">, informa-se os dados corretos, de acordo com o arquivo <\/span><i><span style=\"font-weight: 400\">Salary.csv<\/span><\/i><span style=\"font-weight: 400\">, para comparar com as previs\u00f5es feitas. A fun\u00e7\u00e3o plot cria uma reta baseada nos dados dos anos de experi\u00eancia e nas previs\u00f5es de sal\u00e1rio realizadas pelo algoritmo. Por fim, utiliza-se a fun\u00e7\u00e3o <\/span><i><span style=\"font-weight: 400\">show<\/span><\/i><span style=\"font-weight: 400\"> para mostrar o gr\u00e1fico. Agora podemos executar o programa e, caso o <\/span><i><span style=\"font-weight: 400\">random_state<\/span><\/i><span style=\"font-weight: 400\"> seja igual a 0, o resultado \u00e9 esse:<\/span><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-3119 size-full\" src=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img12.png\" alt=\"\" width=\"576\" height=\"415\" srcset=\"https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img12.png 576w, https:\/\/www.ufsm.br\/app\/uploads\/sites\/791\/2021\/05\/img12-300x216.png 300w\" sizes=\"(max-width: 576px) 100vw, 576px\" \/><\/p>\n<p><span style=\"font-weight: 400\">Com isso, podemos conhecer um pouco mais da \u00e1rea de Intelig\u00eancia Artificial e suas diversas sub\u00e1reas, assim como entender melhor como uma aplica\u00e7\u00e3o de Machine Learning funciona na pr\u00e1tica. Caso tenha alguma d\u00favida ou queira um minicurso sobre o assunto futuramente, entre em contato com os petianos.<\/span><\/p>\n<p>&nbsp;<\/p>\n<p><span style=\"font-weight: 400\">Refer\u00eancias<\/span><\/p>\n<ul>\n<li style=\"font-weight: 400\"><a href=\"https:\/\/www.salesforce.com\/br\/blog\/2018\/4\/Machine-Learning-e-Deep-Learning-aprenda-as-diferencas.html\"><span style=\"font-weight: 400\">Diferen\u00e7as de termos<\/span><\/a><\/li>\n<li style=\"font-weight: 400\"><a href=\"https:\/\/stefanini.com\/pt-br\/trends\/artigos\/as-7-principais-aplicacoes-de-inteligencia-artificial-nas-empres\"><span style=\"font-weight: 400\">Aplica\u00e7\u00f5es IA<\/span><\/a><\/li>\n<li style=\"font-weight: 400\"><a href=\"https:\/\/scikit-learn.org\/stable\/index.html\"><span style=\"font-weight: 400\">Documenta\u00e7\u00e3o sklearn<\/span><\/a><\/li>\n<li style=\"font-weight: 400\"><a href=\"https:\/\/pandas.pydata.org\/docs\/index.html\"><span style=\"font-weight: 400\">Documenta\u00e7\u00e3o pandas<\/span><\/a><\/li>\n<li style=\"font-weight: 400\"><a href=\"https:\/\/matplotlib.org\/stable\/contents.html\"><span style=\"font-weight: 400\">Documenta\u00e7\u00e3o matplotlib<\/span><\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Fala pessoal, no PET Reda\u00e7\u00e3o desta semana iremos entender mais sobre uma das \u00e1reas mais comentadas e que, ao mesmo tempo, mais leva d\u00favidas a qualquer tipo de programador, estamos falando da Intelig\u00eancia Artificial (IA). Introdu\u00e7\u00e3o \u00e0 Intelig\u00eancia Artificial N\u00e3o \u00e9 de hoje que o termo Intelig\u00eancia Artificial est\u00e1 sendo discutido, ali\u00e1s desde o fim [&hellip;]<\/p>\n","protected":false},"author":2948,"featured_media":3118,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[124,112],"tags":[202,149],"class_list":["post-3117","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-destaques","category-redacao","tag-ia","tag-redacao"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ufsm.br\/pet\/sistemas-de-informacao\/wp-json\/wp\/v2\/posts\/3117","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ufsm.br\/pet\/sistemas-de-informacao\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.ufsm.br\/pet\/sistemas-de-informacao\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.ufsm.br\/pet\/sistemas-de-informacao\/wp-json\/wp\/v2\/users\/2948"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ufsm.br\/pet\/sistemas-de-informacao\/wp-json\/wp\/v2\/comments?post=3117"}],"version-history":[{"count":0,"href":"https:\/\/www.ufsm.br\/pet\/sistemas-de-informacao\/wp-json\/wp\/v2\/posts\/3117\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ufsm.br\/pet\/sistemas-de-informacao\/wp-json\/wp\/v2\/media\/3118"}],"wp:attachment":[{"href":"https:\/\/www.ufsm.br\/pet\/sistemas-de-informacao\/wp-json\/wp\/v2\/media?parent=3117"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.ufsm.br\/pet\/sistemas-de-informacao\/wp-json\/wp\/v2\/categories?post=3117"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.ufsm.br\/pet\/sistemas-de-informacao\/wp-json\/wp\/v2\/tags?post=3117"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}