<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Diegorn on Medium]]></title>
        <description><![CDATA[Stories by Diegorn on Medium]]></description>
        <link>https://medium.com/@diego25rn?source=rss-1193ba6f2431------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3kFO54H42uZKbMkO</url>
            <title>Stories by Diegorn on Medium</title>
            <link>https://medium.com/@diego25rn?source=rss-1193ba6f2431------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 04:40:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@diego25rn/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Aplicativo streamlit para um estudo de caso em machine learning com o dataset MNIST]]></title>
            <link>https://medium.com/@diego25rn/aplicativo-streamlit-para-um-estudo-de-caso-em-machine-learning-5f32c3f8a80d?source=rss-1193ba6f2431------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f32c3f8a80d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mnist]]></category>
            <category><![CDATA[streamlit-app-deployment]]></category>
            <dc:creator><![CDATA[Diegorn]]></dc:creator>
            <pubDate>Wed, 27 Jul 2022 01:20:25 GMT</pubDate>
            <atom:updated>2022-07-27T01:53:04.065Z</atom:updated>
            <content:encoded><![CDATA[<p>Vamos neste texto propor um estudo de caso em machine learning com o dataset de digitos escritos à mão MNIST para ilustrar o processamento de imagens para predição em um aplicativo, bem como formular um pipeline de machine learning com tensorflow e a plataforma Weights and biases para a organização desse pipeline.</p><h4><strong>Introdução</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Fr1ae7efYAENB4E4GGUgw.png" /><figcaption>MNIST Dataset</figcaption></figure><p>Um dos conjuntos de dados mais utilizados quando se está estudando machine learning com o tensorflow, é o MNIST. Os dados consistem em imagens de dígitos escritos à mão. Todas as imagens estão em tons de cinza em proporções 28X28.</p><p>Como mencionado anteriormente, é um conjunto de dados muito conhecido na comunidade de machine learning. Entretanto, uma coisa que não é tão abordada é o tratamento de novos dados tanto para uma predição no modelo criado com a MNIST, quanto para o ré-treino do modelo quando os resultados não estão mais satisfatórios. Abaixo, um exemplo de imagem com vários dígitos escritos à mão.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*TQ_bDjIqdku-TkrLwnCJ9Q.png" /></figure><p>Nesse contexto de preparar novos dados, estamos propondo um pequeno projeto com a biblioteca streamlit para ilustrar o processamento dessas imagens após o sistema estar em produção. Além disso, também será mostrado todo o pipeline de criação dos modelos em uma abordagem de mlops com boas práticas de machine learning.</p><h4><strong>Aquisição dos dados</strong></h4><p>Como o dataset do MNIST é muito utilizado o tensorflow 2.0 já possui esse conjunto de dados em seus módulos. Então para fazer o download dos dados diretamente do tensorflow 2.0 a gente pode simplesmente digitar o seguinte trecho de código que o dataset já é carregado para as variáveis de treino e de teste:</p><pre>(x_train, y_train),(x_test, y_test)=keras.datasets.mnist.load_data()</pre><p>Entretanto no intuito de lidar com o dado um pouco mas bruto, fizemos o download do zip disponível no link: <a href="http://yann.lecun.com/exdb/mnist/">http://yann.lecun.com/exdb/mnist/</a>. Depois de feito o download usamos o seguinte comando no terminal para fazer o upload dos dados para o wandb:</p><pre>!wandb artifact put \<br>— name nome_projeto/mnist_data.gz \<br>— type gzip \<br>— description “The train from mnist” train-images-idx3-ubyte.gz</pre><p>O intuito de subirmos os dados iniciais para que o wandb é para tenhamos um versionamento dos dados para cada etapa do pipeline de machine learning que planejamos para o projeto.</p><h4>…</h4><p>O pipeline que utilizamos para criar o modelo de predição tem somente 4 etapas sendo elas, o download dos dados, o pré-processamento escalando os valores de tons de cinza entre 0 e 1, o treino do modelo(Essa etapa engloba o hyperparameter tuning e testes com métricas do modelo). Por último o deploy do app que vai consumir o modelo e os “novos dados”. Próximo paragrafo é o pré-processamento.</p><h4><strong>Pré-processamento</strong></h4><p>O pré-processamento do conjunto de dados escolhido é simplesmente dividir os dados de treino e de teste por 255. Essa operação é feita para que os pesos converjam relativamente mais rápido na rede neural. Como as imagens em tons de cinza são representadas como matrizes de inteiros indo de 0 a 255, todos os tons de cinza terão valores no intervalo de 0 a 1.</p><p>A sequência do pré-processamento é a seguinte:</p><pre># chamamos um run do wandb para baixarmos os dados<br>run = wandb.init(<em>project</em>=&quot;nome_projeto&quot;, <em>save_code</em>=True,<em>job_type</em>=&#39;preprocessing&#39;)</pre><pre># baixamos o dataset<br>dataset = &#39;mnist.gz&#39;<br>artifact = run.use_artifact(f&quot;nome_projeto/ {dataset}:latest&quot;)<br>artifact.file()</pre><pre># abrimos o dataset com gzip e idx2numpy<br><em>with</em> gzip.open(artifact.file(), &#39;r&#39;) <em>as</em> f:<br>     X = idx2numpy.convert_from_file(f)</pre><pre># realizamos a operação de normalização<br>X = X / 255.0</pre><pre># salvamos os dados processados, comprimidos<br>np.savez_compressed(&quot;preprocessed_X&quot;,<em>imgs</em> = X)</pre><pre># fazemos o upload para o wandb<br>!wandb artifact put \<br>--name nome_projeto/preprocessed_X.npz \<br>--type npz \<br>--description &quot;normalized images from mnist&quot; preprocessed_X.npz</pre><p>O nosso pipeline é orientado a artefatos para que possamos criar um controle de versão sobre os dados utilizados em cada etapa da construção do modelo. Agora que nossos dados estão pré-processados vamos para o treinamento.</p><h4>Treinamento</h4><p>Para o treinamento fazemos o download dos dados normalizados resultantes do pré-processamento para dar inicio aos testes de melhores modelos. Para a criação dos modelos usamos a biblioteca tensorflow 2.0, com o tensorflow criamos uma rede neural com uma camada de “flatten” para transformar as imagens bidimensionais em um formato de vetor unidimensional, em seguida temos duas camadas escondidas intercaladas por uma camada de Batchnormalization, e por último na camada de saída temos 10 saídas numéricas dando a probabilidade de cada digito após a predição.</p><p>Essa rede neural foi construida utilizando o seguinte código:</p><pre>model = keras.Sequential([<br>    keras.layers.Flatten(<em>input_shape</em>=(28, 28)),<br>    keras.layers.Dense(128, <em>activation</em>=&#39;relu&#39;),<br>    keras.layers.BatchNormalization(),<br>    keras.layers.Dense(128, <em>activation</em>=&#39;relu&#39;),   <br>    keras.layers.Dense(10, <em>activation</em>=&#39;softmax&#39;)])</pre><p>É relativamente simples a criação de uma rede neural utilizando o keras no tensorflow 2.0, difícil mesmo é encontrar os melhores hiperparametros para treinamento da rede.</p><p>Para encontrar os melhores hiperparâmetros, organizamos a nossa rede neural em uma função chamada “train” que engloba a criação do modelo e o treinamento com callback para o wandb monitorar os hiperparâmetros.</p><pre># baseado nos códigos do github do professor Dr. Ivanovitch Silva<br># <a href="https://github.com/ivanovitchm/ppgeecmachinelearning">https://github.com/ivanovitchm/ppgeecmachinelearning</a><br>def train():<br><em># Default values for hyper-parameters we&#39;re going to sweep over<br></em>defaults = dict(<em>layer_1</em> = 100,<em>layer_2</em> = 100,<br><em>batch_size</em> = 32,<em>learn_rate</em> = 0.001,<em>epoch</em> = 20)</pre><pre>wandb.init(<em>project</em>=&quot;nome_projeto&quot;,<em>save_code</em>=True,<em>job_type</em>=&#39;train&#39;, <em>config</em>= defaults)</pre><pre><em># Config is a variable that holds and saves hyperparameters and inputs<br></em>config = wandb.config</pre><pre><em># Instantiate a simple classification model<br></em>model = keras.Sequential([<br>  keras.layers.Flatten(<em>input_shape</em>=(28, 28)),<br>  keras.layers.Dense(config.layer_1, <em>activation</em>=&#39;relu&#39;,   <em>dtype</em>=&#39;float64&#39;),<br>  keras.layers.BatchNormalization(),<br>  keras.layers.Dense(config.layer_2, <em>activation</em>=&#39;relu&#39;,     <em>dtype</em>=&#39;float64&#39;),<br>  keras.layers.Dense(10, <em>activation</em>=&#39;softmax&#39;, <em>dtype</em>=&#39;float64&#39;)</pre><pre>])</pre><pre>model.compile(<em>optimizer</em>=&#39;adam&#39;,</pre><pre><em>loss</em>=&#39;sparse_categorical_crossentropy&#39;,</pre><pre><em>metrics</em>=[&#39;accuracy&#39;])</pre><pre>model.fit(<em>x</em>=x_train,<em>y</em>=y_train,<br>  <em>batch_size</em>=config.batch_size,<br>  <em>epochs</em>=config.epoch,<br>  <em>validation_data</em>=(x_test,y_test),<br>  <em>callbacks</em>=[WandbCallback(<em>log_weights</em>=True)],<em>verbose</em>=1)</pre><p>Com a função de treinamento definida, a próxima etapa é determinar um conjunto de possibilidades dos hiperparâmetros que são possíveis para a rede neural que desejamos treinar. Fazemos isso criando uma variável dicionário que armazena essas possibilidades.</p><pre>sweep_config = {<br>  &#39;method&#39;: &#39;random&#39;, <em><br>  </em>&#39;metric&#39;: {<br>    &#39;name&#39;: &#39;accuracy&#39;,<br>    &#39;goal&#39;: &#39;maximize&#39;<br>  },<br>  &#39;parameters&#39;: {<br>  &#39;layer_1&#39;: {<br>    &#39;max&#39;: 130,<br>    &#39;min&#39;: 110,<br>    &#39;distribution&#39;: &#39;int_uniform&#39;,<br>  },<br>  &#39;layer_2&#39;: {<br>    &#39;max&#39;: 130,<br>    &#39;min&#39;: 110,<br>    &#39;distribution&#39;: &#39;int_uniform&#39;,<br>  },<br>  &#39;learn_rate&#39;: {<br>    &#39;max&#39;: 0.01,<br>    &#39;min&#39;: 0.0001,<br>  },<br>  &#39;epoch&#39;: {&#39;values&#39;: [20,30,40]},<br>  &#39;batch_size&#39;: {&#39;values&#39;: [32,64]<br>}}}</pre><p>Com essas possibilidades registradas no dicionário, nós chamamos a função de sweep do wandb para procurar os melhores hiperparâmetros que podemos utilizar na rede neural que estamos construindo.</p><p>Para chamar o sweep do weight and biases utilizamos o seguinte trecho de código:</p><pre># criamos um identificador para a operação de sweep<br>sweep_id = wandb.sweep(sweep_config, <em>entity</em>=&quot;wandb_user&quot;,          <em>project</em>=&quot;nome_projeto&quot;)</pre><pre># chamamos o sweep<br><em>#o count é a quantidade de possibilidades que ele irá tentar<br>wandb.agent(sweep_id = sweep_id, function=train,count=15)</em></pre><p>O Resultado do sweep nos retorna um modelo treinado com os hiperparâmetros que geraram o melhor resultado dentre os modelos testados na operação de sweep, além disso, o wandb nos permite verificar os resultados de cada um dos modelos testados com várias métricas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*me88Cg6hyOc_VfFbkngMQQ.png" /><figcaption>wandb sweep</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yLheWoF7RYsY1aHbx1EzSw.png" /><figcaption>metricas monitoradas no sweep</figcaption></figure><p>Como diversas métricas já foram monitoradas durante o treinamento, optamos por não criar outra sessão só para teste do modelo e criação de novas métricas, assumindo que os resultados testados durante o treino já foram satisfatórios para o projeto.</p><p>Após o sweep, já conseguimos recuperar o melhor modelo dentre os treinados e testados utilizando:</p><pre># download do artefato do modelo<br>best_model = wandb.restore(&#39;model-best.h5&#39;, <em>run_path</em>=&quot;autor/nome_projeto/&lt;sweep_nome&gt;&quot;)</pre><pre># carregando o modelo recém baixado<br>modelo = keras.models.load_model(best_model.name)</pre><p>O modelo estando no wandb pode ser baixado em qualquer outro projeto contanto que o dono do projeto esteja utilizando a chave da api do wandb que permite o acesso ao projeto(para autorizar o acesso ao modelo). Essa informação é importante para os próximos tópicos abordados sobre o aplicativo. O próximo tópico irá dar uma breve explicação sobre o processamento de imagens para a predição e então começaremos a falar sobre o aplicativo desenvolvido para o nosso caso de estudo.</p><h4>Processamento Digital das imagens para predição</h4><p>O conceito principal que do processamento digital de imagens(PDI) que vamos abordar são a detecção e extração de regiões de interesse(siglas em inglês , ROI). Dada a imagem exemplo no começo nesse texto, temos interesse em detectar onde estão os dígitos e extrair os dígitos para que possamos realizar uma predição. A detecção dessas regiões de interesse podem ser feitas de várias formas, entretanto nesse projeto seguimos uma abordagem de encadear uma sequência de funções básica de pdi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KgzltmWceb66BCG2JtrGIQ.png" /><figcaption>pipeline de processamento das imagens</figcaption></figure><p>O início do processamento se faz um borramento sobre a imagem utilizando um filtro gaussiano, o resultado é uma amenização dos ruídos contidos na imagem original. Com o ruído reduzido se torna mais fácil detectar onde realmente existem objetos e onde havia apenas uma falha na imagem, assim aplicamos um algoritmo de detecção de bordas para delimitar as bordas dos objetos.</p><p>O algoritmo de bordas é o algoritmo de Canny e o resultado é um conjunto de linhas definindo um “esboço” do contorno geral dos objetos, mas as bordas encontradas não necessariamente estão conectadas no resultado da imagem. Sendo assim, dilatamos as bordas encontradas para que elas se conectem desenhando o contorno dos objetos.</p><p>Por último, são desenhados os contornos e utilizamos o opencv para criar “caixas”, delimitando as coordenadas que limitam os objetos encontrados. Com essas caixas, temos as coordenadas dos objetos, então extraímos com base nessas coordenadas dadas pelas caixas.</p><p>Após extraídos os objetos, aplicamos um threshold para tornar a imagem preto e branca como as imagens originais no dataset do mnist, e refatoramos o tamanho das imagens para 28X28 assim como o tamanho original.</p><p>Extraídas e refatoradas, as imagens estão prontas para predição, nesse ponto é só enviar para o modelo prever.</p><h4>O aplicativo</h4><p>No tópico anterior, explicamos resumidamente como fazer a detecção e extração de imagens em uma imagem maior. O aplicativo tem intuito de permitir que o usuário, interaja com os parâmetros do filtro gaussiano, os parâmetros do algoritmo de Canny, e com os parâmetros do algoritmo de dilatação.</p><p>Com essa interação, o aplicativo vai exibindo os “objetos” parciais que o opencv vai identificando dependendo da precisão das bordas, e do borramento aplicado.</p><p>Depois que o usuário tiver considerado que os parâmentos do processamento estão adequados para a extração das regiões. O aplicativo disponibiliza um modelo para que o usuário mande prever os objetos extraídos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y4m8JFJqyZyfXerbvpyBtA.png" /><figcaption>Aplicativo com todos os parâmetros mínimos e objetos mal detectados</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T0wf0EgwjfkNb_Sq_U7M1Q.png" /><figcaption>Objetos devidamente enquadrados para extração</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gZiKQJdOg-gvVOC9Mv8DLg.png" /><figcaption>extração e predição</figcaption></figure><p>Acima temos 3 telas do aplicativo executando. Um detalhe importante é que para esse projeto a imagem é fixa, por se tratar apenas de um caso de uso, idealmente a imagem poderia ser uma entrada do aplicativo vindo do usuário.</p><p>O aplicativo foi construído utilizando streamlit, mas não vamos adentrar no seu desenvolvimento geral. Somente um overview se seu funcionamento. A estrutura do código se baseia em duas funcionalidades principais, chamar o modelo que está no wandb e disponibilizar esse modelo. A chamada do modelo vai ser mais explorada por ser um código relativamente curto e agregar conceitos interessantes.</p><p>chamada do modelo:</p><pre>#a função executa somente uma vez durante a utilização do aplicativo #e salva as informações do modelo na cache<br>@st.cache(<em>suppress_st_warning</em>=True)<br>def load_model():<br># Login no wandb, carregamos a url de acesso à api de uma variável     # de ambiente chamada WAND_URL<br> os.system(f&quot;wandb login --relogin{config.WandbAcess().WANDB_URL}&quot;)</pre><pre>#Baixamos o modelo <br> best_model = wandb.restore(&quot;model-best.h5&quot;,     <em>run_path</em>=&quot;autor/nome_projeto/&lt;sweep_nome&gt;&quot;)</pre><pre><em>  return</em> best_model.name</pre><p>Utilizamos o basesettings do pydantic para carregar variáveis de ambiente:</p><pre><em>import</em> pydantic</pre><pre>class WandbAcess(pydantic.BaseSettings):</pre><pre>  WANDB_URL: str</pre><pre>  class Config:</pre><pre>    env_file = &quot;.env&quot; <br>#carregamos automaticamente WANDB_URL de um arquivo .env</pre><p>Os arquivos .env geralmente são em arquivo que guardamos variáveis de ambiente em python, essas variáveis são importantes para não deixar exposto informações importantes em código, exemplo de .env file do projeto:</p><pre>#conteudo do arquivo .env<br>WANDB_URL = sua_url_para_acesso_da_api</pre><p>A utilização do modelo é feita após uma sequência de transformações sobre a imagem que ocupam bastante linhas, então não é interessante de se explorar aqui, mas caso tenham interesse podem visitar o repositório do projeto do app no github: <a href="https://github.com/diego2017003/mnist_new_images_studycase">https://github.com/diego2017003/mnist_new_images_studycase</a></p><p>A última etapa é fazer o deploy do aplicativo, o deploy é quando disponibilizamos o aplicativo para uso por outras pessoas. No caso do projeto, vou mostrar o deploy de um projeto streamlit no google cloud.</p><h4>Deploy</h4><p>Nessa etapa, disponibilizamos o aplicativo para que outras pessoas o utilizem, no projeto optamos por disponibilizar o aplicativo via o cloud run, construindo o projeto com o cloud build.</p><p>Para entender pelo menos o básico do deploy, é necessária uma breve apresentação da ferramenta do cloud build. Para utilizarmos o aplicativo na nuvem do google cloud precisamos criar um container, o container funciona como uma pequena máquina virtual com sistema unix que encapsula o mínimo de recursos possível para que um código ou aplicativo execute. Para ver mais a respeito sugiro ler sobre o <a href="https://www.docker.com/resources/what-container/">docker</a>.</p><p>O cloud build é um criador de artefatos no google cloud (de acordo com a definição), no caso do aplicativo ele irá funcionar como um criador de um container na nuvem com o mínimo de recursos possíveis para que nosso aplicativo seja disponível aos usuários.</p><p>O cloud run, também citado anteriormente, serve de interface entre o container criado e o aplicativo. O cloud run, “roda” o container permitindo que o usuário tenha acesso ao aplicativo que criamos.</p><p>Antes de subirmos o projeto para nuvem precisamos definir um arquivo docker para especificarmos como deve ser feita a criação da nossa imagem que resultará posteriormente no container.</p><pre>#Dockerfile<br>#baixamos uma imagem do python para o container<br>FROM python:3.10.2-slim</pre><pre>#instamos bibliotecas necessárias para trabalhar com imagens no #opencv<br>RUN apt-get update<br>RUN apt-get install ffmpeg libsm6 libxext6  -y</pre><pre>#expomos uma porta para acessar o aplicativo<br>EXPOSE 8080</pre><pre>#definimos o diretório de trabalho<br>WORKDIR /app</pre><pre>#copiamos o conteúdo necessário para rodar o aplicativo para dentro #do container<br>COPY ./app/ ./app<br>COPY ./.env ./.env<br>COPY requirements.txt ./requirements.txt<br># caso o cloud build não detect o arquivo .env utilize o comando # <br># COPY . ./ #que tudo na pasta local será copiado para a imagem </pre><pre>#instalamos as dependências do aplicativo<br>RUN pip install -r requirements.txt</pre><pre># Executamos o aplicativo na porta 8080 do container<br>CMD streamlit run --server.port 8080 app/streamlit_app.py</pre><p>Para criarmos o container e disponibilizarmos o aplicativo vamos seguir uma sequência de comandos dentro da <a href="https://cloud.google.com/sdk/gcloud">cli do google cloud</a>.</p><pre># fazemos login na conta do google cloud<br>gcloud auth login</pre><pre># habilitamos o docker<br>gcloud auth configure-docker</pre><pre># escolhemos o projeto destino do aplicativo <br>gcloud config set project projeto_nome</pre><pre># executamos o cloudbuild para criar a imagem no googlecloud<br>gcloud builds submit --tag gcr.io/projeto_nome/aplicativo_nome</pre><p>Depois de criar o container a gente vai criar um serviço para disponibilizar o aplicativo, então entramos na plataforma do google cloud e vamos até o cloud run e criamos um serviço.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*FHg9rnZrnxBWNhWFzi0cfA.png" /><figcaption>criar serviço</figcaption></figure><p>Ao criar o serviço você vai criar uma nova revisão para o seu container recém criado pelo cloud build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*4yjnWPH44w_OXuVemXsiNw.png" /><figcaption>Selecionar o container</figcaption></figure><p>Além disso, há outras configurações importantes. A memória que você quer disponibilizar para o aplicativo, a quantidade de GPU’s dentre outros recursos alocados na nuvem para hospedar o aplicativo. Após escolher as configurações da máquina(permita chamadas não autenticadas caso queira enviar para algum amigo), é só clicar em criar e o aplicativo estará rodando se tudo tiver ocorrido bem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x313uR6pjV7ElZXPrGYflw.png" /><figcaption>Serviço criado</figcaption></figure><p>Depois que o serviço foi criado, a gente pode entrar dentro do serviço e criar tanto novas versões do projeto, quanto acessar o conteúdo do aplicativo por meio de uma url do serviço.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*1pa3i6g-0qC7VJonPWGwUQ.png" /><figcaption>Dentro do serviço</figcaption></figure><p>E então com a url podemos utilizar o aplicativo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Id3pKMwtCj5M8iHcZR6gHA.png" /><figcaption>app no google cloud</figcaption></figure><h4>Considerações finais</h4><p>O aplicativo executou bem no google cloud acessando inclusive a api do wandb com as variáveis de ambiente, entretanto ainda há outros passos que podem ser aplicados ao projeto para torna-lo mais robusto, como a configuração do ci no github para uma integração continua com o cloud build.</p><p>Além disso é importante a leitura sobre o google cloud e o docker para entender bem os conceitos de containers na nuvem ,que foram abordados aqui de maneira bem superficial por não se tratarem do foco do texto.</p><h4>Links importantes</h4><p><a href="https://github.com/ivanovitchm/ppgeecmachinelearning">repositório de machine learning do professor Dr. Ivanovitch silva</a></p><p><a href="https://www.docker.com/">docker</a></p><p><a href="https://cloud.google.com/run?hl=pt-br">cloud run</a></p><p><a href="https://github.com/diego2017003/mnist_new_images_studycase">github do aplicativo</a></p><p><a href="https://github.com/diego2017003/projeto-MNIST_machine_learning">github do projeto completo</a></p><p>github dos autores: <a href="https://github.com/diego2017003">Diego Medeiros</a> , <a href="https://github.com/juliaguardiani">Julia Guardiani</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f32c3f8a80d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reproductible mlops pipeline … just like a poetry]]></title>
            <link>https://medium.com/@diego25rn/reproductible-mlops-pipeline-just-like-a-poetry-72223ea2954b?source=rss-1193ba6f2431------2</link>
            <guid isPermaLink="false">https://medium.com/p/72223ea2954b</guid>
            <category><![CDATA[poetry]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[wandb]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[reproducibility]]></category>
            <dc:creator><![CDATA[Diegorn]]></dc:creator>
            <pubDate>Fri, 03 Jun 2022 18:49:41 GMT</pubDate>
            <atom:updated>2022-06-04T17:19:54.124Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reproductible mlops pipeline … just like a poetry</h3><p>Machine learning has been studied for some time, and nowadays it’s important to understand how to build a project that can grow, be scalable and stable enough to be put into production. With this in mind, We gonna build a little project with the focus on the pipeline of machine learning automate since extract the data till the model ready to production. This article is divided in the three main contents:</p><ul><li>What is mlops? and why should you study it?</li><li>How to manage a python mlops project easily with poetry-python.</li><li>Manage mlops project versioning and artifacts with Weights &amp; Biases</li></ul><ol><li><strong><em>What is mlops? and why should you study it?</em></strong></li></ol><p>Machine learning isn’t a new area of study, but it’s starting to be usable in large scale nowadays. With the bigdata context, the industry has the oportunity of abstract the data contexts and start to automate some funtionalities that can be done with Artificial Intelligence(AI).</p><p>(<em>Spoiler alert</em>)But how said the uncle Ben in Spider-man(2002). “with great power, comes great responsabilitie”(<em>Spoiler alert).</em></p><p>Create a machine learning model and put it in a solution it’s not so difficult but it’s important to understand that even having large data to build a initial solution, the problem’s behavior can change with the time. So, your model that iniciate with 90% of accuracy, can decline to 50% accuracy with one month in production and it can be expansive depending of the problem. In this case, it’s time to rebuild the model with the new data or start a new project because the actual can’t be fixed to the new context. One thing that we can keep with it: build a machine learning solution and put in production sometimes is easy but keep it working well in production is a challenge.</p><p>In this context mlops comes to facilitate the automation of a machine learning pipeline since the data extraction till the model on production, and listening the operation’s side to know when the model needs to be upgraded before it declines in working.</p><p>According to the <a href="https://cloud.google.com/architecture/mlops-continuous-delivery-and-automation-pipelines-in-machine-learning">google cloud</a>, mlops is one way to apply the continuos delivery and continuous integration to machine learning solutions. So, we use the DevOp’s principles to keep the solution working, the developers (ML-Dev) working with continuos upgrades/improvements to the solution, listening to the operations(ops) to guide the improvement and the repairs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1rL7RkZ7_jEQOlXAbufamA.png" /><figcaption>Available in:<a href="https://cloud.google.com/architecture/mlops-continuous-delivery-and-automation-pipelines-in-machine-learning">https://cloud.google.com/architecture/mlops-continuous-delivery-and-automation-pipelines-in-machine-learning</a></figcaption></figure><p>The automation comes to facilitate the continuos development. In a machine learning project we have a lot of steps applieds to the data before the model and it can be maintained between versions a lot of times. Some of this steps are: collect and download the data(Download); check’s the “must have” in the dataset and it’s fails(data checks); Exploratory data analisys(EDA) where we try to abstract and visualize the data behavior; segreagate the data to divide a dataset, a part to the model train-test and a part to validate the model; preprocessing and feature inportance to adapt the data to better representation in the context of the solution; train where the model’s is build; test to accurate the model; validation when we use the “new” data to represents the solution working with not known data. There’s others steps, but these are sufficient to a good machine learning solution deploy in a lot of cases.</p><p>in this project we used only the download, eda, preprocessing and train to exemplify the mlops pipeline.</p><p>2.<strong> How to manage a python mlops project easily with poetry-python.</strong></p><p>When we gonna build a machine learning solution and applies the mlops concepts, it’s normal to work on groups. Even with the github good practices to versioning the code, and environment mangement tools locally, it’s difficulty to represent the same enviroment of development of yours co-workers. Missing libraries, libraries dependencies,python version, and computer conditions can change and commonly they will.</p><p>Poetry-python is a tool that help us to manage the enviroment and the libraries versioning on a python project. The poetry create an enviroment and manages how does the libraries are installed in the enviroment according to it dependencies. Poetry create an .toml file to orchestrate the requirements separating the enviroments between dev and production, and a .lock file to manage the dependencies of each librarie installed. The tool is simple to use, and can be downloaded in : <a href="https://python-poetry.org/docs/">link</a></p><p>Poetry has others funtionalities but to this project we used only 4:</p><pre>#create a new project <br>!poetry init -n “name of project” </pre><pre>#add python package to the requirements<br>!poetry add “python package name”</pre><pre>#create or update an pyenv enviroment according to the requirements<br>!poetry install</pre><pre>#create a lock file to manage the depedencies of the libraries<br>!poetry lock</pre><p>Now, a gonna start to explore the article’s project to exemplify the funcionalities of the poetry in a mlops project.</p><p>2.1 Choosing the data(Download)</p><p>A machine learning project start with the choice of the data. in this case i choose the heart dataset in kaggle that is a useful dataset although it has some problems to explore. the dataset was gotten from: <a href="https://www.kaggle.com/datasets/kamilpytlak/personal-key-indicators-of-heart-disease?select=heart_2020_cleaned.csv">link</a>. But you may find it in the github’s repository of the project : <a href="https://github.com/diego2017003/Machine-learning-project-of-heart-with-MLops">github</a></p><p>Download the data,<strong> <em>check!</em></strong><em>,</em> run the poetry init -n to start a new poetry project and create a repository for the data to use it initially on your project in this way.</p><p>The main objective with this dataset is to predict if one person has a heart disease or not according to his personal informations.</p><p>2.2 EDA</p><pre><em>!poetry add matplotlib<br>!poetry add plotly<br>!poetry add pandas<br>...</em></pre><p>Add to your project your favorite exploratory libraries and start to know your data. EDA can take a time to be done and produce some value to analise how does your data is behaving, but is very very important to know how your data is working and behaving to the project future choices. With EDA we build the first layer of the information about the data.</p><p>In the project we used plotly to see the dataset behevior on a jupyter notebook so simplify our exploration. Next, we have the categorial and the numerical EDA.</p><figure><img alt="Categorical EDA" src="https://cdn-images-1.medium.com/max/1000/1*Vg5iiriF_N5MmTVeUKpKrA.png" /><figcaption>Produced by the author with python plotly</figcaption></figure><p>Analising the categorical EDA is possible to see that the number of people with no heart disease is much bigger than people with heart disease. Fortunately it’s good for the disease context but it can skew our analisys, fortunately for the analisys, in plotly, clicking in the plot’s legend we can hide the clicked categorie and analise only the data’s behavior. On Next figure we normalized the data to see better the behavior of the dataset to numerical data.</p><figure><img alt="numerical data EDA- normalized" src="https://cdn-images-1.medium.com/max/1000/1*BoZd8Tg1JRjwGrXXWyMTgA.png" /><figcaption>Produced by the author with python plotly</figcaption></figure><p>With EDA we saw how the data is behaving according to the target column with want to predict in the model. Next step we gonna preprocess the data.</p><p>2.3 Preprocessing</p><pre>!poetry add scikit-learn<br>!poetry add sklearn-pandas</pre><p>The dataset i choose already has a preprocessing so it can already be skewed. But how we want to show the mlops workflow we will apply our own preprocessing workflow to treat this data.</p><p>For preprocessing and the model we gonna use the <a href="https://scikit-learn.org/0.17/index.html">sklearn library</a>. in the project. The preprocessing has 5 main steps in our project.</p><p>Point Zero: The dataset is unbalanced. So is possible that one downsample could represents a better model train and result.</p><p>First point: Treat missing values and outliers. This preprocessing step may cause a downsample when not normal data is skewing our dataset. and to missing values, we can drop the values or inpute one significant value in the local to not skew out datset with constant not significant values.</p><p>Second point: Separate Numerical and categorical features, because it has different behaviors and on this way , we must consider the type of the columns to apply the preprocessing corretly.</p><p>Third point: Normalize numerical data. depending on the column, numerical data can have different ranges and this can difficulty the model fitting. So we can normalize the data, commonly between one range or according to z-score normalization.</p><p>Fourth point: Consider to make numeric categorical columns. This steps is for use only numbers in the dataset to representate the information, because text columns can’t be preprocessed on every machine learning model.</p><p>For each step i told previously, we can create functions and classes to represents every step and transformation that may occur with the dataset. To preprocessing we used sklearn.pipeline to create a chain between the steps, and for every transformation may occur we created a function that returns the class in the scikit-learn that do the transformation. To manage the dataset i used pandas dataframe.</p><p>To see how does it works, please check the project repository, the code it’s not so easy to bring in this article because of it’s size. Next step to mlop is the train, the choice of the model.</p><p>2.4 Train</p><p>It’s time to choose your machine learning model to the project. This step is difficult sometimes, it depends a lot of knowing how is you data behavior. Initially, one way to choose it, is try the models you know better and apply a grid search to find the best parameters for each model and then train the model to see how does it works. It’s a way of “try and fail learning” till something happens good, it’s valid but not the best way. We can create a list of models from sklearn and build functions to facilitate the choice.</p><p>For this project i choose to use a decision tree classifier. applying a simple gridSerach in the parameter, because the focus of this project it’s not build the best model for the dataset, but create a good pipeline that can be used on mlops process.</p><pre>#example of gridSearch with a decisionTreeClassifier<br>parameters = {&#39;criterion&#39;:[&#39;gini&#39;,&#39;entropy&#39;], &#39;splitter&#39;:[&#39;best&#39;, &#39;random&#39;],&#39;max_depth&#39;:range(1,8)}</pre><pre>clf = GridSearchCV(DecisionTreeClassifier(), parameters,<em>cv</em>=5,<em>scoring</em>=&#39;accuracy&#39;,<em>error_score</em>=&#39;raise&#39;)</pre><pre>y_prep = X_prep[&#39;HeartDisease&#39;]</pre><pre>X_prep = X_prep.drop(<em>columns</em>=[&#39;HeartDisease&#39;])</pre><pre>clf.fit(X_prep, y_prep)</pre><p>as result, i got that parameters after the preprocessing:</p><pre><em>criterion</em>= ‘gini’, <em>splitter</em>= ‘best’, <em>max_depth</em>= 7</pre><p>So i made an union between the model and the preprocessing pipeline and then we have the Mlops full pipeline for build a pipeline model.</p><p>I explain the full pipeline since the download till the preprocessing-train united in the same object. But where comes the poetry?<br>The poetry was used to build and run this project, so every library and dependency i needed is installed in my enviroment built by the poetry. this way, the only thing you need to do is clone the repository and type “poetry install” on the terminal that you gonna have exactly the same libraries i used on the project and can reproduce a similar result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*BkOkDo4_Al-PIAkFfroK9g.png" /><figcaption>Produce by the author with python-poetry</figcaption></figure><p>3. <strong>Manage mlops project versioning and artifacts with Weights &amp; Biases</strong></p><p>Now, we just have all the functions working locally, in separate models. But if i create a new model with worst results when compare to old models? what was the best config of my dataset? what was the best preprocessing result?</p><p>All this questions are normal when we don’t version our mlops experiments. Weights and Biases help us to version our experiments on a cloud enviroment, that can version data, models, pipelines, apply tunings as grid search and so on.</p><p>The weights and biases has a free cote and resources, so you can use a lot of resources for free on your mlops project. the WandB <a href="https://wandb.ai/">link</a></p><p>For this project i used wandb only for version the data and the mlops full pipeline. The first point is, i need to flexibilize my co-workers and my solution acess to updated data, So save it locally is not so good for the project. So first, upload the dataset to wandb and facilitate your data management.</p><p>The second step is download the data from the wandb, now that you upload the dataset you can acess it from “everywhere”. With this in mind i created the module <a href="https://github.com/diego2017003/Machine-learning-project-of-heart-with-MLops/blob/master/source/mlops/modules/download.py">Download</a> on the project, is a script python to download the data artifact.</p><pre>run = wandb.init(<em>project</em>=&quot;project_heart&quot;)</pre><pre>artifact = run.use_artifact(&quot;project_heart/heart_2020_cleaned.csv:latest&quot;)</pre><pre><em>data </em>= pd.read_csv(artifact.file())</pre><p>Now that we already downloaded the data, i organize the code on python modules to preprocessing, download and train the data. And then i call all the modules on a main function that builds the full pipeline and exports the result model to the wandb.</p><pre>model_artifact = &quot;model_export&quot;</pre><pre>joblib.dump(pipeline, model_artifact)</pre><pre>artifact = wandb.Artifact(</pre><pre>model_artifact,</pre><pre><em>type</em>=&quot;pipeline_artifact&quot;,</pre><pre><em>description</em>=&quot;A full pipeline composed of a Preprocessing Stage and a Decision Tree model&quot;,</pre><pre>)</pre><pre>run = wandb.init(<em>project</em>=&quot;project_heart&quot;, <em>save_code</em>=True)</pre><pre>artifact.add_file(model_artifact)</pre><p>When we export the pipeline artifact to the wandb, we can acess it from anywhere. and we have how to use the model on an api for example and put you model on production. As result we got a graph representation of our pipeline into the wandb.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v6zG-mugfwYQe55KBLg74A.png" /><figcaption>project pipeline on wandb produced by author with wandb</figcaption></figure><p>In addition to what was used in this article, wandb has also another functions that can be used to improve you mlops project, likes sweeps that help you to tuning your model’s parameters.</p><p>4. <strong>Conclusion</strong></p><p>With python-poetry and wandb we can create a mlops project that is easy to manage artifacts and easy to reproduct the results because of the poetry enviroment tools.<br>For next projects we can use this results to build an api to server the model, and an app to build the result visualization.</p><p>5. <strong>Good links</strong></p><p><a href="https://github.com/ivanovitchm/ppgeecmachinelearning">https://github.com/ivanovitchm/ppgeecmachinelearning</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72223ea2954b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>