<?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[Edge Analytics - Medium]]></title>
        <description><![CDATA[We’re a data science company that solves hard problems at the intersection of bits and atoms. Get in touch at info@edgeanalytics.io! - Medium]]></description>
        <link>https://medium.com/edge-analytics?source=rss----30d72a83ac98---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Edge Analytics - Medium</title>
            <link>https://medium.com/edge-analytics?source=rss----30d72a83ac98---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 11:00:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/edge-analytics" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[MLOps at Edge Analytics | Model Deployment]]></title>
            <link>https://medium.com/edge-analytics/mlops-at-edge-analytics-model-deployment-bf01489b121d?source=rss----30d72a83ac98---4</link>
            <guid isPermaLink="false">https://medium.com/p/bf01489b121d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Connor Davis]]></dc:creator>
            <pubDate>Fri, 05 May 2023 16:05:35 GMT</pubDate>
            <atom:updated>2023-05-05T16:27:24.344Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part Five of Five</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ykJlTIj1S7EImtiB9DrWBA.png" /><figcaption>Image created with DALL-E 2.</figcaption></figure><p>As machine learning models become more widely deployed, ML practitioners have shown increasing interest in MLOps. In our <a href="https://medium.com/@connor_48408/e3fcdaed7534">introductory blog</a>, we give a brief background on how we think about MLOps at Edge Analytics.</p><p>So far in this series we have stored raw data and curated methods for accessing it, processed the data in preparation for modeling, trained and tuned a variety of predictive models, and tracked those models to find the ones that perform best. The last step we cover is how to get those models into the hands of users. This post is the last part of a five part series.</p><p>You can find the other blogs in the series by following the links below:</p><ul><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-series-debdd6f423b0">Part 1: Data Storage with AWS S3 and Boto3</a></li><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-a-data-processing-pipeline-4952f3b66868">Part 2: Data Processing Pipeline</a></li><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-model-development-68e4cd9c223c">Part 3: Model Development</a></li><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-model-tracking-74d05c92b4e3">Part 4: Model Tracking</a></li><li>Part 5: Model Deployment</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pweItQOKLW_OzFbe2Mc4Ng.png" /></figure><p>Running in a Jupyter notebook is typically not the end state of a trained model. To be useful in the wild, it must be deployed somewhere for inference. Where and how the model is deployed depends on how it is used. Some general questions to consider when figuring out how to serve a model to users include:</p><ul><li>Who needs access to the model outputs?</li><li>How much does inference time matter?</li><li>How often does the model need to be run?</li><li>Where will the model be hosted?</li></ul><p>There are many ways to package and deliver a TensorFlow, PyTorch, or SKLearn model, including solutions from a variety of cloud providers. When a user needs occasional access and has an active internet connection, we often set up an API endpoint on AWS Lambda. If we need a GPU for faster inference, we may also use AWS SageMaker. When the user needs continuous input and real-time output on an edge device, we might use TensorFlow Lite to package the model and deploy it to a microcontroller. We will briefly touch on each of these three deployment methods in this blog, with more focus on deployment using AWS SageMaker.</p><h3>Model deployment in AWS Lambda</h3><p><a href="https://aws.amazon.com/lambda/">AWS Lambda</a> is an event-driven, serverless compute resource. When creating an AWS Lambda function, the developer identifies a particular event that will trigger a provisioning of resources on AWS to run a model inference function. Because you are only charged for the time it takes to run your hosted function, this serverless method keeps running costs low for models that are only occasionally accessed. Lambda also handles scaling, memory allocation, and security, making it a safe and easy-to-use model deployment resource. One drawback is that Lambda does not currently offer GPU resources, which can be a bottleneck for model inference. See <a href="https://medium.com/edge-analytics/tutorial-building-a-serverless-event-driven-handwritten-notes-summarization-app-1c213ee7cd1e">this blog</a> we wrote for an in-depth look at getting started with AWS Lambda!</p><h3>Model deployment in AWS SageMaker</h3><p>Unlike AWS Lambda, with <a href="https://aws.amazon.com/pm/sagemaker/?trk=8987dd52-6f33-407a-b89b-a7ba025c913c&amp;sc_channel=ps&amp;ef_id=Cj0KCQjwr82iBhCuARIsAO0EAZz_6dB7225W-2jZHOvnzmg9Xg0ixqypvRa9yTZFdnBEeSn45liumLsaAsy9EALw_wcB:G:s&amp;s_kwcid=AL!4422!3!532502995192!e!!g!!aws%20sagemaker!11206038603!113600690367">AWS SageMaker</a> we can provision persistent instances to run models. These instances are always running, so you can avoid the <a href="https://aws.amazon.com/blogs/compute/operating-lambda-performance-optimization-part-1/">cold start</a> you may observe with code changes or updates to an AWS Lambda function. SageMaker offers many of the perks of AWS Lambda but with the added bonus of being a model-first service and providing large, GPU-based instances as options.</p><p>Recall that for our example MLOps pipeline, we used the <a href="https://www.kaggle.com/datasets/paultimothymooney/blood-cells">Blood Cell Images</a> dataset from Kaggle to generate a model that predicts cell type from a microscope image. We can think of deploying this model to SageMaker in three steps:</p><ol><li>Formatting the model for deployment</li><li>Deploying the model</li><li>Testing the deployed model</li></ol><p>Here we take a closer look at each of these steps.</p><h4>Step 1: Formatting the model for deployment</h4><p>Formatting your model for deployment will vary depending on which deep learning framework you <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/deploy-model.html">choose</a>. Although there are several file formats for saving a TensorFlow model, SageMaker requires the <a href="https://www.tensorflow.org/guide/saved_model">SavedModel</a> format. The four components of the SavedModel for our example look like this:</p><pre>variables <br>    |--variables.data-00000-of-00001<br>    |--variables.index<br>keras_metadata.pb<br>saved_model.pb</pre><p>If the ModelCheckpoint callback was used in your TensorFlow model training script, it will automatically save models using this layout. Conveniently, if you used Weights and Biases for model tracking and included the WandbModelCheckpoint, the checkpoint models will also be saved with this format. Otherwise, if the model is saved in a different format, such as an H5 file, you will need to load and save it again:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/586dab90fe2f100d544c5be7f07150c1/href">https://medium.com/media/586dab90fe2f100d544c5be7f07150c1/href</a></iframe><p>Once you have the model files in the proper format, they need to be placed in a larger folder structure for export to the SageMaker endpoint. The overarching file structure should look like this:</p><pre>export_folder <br>    |--001 <br>        |--variables <br>            |--variables.data-00000-of-00001<br>            |--variables.index<br>        |--keras_metadata.pb<br>        |--saved_model.pb</pre><p>You can give the “export_folder” any name you want, but the naming conventions for its contents are more strict. Importantly:</p><ul><li>The model files, especially the “variables” files, are sensitive to name changes and should be named as shown above.</li><li>The folder containing the model files (in this example, the “001” folder) should be named with only the model version number. Even changing the name to “model_001” may cause the model deployment to fail.</li></ul><p>Once the model has been properly saved in the “export_folder,” the folder needs to be converted to a tar.gz file. This is done easily with the tarfile package in Python:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb596955b8007e016e9bae999f9489cb/href">https://medium.com/media/bb596955b8007e016e9bae999f9489cb/href</a></iframe><h4>Step 2: Deploying the model</h4><p>If the setup in Step 1 has been done correctly, actual deployment to SageMaker is simple and can be done in four lines of code using the Python SageMaker SDK.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6909c62f6b3a23c00a92a53f529e968c/href">https://medium.com/media/6909c62f6b3a23c00a92a53f529e968c/href</a></iframe><p>A few notes about the last two lines of code:</p><ul><li>For the TensorFlowModel instance, make sure you know what version of the TensorFlow package was used to create the model. This will be your framework_version argument.</li><li>The variable my_sagemaker_role can be found by calling get_execution_role() from the SageMaker SDK.</li><li>Once the model is deployed, it will run constantly on the number and type of instances that you specify. Make sure to select an appropriate initial_instance_count and instance_type so you don’t incur unexpected costs. Here is a list of <a href="https://aws.amazon.com/sagemaker/pricing/?p=pm&amp;c=sm&amp;z=4">SageMaker instance types and their prices</a>.</li></ul><h4>Step 3: Accessing the deployed model</h4><p>With the model deployed to a SageMaker endpoint, we can now access it to make live predictions on new data. First, make sure to preprocess the same way you did for the training data. To do this, we recommend using the same <a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-a-data-processing-pipeline-4952f3b66868">data processing pipeline</a> that was set up prior to model development.</p><p>There are three main methods for sending images to the model endpoint and retrieving results. We can use the SageMaker SDK, the Boto3 SDK, or the CLI. Each method follows the same general process:</p><ol><li>Serialize the input images.</li><li>Send the images to the model endpoint.</li><li>Receive and parse the output.</li></ol><p>With the SageMaker SDK, the first and third steps are mostly handled by functions in the package. For example, we can import a json_serializer and json_deserializer from the SDK. When included as arguments for the Predictor class, these will serialize/deserialize data to/from the model endpoint. Remember that if our input images are numpy arrays, they need to be converted to Python lists to be JSON serializable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30f9a8b5221013c0c85feb5abd160063/href">https://medium.com/media/30f9a8b5221013c0c85feb5abd160063/href</a></iframe><p>Using the Boto3 SDK requires us to serialize the input and deserialize the output. Also, recall from our <a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-series-debdd6f423b0">data storage blog</a> that the Boto3 client returns metadata along with the model response, so the output needs to be parsed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84612d7b4ca7809eef05ce782b68bafc/href">https://medium.com/media/84612d7b4ca7809eef05ce782b68bafc/href</a></iframe><p>To use the CLI, the serialized input images need to be saved to disk (e.g. as input_images.json). Similarly, the model response will be written to disk before it can be parsed (e.g. as model_response.json). Then, when running the CLI from the same directory as the saved input_images.json, we call:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0430e7b0fc3bcb03256e691cb49e3bb/href">https://medium.com/media/b0430e7b0fc3bcb03256e691cb49e3bb/href</a></iframe><p>All three of these SageMaker access methods are simple and effective. You should use the one that is most appropriate for your application!</p><h3>Model deployment to the edge</h3><p>Low powered edge devices, including wearables and smartwatches, are ubiquitous. Many wearables benefit from models making predictions on the hardware itself. Deploying models to an edge device, like a microcontroller, is a very different process from cloud deployment. You’ll likely be working in a low level programming language like C, C++, or Rust, and there may be specific constraints related to the ARM architecture or firmware compiler. Memory and power constraints also range from moderate to severe; thinking about RAM in terms of kilobytes or even bytes is commonplace. Managing data inputs and outputs also requires careful attention.</p><p>In general, deploying models to microcontrollers is a bespoke process that depends heavily on the hardware and firmware setup. Someone experienced in working with low level languages for embedded devices is necessary. We’ve had success writing our own C implementations of algorithms but have also found that <a href="https://www.tensorflow.org/lite/microcontrollers">TensorFlow Lite for Microcontrollers</a> can reduce development cycle times once the libraries are integrated into the code base.</p><h3>What now?</h3><p>The raw data has been stored, and data I/O methods have been developed. The data has been processed and used to train and tune a large number of models. Those models have been logged and tracked to find the most effective one. Now, that selected model has been deployed and is ready to be integrated into your application.</p><p>However, the work of MLOps doesn’t stop here. The deployed model still needs to be rolled out to your users. It must be monitored to ensure there are no performance issues or unexpected outputs. And as new data comes in, it should be stored, processed, and used to tune your models. The need to maintain and improve ML models is constant, but as this work continues, we hope you return to the five pillars of MLOps we’ve explored in this series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nS5-8JNgfXqiTkCSlKGUoA.png" /></figure><h3>Machine learning at Edge Analytics</h3><p><a href="https://edgeanalytics.io/">Edge Analytics</a> helps companies build MLOps solutions for their specific use cases. More broadly, we specialize in data science, machine learning, and algorithm development both on the edge and in the cloud. We provide end-to-end support throughout a product’s lifecycle, from quick exploratory prototypes to production-level AI/ML algorithms. We partner with our clients, who range from Fortune 500 companies to innovative startups, to turn their ideas into reality. Have a hard problem in mind? Get in touch at <a href="/service/mailto:info@edgeanalytics.io">info@edgeanalytics.io</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf01489b121d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-model-deployment-bf01489b121d">MLOps at Edge Analytics | Model Deployment</a> was originally published in <a href="https://medium.com/edge-analytics">Edge Analytics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MLOps at Edge Analytics | Model Tracking]]></title>
            <link>https://medium.com/edge-analytics/mlops-at-edge-analytics-model-tracking-74d05c92b4e3?source=rss----30d72a83ac98---4</link>
            <guid isPermaLink="false">https://medium.com/p/74d05c92b4e3</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Connor Davis]]></dc:creator>
            <pubDate>Wed, 03 May 2023 15:00:06 GMT</pubDate>
            <atom:updated>2023-05-05T16:31:46.256Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part Four of Five</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KxBepr4ihhrnuAyTSwqgUg.png" /><figcaption>Image created with DALL-E 2.</figcaption></figure><p>As machine learning models become more widely deployed, ML practitioners have shown increasing interest in MLOps. In our <a href="https://medium.com/@connor_48408/e3fcdaed7534">introductory blog</a>, we give a brief background on how we think about MLOps at Edge Analytics.</p><p>Here we look at the fourth pillar of our MLOps pipeline: model tracking. Tracking generally means logging relevant information to a database or other storage for future use. As we train and test ML models, integrating model tracking software allows us to easily compare and contrast our model runs to make high value insights quickly and with confidence. This post is part four of a five part series.</p><p>You can find the other blogs in the series by following the links below:</p><ul><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-series-debdd6f423b0">Part 1: Data Storage with AWS S3 and Boto3</a></li><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-a-data-processing-pipeline-4952f3b66868">Part 2: Data Processing Pipeline</a></li><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-model-development-68e4cd9c223c">Part 3: Model Development</a></li><li>Part 4: Model Tracking</li><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-model-deployment-bf01489b121d">Part 5: Model Deployment</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A74bySAucZnZWysCgJzn0w.png" /></figure><p>ML modeling experiments are most useful if we keep a record of what we tried and how it turned out. Tracking model configurations and results per experiment trial helps us:</p><ol><li>Efficiently identify parameters of the best performing models</li><li>Reproduce these models at a later date</li></ol><p>The second point is particularly important for us to be confident that any models we develop will behave as expected when deployed “in the wild.”</p><p>Two questions help guide our model tracking:</p><ol><li>What components do we want to track?</li><li>What data formats and services should we use to track them?</li></ol><p>There are many considerations to take into account when answering these questions. For example, certain components (e.g. metrics) help identify best performing models. Other components (e.g. hyperparameters) are necessary for reproducibility. We should understand the storage requirements for components we plan to track, and we should have a sense of what dashboarding tools would make our lives easier. We will examine these questions and others more closely in the context of our example MLOps pipeline.</p><h3>Components we track</h3><p>There are three types of components that we might care to track. They are parameters, metrics, and artifacts. Parameters are any inputs that impact how a modeling experiment is set up and executed. Metrics are the results by which we gauge performance of the modeling run. An artifact is a catch-all term for any file we want to log with the experiment, which may include model weights, figures, or text summaries.</p><p>The set of components tracked for an experiment should fully specify every aspect of the experiment you may want to assess in the future; you want to ensure there are no information gaps in the data you log. Still, some attention should be taken to avoid exploding data storage costs. For example, tracking a dataset ID tag as a parameter may be a better solution than logging an entire training dataset as an artifact.</p><p>The types of tracked components differ across different areas of an MLOps pipeline. The table below provides a brief discussion of how we might consider what to track at each major stage. Note we discuss potential tracked data in terms of images, as our example dataset is the <a href="https://www.kaggle.com/datasets/paultimothymooney/blood-cells">Blood Images Dataset</a> from Kaggle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*274YvVvG_rDKqlhP-2cCwg.png" /><figcaption>Discussion of elements to track in an MLOps pipeline.</figcaption></figure><h3>Organization</h3><p>When we run thousands of trials, organizing everything can get messy. Third-party MLOps software platforms that help with this problem have matured in recent years. Integration with custom project code only requires a few lines of code, and dashboards help sort through modeling trials easily. The best part is that all of the complexity of logging and database management is taken care of under the hood. <a href="https://wandb.ai/site">Weights and Biases</a> (W&amp;B), <a href="https://mlflow.org/">MLflow</a>, and <a href="https://neptune.ai/?utm_source=googleads&amp;utm_medium=googleads&amp;utm_campaign=[SG][HI][brand][rsa][all]&amp;utm_term=neptune%20ai&amp;gclid=CjwKCAjw3POhBhBQEiwAqTCuBjmZxBPoWiCEg6NH-TNQIZb-cHpBVUePHECrmrUITmnI2nU99uWr5RoCL_UQAvD_BwE">neptune.ai</a> are three well known services that share many model tracking features. While <a href="https://neptune.ai/vs/wandb-mlflow?utm_source=googleads&amp;utm_medium=googleads&amp;utm_campaign=[SG][HI][competitors-vs][rsa][all]&amp;utm_term=wandb%20vs%20mlflow&amp;gclid=CjwKCAjw3POhBhBQEiwAqTCuBisw8WKLpmwwMti3GrUNghzg7xHgvCr0eQ-Efp97g3n1EDuEQPCCVRoC1_UQAvD_BwE">all three platforms are excellent</a>, we explore W&amp;B functionality for this example pipeline because setup is easy, the documentation is extensive, and they have a broad suite of visualization features.</p><p>Here we give a short introduction to how we implemented W&amp;B into our example pipeline.</p><h4>Weights and Biases set up</h4><p>Getting started with W&amp;B is simple. Once you sign up for an account on their website (it’s free for individuals!), you will be guided through the steps to download the <a href="https://docs.wandb.ai/quickstart">W&amp;B Python SDK</a>.</p><p>A basic W&amp;B implementation in Python looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ff7dbdd5107d67cd72251354cf67816/href">https://medium.com/media/3ff7dbdd5107d67cd72251354cf67816/href</a></iframe><p>Regarding the wandb.init() call above:</p><ul><li>The project argument is the name for the overarching project. Multiple modeling runs with different configurations can be saved to a single project.</li><li>The config argument is a dictionary of model configuration values. The keys and values in this dictionary will be used to group and compare the various model runs within the project.</li><li>The name argument is the name of a single model run. If left empty, a random name is generated.</li></ul><p>Additionally, any objects and files you log within the wandb_run will be saved to the given run name, under the given project, and will be viewable on the W&amp;B dashboard.</p><h4>Logging</h4><p>Within a W&amp;B modeling run, you can log any arbitrary object or file as an artifact. Keep in mind, however, that when doing so, the default behavior will copy the object to W&amp;B cloud storage (GCS in the United States) This convenience works well for some use cases, but here we prefer to handle cloud storage on our own to avoid tight coupling with third party tools. Instead, we log <a href="https://docs.wandb.ai/guides/artifacts/track-external-files">reference artifacts</a> to URIs in our own S3 buckets. In doing so, only the URI reference is saved as an artifact to W&amp;B. This gives us better control over our stored data and increases security for tracking sensitive files.</p><h4>Viewing the dashboard</h4><p>W&amp;B provides a nice dashboard for keeping track of logged artifacts and viewing modeling results. To navigate to the dashboard, go to wandb.ai/home and select your project. The first tab will show some training results for each modeling run within the project. For the dashboard below, we used the WandbMetricsLogger TensorFlow callback to track the recall, precision, and accuracy at each epoch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dTwhprHLrsSSZRvei856iw.png" /><figcaption>Training and validation metrics are tracked for each run in a W&amp;B project.</figcaption></figure><p>A second tab on the dashboard organizes these results into a table. This format allows you to easily sort and filter modeling runs based on hyperparameters, metrics, or other logged items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hL7n8Uw9ViTrFp7zFsZfUw.png" /><figcaption>W&amp;B organizes metrics and characteristics of modeling runs in a table format.</figcaption></figure><p>These are just two of many nice features in the W&amp;B dashboard. It also provides great visualizations for organizing hyperparameter searches, allows you to keep track of artifact data and metadata, generates reports with your results, and more. We recommend you spend some time getting familiar with all the dashboard has to offer!</p><h4>Hyperparameter search</h4><p>One powerful feature of W&amp;B is its ability to track and visualize hyperparameter searches. You can use the W&amp;B online dashboard to set up a hyperparameter search, or you can integrate W&amp;B into your own search code with their SDK. To keep our example pipeline flexible, we integrate W&amp;B logging into our existing hyperparameter search code.</p><p>During model development, we used the KerasTuner Python package to perform hyperparameter searches. The high level set up of a KerasTuner search looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30edd3c3cf37d3b9771f61d41cad12ec/href">https://medium.com/media/30edd3c3cf37d3b9771f61d41cad12ec/href</a></iframe><p>When calling tuner.search(), a new model is built and trained for each trial in the num_search_trials via a run_trial() method. We can write a custom tuner class that inherits from RandomSearch and overrides run_trial(). The custom method contains the logic to set up a W&amp;B run.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46be96b2efb6fe966b49317ccfb30b23/href">https://medium.com/media/46be96b2efb6fe966b49317ccfb30b23/href</a></iframe><p>Now when we instantiate a WandBTuner and call its search() method, our custom run_trial() method will be used for the hyperparameter search. Then, W&amp;B can access performance metrics and hyperparameters to create beautiful parallel coordinates charts like the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSCa3VjT4KbpoNFJeb10bA.png" /><figcaption>W&amp;B generates graphics like this parallel coordinates chart to visualize hyperparameter search results.</figcaption></figure><p>This image shows one of the many ways W&amp;B gives you to track and visualize your model development. These features help you sort through many modeling trials and makes W&amp;B a great tool for gaining deep insights on your ML model.</p><p>Once we have found the best model and made sure we can recreate its results, it’s time to deploy that model for use in the real world. We’ll discuss this process in the final blog in our series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gioxu2quxPjg1oIqEt_j0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nS5-8JNgfXqiTkCSlKGUoA.png" /></figure><h3>Machine learning at Edge Analytics</h3><p><a href="https://edgeanalytics.io/">Edge Analytics</a> helps companies build MLOps solutions for their specific use cases. More broadly, we specialize in data science, machine learning, and algorithm development both on the edge and in the cloud. We provide end-to-end support throughout a product’s lifecycle, from quick exploratory prototypes to production-level AI/ML algorithms. We partner with our clients, who range from Fortune 500 companies to innovative startups, to turn their ideas into reality. Have a hard problem in mind? Get in touch at <a href="/service/mailto:info@edgeanalytics.io">info@edgeanalytics.io</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74d05c92b4e3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-model-tracking-74d05c92b4e3">MLOps at Edge Analytics | Model Tracking</a> was originally published in <a href="https://medium.com/edge-analytics">Edge Analytics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial: Building a serverless event-driven handwritten notes summarization app]]></title>
            <link>https://medium.com/edge-analytics/tutorial-building-a-serverless-event-driven-handwritten-notes-summarization-app-1c213ee7cd1e?source=rss----30d72a83ac98---4</link>
            <guid isPermaLink="false">https://medium.com/p/1c213ee7cd1e</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Brinnae Bent, PhD]]></dc:creator>
            <pubDate>Tue, 02 May 2023 20:01:00 GMT</pubDate>
            <atom:updated>2023-05-02T20:01:00.106Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building an App in Python with AWS Lambda, S3, Textract, and GPT-4</h4><p>At <a href="https://edgeanalytics.io/">Edge</a>, we love taking notes the old-fashioned way — by hand, and with pen and paper. The classic drawbacks to this approach are that handwritten (non-digital) notes are difficult to share and index for later use. Thumbing back through your notebook to digitize handwritten notes to a computer for sharing and indexing is a painful process. Advances in AI can help with this.</p><p>In a <a href="https://medium.com/edge-analytics/from-scribbles-to-summaries-enhancing-ocr-models-with-gpt-edit-for-handwritten-notes-e1940bbad8f9">recent blog</a>, we shared our solution for automatically converting handwritten notes to a usable, reformatted text summary using OCR and GPT. Today we will be expanding on this idea by building a serverless, event-driven app for handwritten notes summarization using AWS Lambda, S3, Textract, and GPT-4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NPfmMBHFpldObd7k" /></figure><h3>The tools</h3><p>Unless you have been in hibernation this winter, you have likely heard of <a href="https://arxiv.org/abs/2303.08774">OpenAI’s GPT-4</a>, a multimodal large language model that has taken the internet by storm. We will be using GPT-4 to format and summarize our notes in this application.</p><p>We will also use a suite of AWS tools. This includes <a href="https://aws.amazon.com/s3/">AWS S3</a> for cloud storage and <a href="https://aws.amazon.com/textract/">AWS Textract</a> for optical character recognition (OCR). While we could also use an open source OCR model (like <a href="https://github.com/tesseract-ocr/tesseract">Tesseract</a> or <a href="https://huggingface.co/microsoft/trocr-base-handwritten">TrOCR</a>), we opted for the <a href="https://nanonets.com/blog/aws-textract-teardown-pros-cons-review/">reliability and flexibility</a> of the input format of AWS Textract.</p><p>The last tool we will be using is <a href="https://aws.amazon.com/lambda/">AWS Lambda</a>, a serverless, event-driven compute service. Lambda is low cost and flexible, making it perfect for this event-driven application. Event-driven functions are compute events that occur automatically in response to triggers. Also known as Function-as-a-Service, Lambda allows the developer to write backends without having to reserve and maintain servers. Lambda handles scaling, memory allocation, and security.</p><p>We have opted to use AWS web tools for ease of use, but please note that you can do all of the following with the <a href="https://aws.amazon.com/cli/">AWS CLI</a> instead.</p><p>Now that we have defined the tools we will be using for this application, let’s get started!</p><h3>Step 1 — Set up S3 buckets</h3><p>The first step in building our application is setting up our S3 buckets. We will create two buckets: one for the input image — “scribble” — and one for the Markdown output — “summary”. While we could use the same S3 bucket for both the input and the output of our function, it is <a href="https://docs.aws.amazon.com/lambda/latest/dg/with-s3.html">not recommended by AWS</a> because it can cause recursive invocations, which could increase Lambda usage (and the associated costs). <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/creating-bucket.html">Here</a> is a user guide for creating an S3 bucket. Name your bucket and configure it with all the default settings. Note the region you create the S3 bucket in — you will want to create your Lambda in the same region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4vmopbS7b-omJt6z" /></figure><p>Once you have created your buckets, note the Amazon Resource Name (ARN) for each bucket. You will need these to set the IAM permissions for your Lambda. You can find the ARN by navigating to your bucket &gt; Properties &gt; Bucket overview.</p><h3>Step 2 — Set up Lambda to trigger on S3</h3><p>Next, you will create your Lambda function. You should choose “Author from scratch” and choose your Runtime (we’re usingPython 3.9 in this example). Click “Create function”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VzYfUQbd1gO1aFWE" /></figure><p>To set the Lambda up to trigger on your S3 input bucket, click “Add trigger” in the Function overview tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ePGuYhUy2k6iKHsf" /></figure><p>To configure the trigger, choose “S3” as the source and choose the bucket you want to serve as the event source. For event types, select “All object create events”. Optionally, you can add a prefix or suffix that will allow you to limit notifications to objects with keys that start/end with the specified characters (if you only wanted to run the function on .png files, for example). For this example, you can leave these blank. Click “Add”.</p><p>You are now going to add IAM permission policies for your Lambda function. This will give your Lambda access to the S3 buckets you configured above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5VTkebvzoOu3Bw5d" /></figure><p>Navigate to the Configuration tab &gt; Permissions tab. Click on the link under Execution role &gt; Role name. This will take you to the IAM role associated with the Lambda function.</p><p>In the IAM role, select “Add permissions” &gt; Create inline policy. In the JSON tab of the editor, add the following policy (make sure to add your bucket name where you are adding the input file). Click “Review Policy” and add a name to your policy. Alternatively, you can use the Visual editor and add the ARN you copied for your bucket above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7955c0502cf99d9c69093fa70c1fe755/href">https://medium.com/media/7955c0502cf99d9c69093fa70c1fe755/href</a></iframe><p>You will repeat the above step for your bucket where you will send the output of your Lambda function, this time with the action being “s3:PutObject”. See the JSON below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/215ff4bb493aa54b37cef67657cc0270/href">https://medium.com/media/215ff4bb493aa54b37cef67657cc0270/href</a></iframe><p>Now you should be connected to your S3 buckets. If you upload a file to your input S3 bucket, it should trigger the Lambda function. You can easily test this with your lambda_handler function (this is the function that is triggered by the S3 upload and handles the event by default. You can change which function in your code handles the event in Code &gt; Runtime settings &gt; Handler),</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c21e6d67ff9de3b65bc91e2b387ced9/href">https://medium.com/media/0c21e6d67ff9de3b65bc91e2b387ced9/href</a></iframe><p>In your function’s CloudWatch logs (more about this in a later section), you should see an event when you upload a file to your S3 bucket. Now we are ready to build our app!</p><h3>Step 3 — Integrate AWS Textract</h3><p>Integrating Lambda and <a href="https://aws.amazon.com/textract/">AWS Textract</a> is incredibly straightforward. While we are using AWS Textract, you could easily replace this with a different OCR solution.</p><p>In order to utilize AWS Textract, we need to return to our IAM role (following the instructions above) and create a new inline policy. The JSON for the policy is listed below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c3ab8e9ae751546c5aa0343f43de699/href">https://medium.com/media/9c3ab8e9ae751546c5aa0343f43de699/href</a></iframe><p>From the event defined in our <em>lambda_handler()</em> function, we will get the current event record’s bucket name and filename, which we will use in our call to the Textract API using AWS’s SKD for Python, <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/index.html"><em>boto3</em></a>. Since we only need to detect text in the document, we will use the <em>detect_document_text()</em> function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea8f970496c2b1898678ce969791525b/href">https://medium.com/media/ea8f970496c2b1898678ce969791525b/href</a></iframe><p>The response from the above call to the Textract API requires some reformatting to the preferred input to GPT-4. The following function will format the response from Textract into a single string for input to GPT-4:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/219e0f131abf9aa9946238f3363bf0e7/href">https://medium.com/media/219e0f131abf9aa9946238f3363bf0e7/href</a></iframe><h3>Step 4 — Integrate OpenAI GPT</h3><p>To use the OpenAI API, we will need to install the Python openai library. One nuance of AWS Lambda is the Python environment is natively configured with select packages only (like <em>boto3</em>). While you can zip up packages with your code and upload directly to AWS, Amazon’s recommendation is to add a Layer. Layers are additional code and content (e.g. libraries, a custom runtime, other dependencies) that can be uploaded directly to your Lambda function. Layers can be used across lambda functions and are version controlled.</p><p>The following steps will walk you through the process of creating your own Layer. In the same environment you used to develop your code, follow these steps in your command line:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42d32cf935d7d75e8f52aa25b3b4736d/href">https://medium.com/media/42d32cf935d7d75e8f52aa25b3b4736d/href</a></iframe><p>It is very important to name your secondary repository ‘python’. Otherwise, AWS will not know where to find your library.</p><p>Now that you have a zipped file (named package_layer.zip), you can upload it as a Layer to AWS. In AWS Lambda, under “Additional Resources” you will find the Layers tab, where you can view all of your layers. You will create a new layer by clicking the “Create layer” button.</p><p>You will upload your .zip file. Give your layer a name and optionally add a runtime.</p><p>If you go back to your lambda function, you can now select the “Layers” tab under “Code”. Choose “Custom layers” and choose the layer you just created from the dropdown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FSSuo5xK61g4ufmd" /></figure><p>Another item to configure is an environmental variable for your OpenAI API key. You can do this by selecting Configuration &gt; Environmental variables &gt; Edit &gt; Add environment variable.</p><p>You can call this variable in your code like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50261ceb723befe032cb892d7b57590f/href">https://medium.com/media/50261ceb723befe032cb892d7b57590f/href</a></iframe><p>Now you are ready to make calls to the OpenAI API, following their <a href="https://platform.openai.com/docs/introduction">documentation</a>.</p><p>For our GPT-4 application, we used the ChatCompletion.create() function. GPT-4 inputs include the output-string from Textract and a prompt telling GPT-4 that it is a note formatter and summarizer with specific instructions on formatting.</p><h3>Step 5 — Writing to S3</h3><p>Again, <em>boto3</em> makes it easy to write our resulting Markdown text (.md file extension is needed) to our output S3 bucket as shown.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9a6003be8f184a5bc101eecb75479c8/href">https://medium.com/media/d9a6003be8f184a5bc101eecb75479c8/href</a></iframe><h3>Step 6 — General configurations</h3><p>Depending on the application you build, you may have to increase the timeout and/or memory of your Lambda function. You can do this by navigating to Configuration &gt; General configuration &gt; Edit.</p><p>For this application, I needed to increase the timeout because the default 3 second timeout period was not long enough for the API calls to Textract and OpenAI.</p><blockquote>Helpful Hint: If you are confident that your code runs but are still getting errors when testing, try increasing the timeout or memory of your Lambda function.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ZI0qh1LlnpZTv2sfOITVA.png" /></figure><h3>Step 7— Testing</h3><p>There are two options for testing. You can configure a test event in AWS Lambda, or you can upload a file to your input S3 bucket. For debugging, you should become familiar with CloudWatch logs, which will log all requests handled by your function. You can access your logs by selecting the “Monitor” tab and clicking “View CloudWatch logs”. Here is a <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html">guide to using CloudWatch logs</a>.</p><h3>Conclusions</h3><p>In this tutorial, we integrated AWS Lambda, S3, Textract, and GPT-4 to create a useful and fun application for formatting and summarizing your handwritten notes. From here, you can connect the app to inputs/outputs other than S3 — a front-end web interface, a GitHub CI/CD tool, or even a Slack bot (blog on creating a Slack bot coming soon…).</p><p>If you build something using this tutorial, let us know! We want to hear from you — what are you using these tools for?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xCA8aC4p2uSjQos-" /></figure><h3>Building tools with GPT at Edge Analytics</h3><p><a href="https://edgeanalytics.io/">Edge Analytics</a> has helped multiple companies build solutions that leverage GPT models. More broadly, we specialize in data science, machine learning, and algorithm development both on the edge and in the cloud. We provide end-to-end support throughout a product’s lifecycle, from quick exploratory prototypes to production-level AI/ML algorithms. We partner with our clients, who range from Fortune 500 companies to innovative startups, to turn their ideas into reality. Have a hard problem in mind? Get in touch at info@edgeanalytics.io.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*4XZ06hk92AXFY_R-Vb3YPQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c213ee7cd1e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edge-analytics/tutorial-building-a-serverless-event-driven-handwritten-notes-summarization-app-1c213ee7cd1e">Tutorial: Building a serverless event-driven handwritten notes summarization app</a> was originally published in <a href="https://medium.com/edge-analytics">Edge Analytics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MLOps at Edge Analytics | Model Development]]></title>
            <link>https://medium.com/edge-analytics/mlops-at-edge-analytics-model-development-68e4cd9c223c?source=rss----30d72a83ac98---4</link>
            <guid isPermaLink="false">https://medium.com/p/68e4cd9c223c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Connor Davis]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 15:37:53 GMT</pubDate>
            <atom:updated>2023-05-05T16:28:19.617Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part Three of Five</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rghhhSihm1QB8Jrv-1pSXw.png" /><figcaption>Image created with DALL-E 2.</figcaption></figure><p>As machine learning models become more widely deployed, ML practitioners have shown increasing interest in MLOps. In our <a href="https://medium.com/@connor_48408/e3fcdaed7534">introductory blog</a>, we give a brief background on how we think about MLOps at Edge Analytics.</p><p>In previous posts, we examined tools for <a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-series-debdd6f423b0">data storage and I/O</a> and <a href="https://medium.com/@connor_48408/4952f3b66868">data processing</a>; here, we look at model development. During this step, machine learning models are trained and evaluated on the processed data. This is part three of our five part series on building an MLOps pipeline.</p><p>You can find the other blogs in the series by following the links below:</p><ul><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-series-debdd6f423b0">Part 1: Data Storage with AWS S3 and Boto3</a></li><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-a-data-processing-pipeline-4952f3b66868">Part 2: Data Processing Pipeline</a></li><li>Part 3: Model Development</li><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-model-tracking-74d05c92b4e3">Part 4: Model Tracking</a></li><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-model-deployment-bf01489b121d">Part 5: Model Deployment</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mb5wIP0huiMR-YV9pZACwQ.png" /></figure><p>We first need to decide on a framework for training and evaluating models. This framework will need to answer the following questions:</p><ul><li>What library do we want to use for modeling (TensorFlow, PyTorch, JAX, etc.)?</li><li>What modeling architecture is appropriate for our data format and size?</li><li>How do we define a successful model?</li><li>What are appropriate evaluation metrics?</li></ul><p>Recall that we are using the <a href="https://www.kaggle.com/datasets/paultimothymooney/blood-cells">Blood Images Dataset</a> from Kaggle as our example problem where we predict cell type from a microscope image. We use convolutional neural networks (CNNs) for this task since they are the standard architecture for image classification. To build the model, we can choose from a number of deep learning platforms like PyTorch, JAX, or TensorFlow. In this example, we use Tensorflow.</p><h3>Model configuration</h3><p>CNNs, even simple ones, are composed of many configurable hyperparameters. We can build limitless flavors of CNNs by varying the number of convolutional layers, max pooling layers, dropout layers, etc. Furthermore, each of those layers has its own hyperparameters, including convolutional kernel size and stride, pooling kernel size and stride, dropout rate, and more.</p><p>We believe that a good pipeline for model training should have a fair amount of structure while giving an ML engineer access to the knobs necessary to succeed on a project. For that reason, we typically wrap the code to create and compile the model into a main script that accepts an easily edited configuration file. We generally use a YAML file for configuration because its structure is human-readable, and its contents translate into intuitive Python base types. The configuration for our simple CNN is written in the YAML file like this:</p><pre>cnn_config:<br>    # The first three lines specify the input data shape.<br>    input_x_pixels: 480 <br>    input_y_pixels: 480<br>    input_channels: 1<br>    # The convolutional layers.<br>    num_convolutional_layers: 3<br>    num_convolutional_filters: 5<br>    convolutional_kernel_size: 3<br>    convolutional_kernel_stride: 1<br>    convolutional_activation_fxn: &quot;relu&quot;<br>    # The max pooling layers.<br>    num_max_pool_layers: 1<br>    max_pool_size: 2<br>    max_pool_stride: 2<br>    # The output activation and number of labels.<br>    output_activation_fxn: &quot;softmax&quot;<br>    output_len: 6</pre><p>We can also use this YAML configuration file to specify other model-related information such as batch size, number of epochs, loss functions, and evaluation metrics. We can produce an entirely new model by simply editing the config file and passing it from the command line, like this:</p><pre>python train.py --config model_config.yaml</pre><p>Having all this information accessible in a single file makes editing the model structure convenient and reproducible since we log the config file with the other outputs of the training run.</p><h3>The training process</h3><p>Model training has been simplified significantly in recent years by packages like TensorFlow, PyTorch, and JAX. High level interfaces in these packages abstract away many of the pain points of deep learning, so that we can more rapidly iterate on new ideas rather than reinventing the wheel each time. We start with our model configuration file and the processed data (split into training and testing sets):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HI__eKD9bcQn3QOT1vD8vw.png" /><figcaption>Overview of the model training and evaluation process.</figcaption></figure><p>When we run cross validation, we repeat the training process by splitting the data into train and validation sets and complete the process of model building, training, and evaluating. Note that most projects will typically have an additional holdout test dataset that is only used for evaluating the final model prior to deployment.</p><p>For each training run, we log relevant information to help us reason about the model in post-hoc analysis. In this basic example, these outputs include the training log, model file, and model evaluation results. Altogether, they help us keep track of the models we have built and how well they perform. We’ll dive deeper into model logging and tracking in the next blog.</p><h3>Optimizing model hyperparameters</h3><p>All models have hyperparameters that affect model performance. In the case of our simple CNN, we can modify the model layers until we are happy with how it performs on the validation dataset (note: not the final holdout test set!). Manual tuning of hyperparameters is often not feasible, so we turn to solutions for scaled hyperparameter searching. These solutions will train and evaluate many architectures to find those with the best performance.</p><p>The KerasTuner package is built on Keras functionality and provides simple and efficient methods for hyperparameter searching. With it, we can specify ranges of hyperparameter values over which to search. This includes discrete values and continuous distributions for any given hyperparameter. We often configure our pipelines to run searches using the same configuration file as a typical model training, where the hyperparameters of interest contain a list rather than a single value. Downstream, the code contains the logic to treat these lists as axes of a search space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lGAM6nHX8fUciD6Qbu_AFA.png" /><figcaption>Configuration settings for a single model build versus hyperparameter search.</figcaption></figure><p>KerasTuner allows the user to specify how many trials to run, which metrics to use for model evaluation, and which search method to use for selecting hyperparameters (e.g. random search, bayesian optimization, hyperband, etc.). And conveniently, if the tuner chooses an impossible model configuration, it will skip that trial without interrupting the entire search. The KerasTuner package also includes a class for <a href="https://keras.io/api/keras_tuner/tuners/sklearn/">hyperparameter searches on Scikit-learn models</a>!</p><p>As with running the simple train.py script above, all values needed for the hyperparameter sweep are saved in a single tune_config.yaml file. So if we need to change our sweep values, we can do so in the config file and run:</p><pre>python tune.py --config tune_config.yaml</pre><h3>Remote training with Ray</h3><p>Local development is excellent for writing code and unit testing models, but it is typically resource-limited for training and tuning purposes. Ray is a library that offers the ability to scale your Python applications with ease, spinning up remote instances on AWS, GCP, Azure, and more to handle workloads of any size. Ray strikes an impressive balance between being easy to use and configurable. At Edge Analytics, we’re big fans of Ray, and we’re in <a href="https://www.anyscale.com/blog/four-reasons-why-leading-companies-are-betting-on-ray">good company</a>.</p><p>Getting started with Ray is easy. We recommend this <a href="https://docs.ray.io/en/latest/cluster/vms/user-guides/launching-clusters/aws.html">tutorial</a> to launch your own Ray cluster on AWS. Using the tutorial will give the Ray workers access to your S3 buckets auto-magically. Once the cluster is properly configured, you can send your local Python training script to be run on a remote instance.</p><p>Ray offers interfaces for Python and command line. With our goal of maintaining as much independence from any individual platform as possible, we use the CLI here. Since <a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-series-debdd6f423b0">our data I/O for this example is cloud-based</a>, a simple command can kick off a training job on the Ray cluster without any modifications to the local training code:</p><pre>ray job submit --working-dir . \<br>               --runtime-env runtime.yaml \<br>               --entrypoint-num-gpus 1 \<br>               -- python train.py --config model_config.yaml</pre><p>Here are a few helpful tips when working with Ray:</p><ol><li>Spin up a cluster with a small head (m5.large) to keep running costs low. This instance will run constantly and wait for new requests. You can also stop the instance when not in use.</li><li>Virtual CPU allowance with AWS needs to be high enough to accommodate the number of workers you need, and you will likely need to <a href="https://repost.aws/knowledge-center/ec2-on-demand-instance-vcpu-increase">request</a> more.</li><li>S3 permissions for your Ray workers on AWS can sometimes create issues. This <a href="https://github.com/ray-project/ray/issues/9327">thread</a> is extremely helpful for troubleshooting.</li><li>Setting up a <a href="https://docs.ray.io/en/latest/ray-core/handling-dependencies.html#specifying-a-runtime-environment-per-job">runtime environment YAML file</a> can help clean up your job submission command while adding environment variables and specifications for pip/conda environments.</li></ol><p>Many other great resources for training models on remote instances exist, such as <a href="https://cloud.google.com/vertex-ai">Vertex AI</a> at Google and <a href="https://aws.amazon.com/pm/sagemaker/?trk=8987dd52-6f33-407a-b89b-a7ba025c913c&amp;sc_channel=ps&amp;ef_id=CjwKCAjw__ihBhADEiwAXEazJqm6wlRbYNfDrLyihbtjUV1IoHZkMjO7caXIExSM14S_YJliWr30oRoCL0EQAvD_BwE:G:s&amp;s_kwcid=AL!4422!3!532502995192!e!!g!!aws%20sagemaker!11206038603!113600690367">SageMaker</a> at AWS. We have experience running model training scripts on AWS SageMaker Script Mode instances and have found it to be an involved and restrictive process. Comparatively, Ray is easy to set up and flexible, making it a great resource for our example pipeline.</p><h3>Up next</h3><p>In order to get our model just right, we might have to train countless variations of it. When we have hundreds or thousands of model results to sort through, how do we find the best ones? And once we’ve identified those models of interest, how can we ensure reproducibility? These questions are addressed by our next step in the pipeline: model tracking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z3kMM9_a1vmnfWxKXCmS6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nS5-8JNgfXqiTkCSlKGUoA.png" /></figure><h3>Machine learning at Edge Analytics</h3><p><a href="https://edgeanalytics.io/">Edge Analytics</a> helps companies build MLOps solutions for their specific use cases. More broadly, we specialize in data science, machine learning, and algorithm development both on the edge and in the cloud. We provide end-to-end support throughout a product’s lifecycle, from quick exploratory prototypes to production-level AI/ML algorithms. We partner with our clients, who range from Fortune 500 companies to innovative startups, to turn their ideas into reality. Have a hard problem in mind? Get in touch at <a href="/service/mailto:info@edgeanalytics.io">info@edgeanalytics.io</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68e4cd9c223c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-model-development-68e4cd9c223c">MLOps at Edge Analytics | Model Development</a> was originally published in <a href="https://medium.com/edge-analytics">Edge Analytics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MLOps at Edge Analytics | A Data Processing Pipeline]]></title>
            <link>https://medium.com/edge-analytics/mlops-at-edge-analytics-a-data-processing-pipeline-4952f3b66868?source=rss----30d72a83ac98---4</link>
            <guid isPermaLink="false">https://medium.com/p/4952f3b66868</guid>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Connor Davis]]></dc:creator>
            <pubDate>Mon, 24 Apr 2023 16:17:11 GMT</pubDate>
            <atom:updated>2023-05-05T16:29:21.246Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part Two of Five</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TClApysZz3CZIDHojAaHvw.png" /><figcaption>Image created with DALL-E 2.</figcaption></figure><p>As machine learning models become more widely deployed, ML practitioners have shown increasing interest in MLOps. In our <a href="https://medium.com/@connor_48408/e3fcdaed7534">introductory blog</a>, we give a brief background on how we think about MLOps at Edge Analytics.</p><p>In this post, we’ll focus on approaches for transforming raw data into a form we can feed into a model. Cleaning, standardizing, and appropriately formatting raw data are all critically important in the machine learning development cycle. Building data processing pipelines that are flexible, robust, easy-to-understand, and scalable is one of the best investments an ML team can make. This post is part two of our five part series on building an MLOps pipeline.</p><p>You can find the other blogs in the series by following the links below:</p><ul><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-series-debdd6f423b0">Part 1: Data Storage with AWS S3 and Boto3</a></li><li>Part 2: Data Processing Pipeline</li><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-model-development-68e4cd9c223c">Part 3: Model Development</a></li><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-model-tracking-74d05c92b4e3">Part 4: Model Tracking</a></li><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-model-deployment-bf01489b121d">Part 5: Model Deployment</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NJIfdAcdkN1_bcoIEyjNqw.png" /></figure><p>In the first part of this series, we discussed how we can <a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-series-debdd6f423b0">store our raw data with AWS S3</a>, a widely used object storage service. Now, we turn our focus to preparing that data for modeling. Some key considerations for choosing data processing tools include:</p><ul><li>What format is our raw data currently in?</li><li>What format does the data need to be in for modeling?</li><li>How fast does our processing pipeline need to be?</li><li>How will we version our processed dataset so that we can re-use it in the future?</li></ul><p>Of all the steps in an MLOps pipeline, data processing is the least likely to be plug-and-play and often requires a bespoke pipeline. The answers to the questions above will likely depend heavily on the data type (images, time series, tabular, etc.), file format, and size. As such, there is no single best tool for all of your processing needs. Still, we’ll highlight a few of our favorite data wrangling tools in Python — native dataclasses, abstract base classes, and pyserde.</p><h3>Dataclasses</h3><p>One of the first considerations when building a data processing pipeline is how the raw, intermediate, and fully processed data will be represented in memory. We find that structuring the data into <a href="https://docs.python.org/3/library/dataclasses.html">Python dataclasses</a> results in highly expressive data structures with clean syntax and minimal engineering overhead. Recall from the prior blog, we’re demonstrating components of our MLOps pipeline on the <a href="https://www.kaggle.com/datasets/paultimothymooney/blood-cells">Blood Images Dataset</a> from Kaggle. Representing white blood cell images and associated metadata can look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44f8c8207ff9e2ad564dc2965298d1ff/href">https://medium.com/media/44f8c8207ff9e2ad564dc2965298d1ff/href</a></iframe><p>For each image, we create an Image instance as an information rich format for storing data. The full dataset can then be represented as a list of Images. This approach has slightly more overhead than dealing with raw arrays, but is much less likely to introduce bugs. Dataclasses also have lower engineering overhead than other solutions, such as <a href="https://protobuf.dev/">protocol buffers</a>. Flatter data structures and protocol buffers are effective tools that we use when appropriate, but for quick and effective pipelines we prefer native dataclasses.</p><h3>Abstract base classes</h3><p>Although data manipulation methods will vary from project to project, certain overarching steps are standard across data pipelines. For example, we expect to use methods for loading raw data, standardizing it, and dividing the processed data into train and test sets. <a href="https://docs.python.org/3/library/abc.html">Python abstract base classes</a> help in such cases where code is project specific, but we want a broadly applicable pipeline architecture.</p><p>An abstract base class acts as a roadmap for all children classes that inherit from it. An example abstract base class for a data processing pipeline might look as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66e00570de903aa155fed14cb77cc10a/href">https://medium.com/media/66e00570de903aa155fed14cb77cc10a/href</a></iframe><p>Note that the BasePipeline class inherits the ABC class from the abc package, and all major methods we will define for a specific data processing pipeline are decorated with @abstractmethod.</p><p>Now say we want to write an example data processing pipeline for our white blood cell images and call it BloodImagesPipeline. We can write this class as a child of BasePipeline. Doing so will enforce that the three abstract methods above are always implemented. The BloodImagesPipeline class might look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac8857d0f89cd18b036463d5f03c65fc/href">https://medium.com/media/ac8857d0f89cd18b036463d5f03c65fc/href</a></iframe><p>We can now instantiate this BloodImagesPipeline and use it to download, process, and split our dataset for modeling. If we had failed to define any of the three abstract methods in the parent, or attempted to give any of them a different name, the BloodImagesPipeline would fail to instantiate. In this way, abstract base classes can be used to guide development of data processing pipelines for various projects, no matter how different they are.</p><p>At the end of the data processing pipeline, we may find it necessary to store the resulting dataset prior to model training. It is a common practice for us to store processed datasets to ensure future modeling experiments are trained on exactly the same data. We may also need to capture additional information including the one-hot label encoder (if one is used), the random state used to generate the train/test splits, and other metadata associated with processing steps. Once again, we can create a dataclass for structuring this information.</p><h3>Serialization with pyserde</h3><p>We invest heavily in dataclasses that give our projects high structure, so we also need methods to serialize those dataclasses to disk. The <a href="https://pypi.org/project/pyserde/">pyserde library</a> provides easy-to-use functions for serializing/deserializing Python objects into common formats including JSON, YAML, and MessagePack. To use these functions, we add the @serde decorator to our dataclass. Then, we can easily write the serialized object to the appropriate AWS S3 bucket or local storage. Pulling objects from S3 and deserializing is similarly straightforward.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e99cef1af4a12a25ca59640193c01d01/href">https://medium.com/media/e99cef1af4a12a25ca59640193c01d01/href</a></iframe><p>There are a couple of caveats to using pyserde:</p><ul><li>Certain package-specific objects, such as the OneHotEncoder from the scikit-learn package, cannot be serialized. When using pyserde, it is best to stick to primitives, containers, standard library objects, and user defined dataclasses. You can find supported data types in <a href="https://yukinarit.github.io/pyserde/guide/supported-types.html">their documentation</a>.</li><li>Serializing with pyserde is a good option assuming the entire dataset can be loaded into memory all at once. With large datasets, this may not always be the case. Under those circumstances, other storage solutions like <a href="https://www.tensorflow.org/tutorials/distribute/input#sharding">Tensorflow sharded datasets</a> will be more appropriate.</li></ul><p>With pyserde and dataclasses, we can turn entire train and test sets into serialized objects that can be uploaded to and downloaded from cloud storage. In this way, we avoid processing raw data with each new model training. This helps save compute time and increases confidence in results by allowing for versioned datasets to ensure the exact same data is being fed into repeated model experiments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-3ZSrEPezeciETpVQ17sYw.png" /></figure><p>In this post, we looked at our solutions for setting up data pipelines using dataclasses, enforcing structure with abstract base classes, and serializing/deserializing with pyserde. In the next blog, we’ll dive into model training and development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PiSbtYKtigyEP37xM4d15Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nS5-8JNgfXqiTkCSlKGUoA.png" /></figure><h3>Machine learning at Edge Analytics</h3><p><a href="https://edgeanalytics.io/">Edge Analytics</a> helps companies build MLOps solutions for their specific use cases. More broadly, we specialize in data science, machine learning, and algorithm development both on the edge and in the cloud. We provide end-to-end support throughout a product’s lifecycle, from quick exploratory prototypes to production-level AI/ML algorithms. We partner with our clients, who range from Fortune 500 companies to innovative startups, to turn their ideas into reality. Have a hard problem in mind? Get in touch at <a href="/service/mailto:info@edgeanalytics.io">info@edgeanalytics.io</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4952f3b66868" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-a-data-processing-pipeline-4952f3b66868">MLOps at Edge Analytics | A Data Processing Pipeline</a> was originally published in <a href="https://medium.com/edge-analytics">Edge Analytics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MLOps at Edge Analytics | Data Storage with AWS S3 and Boto3]]></title>
            <link>https://medium.com/edge-analytics/mlops-at-edge-analytics-series-debdd6f423b0?source=rss----30d72a83ac98---4</link>
            <guid isPermaLink="false">https://medium.com/p/debdd6f423b0</guid>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[boto3]]></category>
            <dc:creator><![CDATA[Connor Davis]]></dc:creator>
            <pubDate>Fri, 14 Apr 2023 16:03:21 GMT</pubDate>
            <atom:updated>2023-05-05T16:30:41.510Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part One of Five</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*ZxaV_y-WZNRlGxsqCNZkZg.png" /><figcaption>Image created with DALL-E 2.</figcaption></figure><p>As machine learning models become more widely deployed, ML practitioners have shown increasing interest in MLOps. In our <a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-introduction-e3fcdaed7534">introductory blog</a>, we give a brief background on how we think about MLOps at Edge Analytics.</p><p>Here we look at the first pillar of an MLOps pipeline: data storage. This post is part one of a five part series. For the example dataset below, we store raw data for model training and evaluation in an AWS S3 bucket and access it using the Boto3 SDK in Python.</p><p>You can find the other blogs in the series by following the links below:</p><ul><li>Part 1: Data Storage with AWS S3 and Boto3</li><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-a-data-processing-pipeline-4952f3b66868">Part 2: Data Processing Pipeline</a></li><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-model-development-68e4cd9c223c">Part 3: Model Development</a></li><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-model-tracking-74d05c92b4e3">Part 4: Model Tracking</a></li><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-model-deployment-bf01489b121d">Part 5: Model Deployment</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*OTSiberVqDB74YrJaoJg6g.png" /></figure><p>All ML projects start with data. This data, whatever file type it is, however clean it is, must be stored somewhere. When deciding where to house the data, you might consider the following questions:</p><ol><li>What is the scale (MB / GB / TB) of our dataset?</li><li>What format is our data in (tabular, images, time series, text, etc.)?</li><li>What security features do we need for our dataset?</li><li>Do we want the dataset to be publicly available or restricted in any way?</li><li>What functionality exists to access the dataset as quickly as possible (I/O)?</li></ol><p>The answers to these questions can begin to provide guidance on how data should be stored. At Edge Analytics, we have experience using both data warehouses (e.g. Google BigQuery) and data lakes (e.g. AWS S3). For this example pipeline, we’ll lean towards data lakes for their ease of use and flexibility.</p><h3>AWS S3</h3><p>Object cloud storage services like <a href="https://aws.amazon.com/s3/">AWS S3</a>, <a href="https://azure.microsoft.com/en-us/products/storage/blobs">Microsoft Azure Blob</a>, and <a href="https://cloud.google.com/storage/">Google Cloud Storage</a> are widely used and very flexible as data lakes. Although all three provide <a href="https://www.techtarget.com/searchstorage/feature/AWS-vs-Azure-vs-Google-pricing-and-features-compared">similar features at similar prices</a>, AWS has <a href="https://www.pcmag.com/news/four-companies-control-67-of-the-worlds-cloud-infrastructure">led the cloud market</a> in recent years. For this example pipeline, we’ll store all data in AWS S3 buckets. Regarding the questions above:</p><ol><li><strong>What is the scale (MB / GB / TB) of our dataset? </strong>AWS S3 storage is scalable. Although there are limits to how many buckets can be created per account (<a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/BucketRestrictions.html">up to 100, unless a service limit increase is requested</a>), there is no upper limit to the size of a bucket. Additionally, it is <a href="https://aws.amazon.com/s3/pricing/?p=pm&amp;c=s3&amp;z=4">relatively inexpensive to request more storage space</a>.</li><li><strong>What format is our data in (tabular, images, time series, text, etc.)? </strong>S3 can be used to store data for countless use cases and arbitrary data types. Setting up a data lake of raw or processed data files for your project is very straightforward.</li><li><strong>What security features do we need for our dataset? </strong>S3 has many security features that ensure the protection of data like automatic encryption and <a href="https://aws.amazon.com/macie/">Macie</a>, which discovers and reports on sensitive data in your buckets.</li><li><strong>Do we want the dataset to be publicly available or restricted in any way? </strong>Access to S3 buckets is easily managed through services that dictate who can see what data and when. Credentials with varying levels of access can be granted by your AWS manager. Contrarily, if you want to make the data public, S3 will allow that too!</li><li><strong>What functionality exists to access the dataset as quickly as possible (I/O)? </strong>There are several ways of accessing files stored in S3 buckets including a command line interface (CLI), the AWS S3 GUI console, or the Boto3 software development kit (SDK) in python.</li></ol><p>The product offerings for S3 are expansive. We touch very briefly on a few features we use frequently. AWS offers more comprehensive documentation on the <a href="https://aws.amazon.com/s3/">S3 landing page</a>.</p><h3>An example storage solution</h3><p>Prior to interacting with data in S3, you’ll first need to set up AWS credentials and <a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">install the AWS CLI</a>. Once you have credentials for accessing S3, run `aws configure` in your local terminal. A `config` and `credential` file will be created, and you’ll be free to use the S3 CLI. If working in Python, you can install the Python Boto3 SDK instead.</p><p>The data for our blood images classifier example was borrowed from this <a href="https://www.kaggle.com/datasets/paultimothymooney/blood-cells">Blood Cell Images</a> dataset on Kaggle. It consists of 410 JPEG microscope images of white blood cells, 410 XML files with image annotations (one per image), and a single CSV file that gives the cell type label for each image. These files were downloaded to a local machine, then uploaded as-is to an AWS S3 bucket via the CLI. The file structure is shown here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CJllsLQV6pvbRjdLJHTZ2w.png" /><figcaption>File structure of the blood images dataset.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lPNhWSylbOE7u4dhG5oE1A.png" /></figure><h4>Helpful tip!</h4><p>S3 buckets are data lakes; they have a <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-folders.html">flat file structure</a>. So although it is easier to think in terms of a hierarchical file structure, like the one above, the reality is a bit different. Rather than treating files as located within folders, S3 treats cascading directories as prefixes to file names. So the file structure in S3 actually looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vU-mUVNXRzEmuvWs-KXWFg.png" /><figcaption>File structure of the blood images dataset in an S3 bucket.</figcaption></figure><p>Because of this flat structure, there is a tradeoff between finding files easily in the AWS GUI console and accessing files quickly via code. Using a hierarchical folder naming convention can help a user manually find files but slows programmatic access if many files must be read. Alternatively, giving files unique names without folder prefixes speeds up recursive file reading but makes it harder for a user to identify a file based on name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lPNhWSylbOE7u4dhG5oE1A.png" /></figure><p>Although the AWS S3 CLI and GUI console are great for mobilizing data files, the Boto3 SDK in Python works best for loading them into working memory of a Python application, which is our use case here. The functionality of Boto3 is extensive, so much so that we decided to distill and simplify only the functions we needed into a separate class called S3Operations. This class includes ergonomic methods for:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b05b21dd56d09769756bb01fb9515f9d/href">https://medium.com/media/b05b21dd56d09769756bb01fb9515f9d/href</a></iframe><p>As mentioned, the methods in the S3Operations class are wrappers over core Boto3 functionality. We find these convenience methods speed up development time by abstracting hard-to-remember Boto3 syntax into method names we can easily reference. It turns out, for most data I/O we do, we typically use a fairly small subset of Boto3’s total functionality.</p><p>Here is a short snippet of how we use the S3Operations class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b734be555255ed82f7461787d3dda7a1/href">https://medium.com/media/b734be555255ed82f7461787d3dda7a1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lPNhWSylbOE7u4dhG5oE1A.png" /></figure><h4>Helpful tip!</h4><p>The Boto3 SDK requires either a “client” or “resource” to be instantiated in your Python program (e.g. as client = boto3.client(“s3”)) for making S3 service requests. <strong>We recommend always using “client”</strong>. The Boto 3 “client” is a low-level interface that has broad utility and returns metadata for your S3 request along with the data. The “resource” is a high-level interface built on top of the “client” that makes accessing files simple at the expense of some flexibility. As of January 2023, <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/guide/resources.html">AWS does not intend to add new features to “resource.”</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lPNhWSylbOE7u4dhG5oE1A.png" /></figure><h3>Up next</h3><p>Now that we have a place to store the raw data and a way to access it, we will move to the next step in our MLOps pipeline: data processing. Stay tuned for the next blog which we expect to publish the week of April 24.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SBE5y82L_VFflChrx3YHIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nS5-8JNgfXqiTkCSlKGUoA.png" /></figure><h3>Machine learning at Edge Analytics</h3><p><a href="https://edgeanalytics.io/">Edge Analytics</a> helps companies build MLOps solutions for their specific use cases. More broadly, we specialize in data science, machine learning, and algorithm development both on the edge and in the cloud. We provide end-to-end support throughout a product’s lifecycle, from quick exploratory prototypes to production-level AI/ML algorithms. We partner with our clients, who range from Fortune 500 companies to innovative startups, to turn their ideas into reality. Have a hard problem in mind? Get in touch at <a href="/service/mailto:info@edgeanalytics.io">info@edgeanalytics.io</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=debdd6f423b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-series-debdd6f423b0">MLOps at Edge Analytics | Data Storage with AWS S3 and Boto3</a> was originally published in <a href="https://medium.com/edge-analytics">Edge Analytics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MLOps at Edge Analytics | Introduction]]></title>
            <link>https://medium.com/edge-analytics/mlops-at-edge-analytics-series-e3fcdaed7534?source=rss----30d72a83ac98---4</link>
            <guid isPermaLink="false">https://medium.com/p/e3fcdaed7534</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Connor Davis]]></dc:creator>
            <pubDate>Fri, 14 Apr 2023 16:02:16 GMT</pubDate>
            <atom:updated>2023-07-24T20:28:45.283Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ZotInIdn7kkv2UqW9t1FQ.png" /><figcaption>Image created with DALL-E 2.</figcaption></figure><p>At <a href="https://edgeanalytics.io/">Edge Analytics</a>, we strive to develop machine learning applications that are transparent and reproducible. Machine learning projects are often composed of many parts, and the rapidly available software solutions for managing these parts are collectively called Machine Learning Operations (MLOps).</p><p>We’ve found investing in MLOps infrastructure accelerates our ability to extract meaningful insights for the problems we solve. A robust MLOps infrastructure optimizes our iteration time and increases our trust in the models we develop for clients. In this blog series, we’ll discuss an example MLOps pipeline using some of our favorite tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLpnAyyWnz9ZAbc23v0Bxw.png" /></figure><h3>How we use MLOps at Edge Analytics</h3><p>Our team develops and deploys ML models to both edge devices and the cloud. Tracking model development and deployment is critical to ensure algorithms behave as expected in the wild. We’ll demonstrate one example of a full pipeline using tools that have worked well for our team. The example is a modular architecture with functionality broken into five major steps. These steps include:</p><ol><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-series-debdd6f423b0">Data Storage and I/O</a></li><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-a-data-processing-pipeline-4952f3b66868">Data Processing</a></li><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-model-development-68e4cd9c223c">Model Development</a></li><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-model-tracking-74d05c92b4e3">Model Tracking</a></li><li><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-model-deployment-bf01489b121d">Model Deployment</a></li></ol><p>The specific structures of MLOps pipelines will vary from project to project. At Edge Analytics, we use the best tools for the job at hand; however, we consistently use the above five points as guiding pillars for MLOps pipeline development.</p><h3>Considerations for pipeline development</h3><p>Building an MLOps pipeline comes with countless trade-offs for balancing structure and flexibility. In selecting the best tools for our clients, we are guided by two major principles:</p><ol><li>Code abstractions for third-party tools should be simple, consistent, and well documented.</li><li>No single platform has the best of all solutions, and new features are frequently available. We should maintain a flexible pipeline capable of interchanging third-party platforms.</li></ol><p>There are several services that provide end-to-end MLOps support, such as <a href="https://aws.amazon.com/sagemaker/">AWS SageMaker</a> and <a href="https://www.ray.io/">Ray</a>. However, we aim to avoid tight coupling with any given service by enabling integration with a variety of Python packages and services.</p><p>Lastly, it should be acknowledged that there is no one way to build an MLOps pipeline. There are many incredible tools that can assist in developing and tracking ML models. We hope this example pipeline gives you a good place to start and encourages you to seek out the methods that best serve your project!</p><h3>A blog series to showcase our process</h3><p>Over this series of blog posts, we will examine each of the five central MLOps pipeline pillars more closely in the context of an example project classifying white blood cell images by cell type. And with that, let’s take a look at <a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-part-1-data-storage-with-aws-s3-and-boto3-debdd6f423b0">data storage</a>…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OTSiberVqDB74YrJaoJg6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nS5-8JNgfXqiTkCSlKGUoA.png" /></figure><h3>Machine learning at Edge Analytics</h3><p><a href="https://edgeanalytics.io/">Edge Analytics</a> helps companies build MLOps solutions for their specific use cases. More broadly, we specialize in data science, machine learning, and algorithm development both on the edge and in the cloud. We provide end-to-end support throughout a product’s lifecycle, from quick exploratory prototypes to production-level AI/ML algorithms. We partner with our clients, who range from Fortune 500 companies to innovative startups, to turn their ideas into reality. Have a hard problem in mind? Get in touch at <a href="/service/mailto:info@edgeanalytics.io">info@edgeanalytics.io</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3fcdaed7534" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edge-analytics/mlops-at-edge-analytics-series-e3fcdaed7534">MLOps at Edge Analytics | Introduction</a> was originally published in <a href="https://medium.com/edge-analytics">Edge Analytics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a CNN to predict bicycle wheelies: insights into rapid prototyping]]></title>
            <link>https://medium.com/edge-analytics/building-a-cnn-to-predict-bicycle-wheelies-insights-into-rapid-prototyping-143d5f09c167?source=rss----30d72a83ac98---4</link>
            <guid isPermaLink="false">https://medium.com/p/143d5f09c167</guid>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[digital-health]]></category>
            <category><![CDATA[sensors]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ren Gibbons]]></dc:creator>
            <pubDate>Thu, 30 Mar 2023 15:55:56 GMT</pubDate>
            <atom:updated>2023-03-30T15:55:55.995Z</atom:updated>
            <content:encoded><![CDATA[<h4>We chronicle our quick iteration process building an ML model for bicycle wheelies from IMU data in spare time over three days.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/0*YQ0vWqgm0WxQiyUf" /></figure><p>At <a href="https://edgeanalytics.io/">Edge Analytics</a>, we have years of experience developing machine learning models built for human movements and deploying those models in low power, compute constrained environments like wearable devices. Specifically, we’ve worked extensively with inertial measurement unit (IMU) data (i.e. three axis accelerometer and gyroscope channels) collected on the body with applications in consumer electronics and digital health and medicine. Applications we’ve worked on in the past include <a href="https://medium.com/edge-analytics/neural-network-on-the-tip-of-a-pencil-efd4c83ed36c">sleep tracking</a>, <a href="https://blog.cionic.com/predicting-someones-movement-before-they-move-f949fddf0aa9">gesture recognition</a>, walking speed, and prediction of physiological phenomena that can’t be directly captured from movement.</p><p>As we’ve gone through iteration cycles of building and deploying models, we realized the importance of collecting our own pilot data for rapid experimentation and algorithm development in early phase product cycles. Demonstrating proof of concept early can ensure viability of an idea before investing heavily in expensive and time consuming data collection efforts. We made an internal investment to build out firmware to enable easy collection of IMU data using the <a href="https://www.st.com/en/evaluation-tools/steval-mksbox1v1.html">ST SensorTile.box</a> prototype board and <a href="https://www.st.com/resource/en/application_note/dm00571818-lsm6dsox-alwayson-3d-accelerometer-and-3d-gyroscope-stmicroelectronics.pdf">ST LSM6DSOX</a> sensor module. Building these tools has paid dividends multiple times over, as we can now iterate from idea to data collection to proof of concept in an afternoon for algorithms built on IMU data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HwQ7CkAvkr3AkoIt" /><figcaption><em>Our standard flow when first working on a new problem like bicycle wheelies.</em></figcaption></figure><p>We had a silly idea recently to see if we could build a machine learning model to help track one of the author’s favorite pastimes: riding wheelies on a mountain bike. Going through a rapid iteration cycle of building a convolutional network with 97% accuracy at predicting between wheelie, pedal, coast, or other/unknown classes reveals a lot about Edge’s process for building early prototypes. From no data to final model iteration, we built out this proof of concept in spare time over three days.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VMMg0GfYfTcdBilQ" /><figcaption><em>We built a neural network to predict whether a movement is a bicycle wheelie, pedal, coast, or </em>other/<em>unknown gesture.</em></figcaption></figure><p>Having a platform for data collection is a prerequisite for building a proof of concept wheelie predictor. Our solution to this was a prior investment in building firmware tools and utilities that enable the <a href="https://www.st.com/en/evaluation-tools/steval-mksbox1v1.html">SensorTile.box</a>, a prototype IoT board with ARM Cortex-M4 microcontroller, to work with the <a href="https://www.st.com/resource/en/application_note/dm00571818-lsm6dsox-alwayson-3d-accelerometer-and-3d-gyroscope-stmicroelectronics.pdf">LSM6DSOX</a>, an integrated circuit with accelerometer and gyroscope. Look out for a future blog where we outline how we approached building the firmware to support data collection with this hardware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RfaP28bTNonSGyZ1" /><figcaption><em>Picture of the SensorTile prototype board used to collect data for this project.</em></figcaption></figure><h3>Collecting data</h3><p>As is often the case when working with data from sensors on the human body, data collection was perhaps the most challenging aspect of this project. We placed the SensorTile box on the lateral side of the right thigh to capture the pedaling motion. We assumed <em>a priori</em> that approximately three minutes of training data would be sufficient for an initial model. Collecting data for pedaling, coasting, and other/unknown was straightforward. We simply started collecting data from a stop, then began bicycling. Obtaining labeled data for wheelies was more challenging since the author cannot hold a wheelie indefinitely. Instead, he’d repeat sets of wheelies as long as possible (typically 5–20 seconds). Then, later during data processing, we manually labeled periods of each recording as one of the four labels. Extracted windows of each class are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7wH4OdEEeXQumN1E" /><figcaption><em>Three second windows showing raw IMU data for each of the four classes. Clear visual differences in each class exist indicating this problem should be fairly straightforward for a well designed machine learning model.</em></figcaption></figure><p>Test data was collected using a similar protocol, though each test recording is distinct from the training recordings to show some generalization.</p><p>We note the proof of concept demonstrated here is on a sample of n=1 persons. If Edge decided to invest more heavily in this work, we would recruit from a much larger pool of participants for data collection while carefully considering our inclusion criteria to ensure the training data accurately reflects the end user population to avoid model bias.</p><h3>Creating a model to predict wheelies</h3><p>Next, we trained a 1D convolutional neural network (CNN) on windows of IMU data labeled by activity class. We chose a three layer 1D CNN since this architecture has certain favorable characteristics (e.g. a 0.5 second receptive field with temporal invariance of IMU features within the window) and is fairly amenable to deployment to a microcontroller. In fact, TensflowLite for Microcontollers provides a “Magic Wand” <a href="https://codelabs.developers.google.com/magicwand#0">tutorial</a> that uses a similar 1D CNN configuration. Deploying models like this to low power microcontrollers is gaining traction but still remains fairly cutting edge. We may do a follow up blog showing how we’d deploy such a model (if you would like to see this blog, let us know in the comments!).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z3arM1pyoVoEnM9D" /><figcaption><em>CNN architecture used for this project. The IMU is sampled at 208 Hz, so a 100 sample window is about a half second of data seen by the model during a single inference.</em></figcaption></figure><p>As anticipated by training data visuals in the previous section, our CNN does quite well at learning to detect wheelies. The video below shows a single recording including all four model activity classes. Model inference is run on a desktop with a stride of two samples, but any stride can be chosen. Note the model is quite confident during steady state activity like wheelies but experiences slight delays at transition periods. This is expected since the model sees a window extending half a second in the past.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*YylLCvvNojmLy0MA" /><figcaption><em>Aligned video, prediction, and IMU streams of a recording containing all classes. CNN inference occurs on a desktop with a stride of two samples and a 100 sample window (nominal sample rate is 208 Hz). The background colors show the true activity label. During “steady state”, the model is quite confident in its predictions. As the author begins bicycling, the model experiences some uncertainty, and there is some inevitable transition delay between classes.</em></figcaption></figure><p>The video above shows how the model performs when predicting activity by rolling over a recording of data. Below, we show quantitative results of model performance on 1,966 samples from five test recordings. Overall, the model achieves 97% accuracy. Note the model has slightly lower recall for coast and pedal, which the model occasionally predicts as other/unknown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*22kot5vHkenA3QDC" /><figcaption><em>Test set confusion matrix and classification report. Overall, the model achieves 97% accuracy on 1,966 samples. The model is quite confident in wheelie predictions, only making mistakes in 11 of 788 samples. The model occasionally misclassifies pedal and coast as other/unknown. Note that we did not evaluate on other/unknown in this confusion matrix since true positives of wheelie, pedal, and coast are of highest interest.</em></figcaption></figure><h3>Meaningful applications in digital health</h3><p>Despite having a lot of fun on this project, this exact application’s impact could only provide value to a minuscule subset of the total population. One of our driving goals at Edge is to ultimately build products that help a broad range of people, and we are very interested in deploying algorithms for digital health to wearables. IMU sensors are commonly used in consumer devices as well as digital health research including <a href="https://www.medrxiv.org/content/10.1101/2020.07.24.20160663v1.full.pdf">sleep tracking</a>, <a href="https://www.thelancet.com/journals/landig/article/PIIS2589-7500(22)00111-X/fulltext">activity monitoring</a>, <a href="https://www.nature.com/articles/s41746-022-00676-9">disease incidence</a>, and <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC9318359/">diagnostics</a>. Often used for <a href="https://www.ingentaconnect.com/content/wk/ajg/2022/00000117/00000001/art00017">remote monitoring and management</a> of various conditions, IMU sensors can improve healthcare outcomes, which is very exciting to our team. We are particularly interested in using IMU sensors to improve activity detection in certain populations, such as in elderly care, or in edge case activities like pushing a stroller (stay tuned for an upcoming blog on this!).</p><h3>Where we would take this next</h3><p>Developing a 1D CNN wheelie detector for a single user was a fun proof of concept, but where would we take this next? At Edge, we like to explore the full scope of problems to see how much performance we can extract by using more complex algorithms and, equally importantly, see how simple a model can be while retaining acceptable performance. We’re interested in applying sequence model architectures (e.g. LSTM), or even transformers, to this task as an exploration of more complex models. On the other hand, we wonder how far we could get using a simple tree or heuristics based approach. Furthermore, we are always interested in pushing models to microcontrollers. Stay tuned for follow up blogs where we will explore these concepts and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_iVJ81im2vmYRIA5" /></figure><h3>Machine learning at Edge Analytics</h3><p><a href="https://edgeanalytics.io/">Edge Analytics</a> has helped multiple companies build solutions using IMU data on the body. More broadly, we specialize in data science, machine learning, and algorithm development both on the edge and in the cloud. We provide end-to-end support throughout a product’s lifecycle, from quick exploratory prototypes to production-level AI/ML algorithms. We partner with our clients, who range from Fortune 500 companies to innovative startups, to turn their ideas into reality. Have a hard problem in mind? Get in touch at <a href="/service/mailto:info@edgeanalytics.io">info@edgeanalytics.io</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=143d5f09c167" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edge-analytics/building-a-cnn-to-predict-bicycle-wheelies-insights-into-rapid-prototyping-143d5f09c167">Building a CNN to predict bicycle wheelies: insights into rapid prototyping</a> was originally published in <a href="https://medium.com/edge-analytics">Edge Analytics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating Better Health Outcomes: Harnessing Generative ML Models in Digital Medicine]]></title>
            <link>https://medium.com/edge-analytics/generating-better-health-outcomes-harnessing-generative-ml-models-in-digital-medicine-329b5d9ffb0e?source=rss----30d72a83ac98---4</link>
            <guid isPermaLink="false">https://medium.com/p/329b5d9ffb0e</guid>
            <category><![CDATA[medicine]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[generative-ai]]></category>
            <dc:creator><![CDATA[Brinnae Bent, PhD]]></dc:creator>
            <pubDate>Thu, 23 Mar 2023 15:04:26 GMT</pubDate>
            <atom:updated>2023-03-23T15:14:42.023Z</atom:updated>
            <content:encoded><![CDATA[<p>The public has been enraptured by artistic images created using generative models like <a href="https://openai.com/product/dall-e-2">DALLE-2</a> and <a href="https://stability.ai/blog/stable-diffusion-public-release">Stable Diffusion</a> and have been amazed by conversations with the seemingly omniscient <a href="https://chat.openai.com/chat">Chat-GPT</a>. Use cases for these generative models are being explored in spaces from <a href="https://www.mckinsey.com/industries/retail/our-insights/generative-ai-unlocking-the-future-of-fashion">fashion</a> to <a href="https://www.forbes.com/sites/johanmoreno/2022/11/17/notion-ai-wants-to-be-your-new-writing-assistant/?sh=44a3792f746e">copy editing</a>.</p><p>As a digital health data scientist at <a href="https://edgeanalytics.io/">Edge Analytics</a>, I am always on the lookout for the best machine learning methods to solve healthcare problems. In this article, I delve into the applications of generative ML models in digital medicine. With the potential to generate synthetic data for algorithm training, support analysis of existing health data, personalize medicine through simulation, and enhance patient education, these models hold great promise. I am particularly interested in exploring the use cases of generative models in mental health and will provide an in-depth analysis of this application.</p><p>Overall, this article highlights potential future use cases for generative models in digital medicine.</p><h3>Improving models through data generation</h3><p>Training machine learning models for medical applications is challenging. One of the primary reasons for this is a lack of available training data. Machine learning models require large amounts of training data to make accurate predictions. Medical data is particularly challenging to obtain and use for a number of reasons. First, data should be procured with patient permission to ensure patient privacy, a process that is often very time-consuming and resource-intensive. Second, medical data is often highly imbalanced, and poor data coverage makes modeling rare conditions difficult. For example, gathering data on a specific type of cancer might yield just a few cases amidst hundreds or thousands of records. Lastly, available medical data is highly biased. Machine learning models exhibit the same biases as the data used to train them, so critical to minimize bias in training datasets.</p><p>Generative models can be used to synthetically create balanced realistic data with minimal bias and no privacy restrictions. A few examples for how generative synthetic data could be used in digital medicine:</p><ul><li>Generative models can be used to create synthetic medical images similar to their real counterparts, but with a known ground truth. This can help in the development and evaluation of medical image analysis algorithms. For example, generative adversarial networks (GANs), have already been used to produce synthetic X-ray, computed tomography (CT), magnetic resonance imaging (MRI), and positron emission tomography as well as retinal, dermoscopic, and ultrasound images [<a href="https://pubmed.ncbi.nlm.nih.gov/35022924/">Source</a>, <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC9345230/">Source</a>].</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/0*y9f-0gU5xiJUoo6y" /></figure><p><strong>Caption:</strong> <em>Synthetic chest X-rays using NVIDIA’s StyleGAN2-ADA model [</em><a href="https://pubmed.ncbi.nlm.nih.gov/35022924/"><em>Source</em></a><em>]</em></p><ul><li>Generative models can be used to synthesize patient data for use in research and development while maintaining patient privacy. For example, privacy regulations often limit access to electronic health record (EHR) data. Using synthetic EHR data generated using GAN or GAN-style models can eliminate this risk [<a href="http://proceedings.mlr.press/v68/choi17a">Source</a>, <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7647178/">Source</a>].</li><li>To help researchers and clinicians better understand disease progression and effective treatments, generative models can be used to predict the progression of diseases by generating synthetic data that simulates the disease process. A recent study used a generative Markov-Bayesian-based model to generate 5,000 synthetic illness trajectories to infer the progression of complications in type 2 diabetes patients [<a href="https://bmcmedinformdecismak.biomedcentral.com/articles/10.1186/s12911-022-01915-5">Source</a>].</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EtnoYIIjq30G4WAF" /><figcaption><em>Generative models can create thousands of illness trajectories, as shown here, which can be used to better understand disease progression and improve treatments [</em><a href="https://bmcmedinformdecismak.biomedcentral.com/articles/10.1186/s12911-022-01915-5/figures/3"><em>Source</em></a><em>]</em></figcaption></figure><p>In addition to synthetic data generation, generative models can be used to augment existing data. Augmenting existing datasets with additional data points may be helpful in cases where the available data is limited, or when the model needs more training examples. A recent study uses GANs to augment the Cleveland dataset, a small and imbalanced dataset for heart disease prediction [<a href="https://www.mdpi.com/2075-4418/12/12/2899">Source</a>]. Another recent study proposes a longitudinal-diagnostic generative adversarial network (LDGAN) to predict multiple clinical scores at future time points using incomplete longitudinal MRI data [<a href="https://mingxia.web.unc.edu/wp-content/uploads/sites/12411/2020/11/ning2020_chapter_ldganlongitudinal-diagnosticge.pdf">Source</a>].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*VS83wVznA5B4SOKL71x0Kg.png" /><figcaption><em>Data augmentation of MRI data using a generative adversarial network [</em><a href="https://mingxia.web.unc.edu/wp-content/uploads/sites/12411/2020/11/ning2020_chapter_ldganlongitudinal-diagnosticge.pdf"><em>Source</em></a><em>]</em></figcaption></figure><p>Data imputation is often done when data points are missing due to measurement error or patient noncompliance. While traditional data imputation methods are simple (i.e. mean or median imputation), they are often not representative of the actual data and can have significant impacts on the resulting model. In some instances, generative models can be used for data imputation. Imputation using generative models has been shown to have better performance than traditional methods in clinical research applications [<a href="https://bmcmedresmethodol.biomedcentral.com/articles/10.1186/s12874-021-01272-3">Source</a>].</p><h3>Supporting analyses of existing health data</h3><p>The incredible power of generative large language models could be harnessed for analysis of existing datasets in digital medicine. For example, a model can scan through hundreds of pages of medical records to extract key information for personalized treatment or health plans. The development of a large language model for EHRs has been used for clinical concept extraction, medical relation extraction, semantic textual similarity, natural language inference, and medical question answering [<a href="http://nature.com/articles/s41746-022-00742-2">Source</a>]. Models fine-tuned on biomedical data, like <a href="https://arxiv.org/pdf/2210.10341.pdf">BioGPT</a> (fine-tuned on GPT-2) or <a href="https://aws.amazon.com/comprehend/medical/">AWS Comprehend Medical</a>, will play a central role in language modeling applied to medicine.</p><p>Generative models could also be used to aid healthcare providers through clinical decision support, like identifying potential drug interactions or recommending medication dosages. Early stage research shows great promise in predicting drug-drug interactions using generative models [<a href="https://arxiv.org/pdf/2209.09941.pdf">Source</a>]. Research using generative models to design drug combinations showed that the generated drug combinations collectively cover the disease module similar to FDA-approved drug combinations and could potentially suggest novel pharmacology strategies [<a href="https://academic.oup.com/bioinformatics/article/36/Supplement_1/i445/5870465">Source</a>].</p><p>Research in digital medicine could also greatly benefit from generative models: by analyzing large amounts of data and identifying patterns and trends, generative models could aid in the development of new insights into the causes of diseases, methods for early detection of disease, and novel treatments. Early research shows promising results using GANs to assess progression of Alzheimer’s disease [<a href="https://www.frontiersin.org/articles/10.3389/fnagi.2022.841696/full">Source</a>].</p><h3>Personalized medicine with a digital twin</h3><p>A digital twin is a virtual model designed to accurately reflect a physical object. Used in applications from modeling wind turbines to space capsules, digital twins are extremely useful for providing insights into a variety of sensor systems and their environment.</p><p>The human body is incredibly complex and thus challenging to simulate. With generative models, we may get one step closer to having our own health digital twin. Health digital twins are virtual representations of patients that are generated from multimodal patient data, population data, and real-time updates on patient and environmental variables [<a href="https://www.nature.com/articles/s41746-022-00694-7#:~:text=Health%20digital%20twins%20are%20defined,on%20patient%20and%20environmental%20variables.">Source</a>]. For example, generative models could be used to predict the outcomes of different treatment options and predict an individual’s response to different treatment options, personalizing medicine. The startup world is already investing in this idea: <a href="https://www.unlearn.ai/">Unlearn AI</a> has raised <a href="https://www.fastcompany.com/90814042/digital-twins-drug-development-clinical-trials-ai-innovation">$50 million</a> to build their platform that simulates potential health outcomes for individual patients using generative models.</p><h3>Patient education</h3><p>Generative models could also be used for patient education and to help patients manage their health and wellness. Imagine an empathetic <a href="https://symptoms.webmd.com/">WebMD</a>, interactive educational modules to explain medical concepts, or a disease management system to help patients manage chronic conditions, such as diabetes or hypertension. While not reliable enough to provide healthcare management education yet, generative models hold significant promise to enable personalization of education and health management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eT9tKX_X0A9ZbuWj" /><figcaption><em>Generative models could be used to create empathetic, interactive chatbots for patient education and health management (Source: author using DALL-E 2)</em></figcaption></figure><h3>Applying generative models to mental health</h3><p>The mental health subfield of digital medicine is one area with numerous applications for generative models. Therapies could be enhanced greatly using generative modeling.</p><ul><li>Art is a common mode of therapy. Image generative models can be used to generate art in collaboration with patients. Patients providing inputs to generate unique artwork could be used as a form of creative expression and therapy. At the time of writing this article, I could only find one app claiming to use generative AI art for art therapy, <a href="https://creator.nightcafe.studio/ai-art-therapy">NightCafe</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u_k9bF7e9WUnR7tq" /><figcaption><em>Generative image models could be used in art therapy (Source: author using DALL-E 2)</em></figcaption></figure><ul><li>Generative models could be used to generate images representing a patient’s emotions to serve as a starting point for discussion during traditional therapy sessions.</li><li>Image <a href="https://digitalcommons.lindenwood.edu/cgi/viewcontent.cgi?article=1452&amp;context=faculty-research-papers">generative models can be used to create realistic virtual environments</a> for patients to experience. These <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6823515/">virtual environments can be used in exposure therapy</a> to help patients confront their fears or anxieties in a controlled setting.</li><li>“Bot therapists” built on large language generative models could be used for 24/7 therapy sessions. People who are worried about judgment or biased care may be more willing to share their concerns with a bot. The Chat GPT <a href="https://www.reddit.com/r/ChatGPT/comments/zr5e17/chatgpt_is_better_than_my_therapist_holy_shit/">subreddit</a> is filled with individuals using Chat GPT as therapy [<a href="https://www.axios.com/2023/03/08/therapy-chatbots-chatgpt-ai">Source</a>]. It is important to note, however, that, according to OpenAI’s <a href="https://platform.openai.com/docs/usage-policies/platform-policy">policies</a>, Chat GPT is not fine-tuned to provide medical information and should not be used to provide diagnostic or treatment services for health conditions. In the future, one could imagine a world where a Chat GPT-like model <strong>is </strong>fine-tuned or trained with medical data to provide therapy.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PZIYRmQVxyZZcN_l" /><figcaption><em>Anecdotally, Chat-GPT is already being used as a proxy for therapy. In the future, sophisticated generative models may be developed specifically for improving mental health (Source: author using Chat-GPT)</em></figcaption></figure><h3>Potential challenges</h3><p>There are a number of challenges with using generative models in digital medicine that will need to be addressed as these technologies transition from R&amp;D to clinical settings. In addition to <a href="https://link.springer.com/article/10.1007/s13735-020-00196-w">technical challenges</a> [<a href="https://www.sciencedirect.com/science/article/pii/S2352396423000774">Source</a>, <a href="https://www.researchgate.net/publication/339808092_Medical_Text_and_Image_Processing_Applications_Issues_and_Challenges">Source</a>], there are ethical considerations that I would be remiss to not note:</p><p><strong>Bias</strong></p><p>Bias in the training dataset of generative models will result in biased model outputs. Models should be trained using representative data from the population they intend to be used on to mitigate downstream <a href="https://www.ajl.org/">bias and potential harm</a>.</p><p><strong>Misuse</strong></p><p>Misuse of these models in healthcare is another potential challenge. These models have incredible potential to augment healthcare, but these models should never be intended to replace a healthcare provider or be used for nefarious purposes.</p><h3>Conclusions</h3><p>In conclusion, generative models hold immense potential in digital medicine. They can augment models with synthetic data, aid in the analysis of existing data, and personalize medicine through the creation of a “digital twin”. Additionally, generative AI can improve patient education and therapy, particularly in the domain of mental health. While there are challenges to overcome, I believe we are only just beginning to see the benefits to healthcare generative models will provide.</p><h3>What are you planning to use generative models for?</h3><p>We want to hear from you! How do you plan to use generative models? Leave us a comment or send us an email at <a href="http://info@edgeanalytics.io/">info@edgeanalytics.io</a>. While you’re here, check out our blog series on Getting the Most Out of GPT-3-based Text Classifiers: <a href="https://medium.com/edge-analytics/getting-the-most-out-of-gpt-3-based-text-classifiers-part-one-797460a5556e">Part 1</a>, <a href="https://medium.com/edge-analytics/getting-the-most-out-of-gpt-3-based-text-classifiers-part-two-a869313b4206">Part 2</a>, <a href="https://medium.com/edge-analytics/getting-the-most-out-of-gpt-3-based-text-classifiers-part-three-77305628f472">Part 3</a> or check out our recent blog on <a href="https://medium.com/edge-analytics/from-scribbles-to-summaries-enhancing-ocr-models-with-gpt-edit-for-handwritten-notes-e1940bbad8f9">GPT-Edit</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JxxmP_0-piEAVNQB" /></figure><h3>Generative AI at Edge Analytics</h3><p><a href="https://edgeanalytics.io/">Edge Analytics</a> has helped multiple companies build solutions that leverage generative models. More broadly, we specialize in data science, machine learning, and algorithm development both on the edge and in the cloud. We provide end-to-end support throughout a product’s lifecycle, from quick exploratory prototypes to production-level AI/ML algorithms. We partner with our clients, who range from Fortune 500 companies to innovative startups, to turn their ideas into reality. Have a hard problem in mind? Get in touch at <a href="http://info@edgeanalytics.io/">info@edgeanalytics.io</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=329b5d9ffb0e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edge-analytics/generating-better-health-outcomes-harnessing-generative-ml-models-in-digital-medicine-329b5d9ffb0e">Generating Better Health Outcomes: Harnessing Generative ML Models in Digital Medicine</a> was originally published in <a href="https://medium.com/edge-analytics">Edge Analytics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Scribbles to Summaries: Enhancing OCR Models with GPT-Edit for Handwritten Notes]]></title>
            <link>https://medium.com/edge-analytics/from-scribbles-to-summaries-enhancing-ocr-models-with-gpt-edit-for-handwritten-notes-e1940bbad8f9?source=rss----30d72a83ac98---4</link>
            <guid isPermaLink="false">https://medium.com/p/e1940bbad8f9</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Brinnae Bent, PhD]]></dc:creator>
            <pubDate>Wed, 08 Mar 2023 14:18:58 GMT</pubDate>
            <atom:updated>2023-03-24T15:23:52.595Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PJjdobwan8OucCED" /><figcaption><em>Created with DALL-E 2 by the author</em></figcaption></figure><p><em>*** EDIT: As of 3/23/23, OpenAI has </em><a href="https://news.ycombinator.com/item?id=35242069"><em>discontinued</em></a><em> GPT Edit. You can use GPT-4 to format and summarize notes in one go with the following prompt: “You are a note formatter and summarizer. You format notes as Markdown and fix grammar and spelling. Then you append a 3 bullet summary to the end of the note.” ***</em></p><p>In the age of digitization, many still prefer taking notes by hand rather than typing. This is great until a co-worker asks you to send your notes from last week’s meeting, but the notes only exist on paper. Thumbing back through your notebook to transcribe (and reformat) those notes to a computer is a painful process. Advances in AI can help with this.</p><p>In this blog, we’ll show our solution for automatically converting handwritten notes to a usable, reformatted text summary using a common OCR-based handwriting-to-text application and GPT-Edit.</p><h3>What is GPT-Edit?</h3><p><a href="https://openai.com/blog/gpt-3-edit-insert">GPT-Edit</a> is one of the newest models from OpenAI. Currently in <em>beta </em>release, GPT-Edit is a powerful tool for editing text, fixing spelling errors and grammatical mistakes, and reformatting text. The model takes to-be-edited text and an instruction prompt as inputs and outputs the edited text body.</p><p>Example instructions for GPT-Edit include:</p><ul><li><em>“Fix the spelling mistakes”</em></li><li><em>“Format like a letter”</em></li><li><em>“Change text into first person”</em></li></ul><p>You can learn more about the GPT-Edit API <a href="https://platform.openai.com/docs/api-reference/edits/create">here</a>, or you can test out GPT-Edit in the OpenAI Playground <a href="https://platform.openai.com/playground?mode=edit">here</a>.</p><h3>The challenge with optical character recognition models</h3><p>Optical character recognition (OCR) models are a model class that predicts characters, i.e. letters and numbers, from images. If you are a data scientist or an ML engineer, chances are one of the first deep learning models you built was an OCR model using the <a href="https://en.wikipedia.org/wiki/MNIST_database">MNIST</a> handwritten digits dataset. It’s a favorite prompt for introductory courses and tutorials. They are widely used in applications ranging from data entry automation, verifying and processing documents, and recognition of labels/number plates.</p><p>We’ll show an example of OCR used to convert images of handwritten notes to machine-readable text and highlight areas for improvement. While the MNIST dataset is a fairly simple and highly curated setting for developing toy models, real world applications tend to be more difficult. For example, the position of characters provides important context for how the machine text should be organized. Many commercial applications exist for handwritten text transformation, including Microsoft OneNote, PDFElement, and Evernote. Applications for the iPhone and iPad that convert handwriting to text include GoodNotes 5, Notability, Notes Plus, Pen to Print, Text Scanner and WritePad for iPad in addition to the native iOS Notes application. For Android users handwriting conversion apps include Adobe Scan, CamScanner, Google Keep, Readiris and Smart Lens. While these technologies are widely available and commonly used, we have found that the output text is often poorly formatted and riddled with grammatical errors, adding friction to note-taking and review.</p><p>In the figure below, we show an example handwritten note on the left. On the right, we show the transcription from the native Notes app on iOS. Observe the grammar and formatting problems in the transcription.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ylRW1ZLcg0K-5Zk560bpcA.png" /><figcaption><em>(Left) Handwritten note; (Right) Corresponding machine-readable text</em></figcaption></figure><h3>Using GPT-Edit to improve the quality of transcribed text</h3><p>We hypothesized that results from OCR models could be improved using GPT-Edit. To test this hypothesis, we fed the transcribed text into GPT-Edit <em>(text-davinci-edit-001</em>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a2ab337361ac5aab204c3995940e67a/href">https://medium.com/media/3a2ab337361ac5aab204c3995940e67a/href</a></iframe><p>We added line breaks to the prompt to tell GPT-Edit where the line breaks occurred in the output of the OCR model (note: these are not the line breaks seen in our original handwritten text).</p><p>Here is the edited response from GPT-Edit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_cS4JNY-guM2inIM" /><figcaption><em>Raw output from GPT-Edit model</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*SJvbER39ENcNqvoRhOT0cA.png" /><figcaption>Markdown output from GPT-Edit model</figcaption></figure><p>The result from GPT-Edit looks much more similar to the original handwritten note than the output from the OCR model alone. The grammar and spelling is improved; line breaks are true to the original text; and the Markdown formatting makes the note more readable. This note could be more easily shared and understood than the output from the OCR model alone.</p><h3>Challenges with using GPT-Edit</h3><p>The results from GPT-Edit are highly stochastic. We have found that the model requires prompt engineering and experimentation to produce more repeatable results. Experimenting with the <em>temperatur</em>e and <em>top_p</em> GPT variables are also ways to control randomness and diversity, respectively. You can add these to your prompt to the API like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ab859a480814c7e6b0771f81726a8fb/href">https://medium.com/media/0ab859a480814c7e6b0771f81726a8fb/href</a></iframe><p>Fine tuning the model is potentially another way to generate more repeatable results for particular use cases. For example, the model could be tuned for a specific type of formatting like Markdown or formatting notes to your personalized note-taking style. While fine tuning is not currently supported by the GPT-Edit API like it is for the GPT base models, we are eagerly anticipating the release of fine-tuning for GPT-Edit.</p><h3>One step further — note summarization using GPT-3</h3><p>Can we use the output of OCR + GPT-Edit as the input in GPT-3 (<em>text-davinci-003</em>) in order to summarize our note? Let’s try it!</p><p><strong>Summary from GPT-3 using GPT-Edit output</strong> as the input along with the prompt “summarize the following note”:</p><blockquote>At the meeting on 1/30/23, Bob proposed a 3 point plan to build cool stuff, work with awesome people, and eat lots of pizza. Bob was assigned tasks to write a blog, edit a blog, and order a pizza. His favorite pizza toppings are pineapple, ham, and mushrooms.</blockquote><h3>Conclusions</h3><p>We hypothesized that we could use the brand new GPT-Edit model from Open AI to improve output from OCR models on the task of transcribing handwritten notes to text. In this blog, we demonstrated this, using a commonly used OCR-based handwriting-to-text application and the GPT-Edit model to automatically convert a handwritten note to a useable, reformatted note that can be shared easily with others. Additionally, we were able to summarize the note with GPT-3, taking “scribbles” to summaries!</p><h3>What use case do you have for GPT-Edit?</h3><p>We want to hear from you! How do you plan to use GPT-Edit or other large language models? Leave us a comment or send us an email at <a href="/service/mailto:info@edgeanalytics.io">info@edgeanalytics.io</a>. While you’re here, check out our blog series on Getting the Most Out of GPT-3-based Text Classifiers: <a href="https://medium.com/edge-analytics/getting-the-most-out-of-gpt-3-based-text-classifiers-part-one-797460a5556e">Part 1</a>, <a href="https://medium.com/edge-analytics/getting-the-most-out-of-gpt-3-based-text-classifiers-part-two-a869313b4206">Part 2</a>, <a href="https://medium.com/edge-analytics/getting-the-most-out-of-gpt-3-based-text-classifiers-part-three-77305628f472">Part 3</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3e7kXY7f7t5GtWvo5nasg.png" /></figure><h3>GPT-3 at Edge Analytics</h3><p><a href="https://edgeanalytics.io/">Edge Analytics</a> has helped multiple companies build solutions that leverage GPT-3. More broadly, we specialize in data science, machine learning, and algorithm development both on the edge and in the cloud. We provide end-to-end support throughout a product’s lifecycle, from quick exploratory prototypes to production-level AI/ML algorithms. We partner with our clients, who range from Fortune 500 companies to innovative startups, to turn their ideas into reality. Have a hard problem in mind? Get in touch at <a href="/service/mailto:info@edgeanalytics.io">info@edgeanalytics.io</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1940bbad8f9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edge-analytics/from-scribbles-to-summaries-enhancing-ocr-models-with-gpt-edit-for-handwritten-notes-e1940bbad8f9">From Scribbles to Summaries: Enhancing OCR Models with GPT-Edit for Handwritten Notes</a> was originally published in <a href="https://medium.com/edge-analytics">Edge Analytics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>