<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Patrick Ryan on Medium]]></title>
        <description><![CDATA[Stories by Patrick Ryan on Medium]]></description>
        <link>https://medium.com/@patrick-ryan?source=rss-517be808296c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*ZbT3MuY6NEJXL0QGSjcVqg.png</url>
            <title>Stories by Patrick Ryan on Medium</title>
            <link>https://medium.com/@patrick-ryan?source=rss-517be808296c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:58:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@patrick-ryan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[AWS Lambda access to RDS MySql Architecture Pattern]]></title>
            <link>https://awstip.com/aws-lambda-access-to-rds-mysql-architecture-pattern-4e41e4ff4331?source=rss-517be808296c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e41e4ff4331</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[aws-networking]]></category>
            <dc:creator><![CDATA[Patrick Ryan]]></dc:creator>
            <pubDate>Sat, 12 Mar 2022 18:55:45 GMT</pubDate>
            <atom:updated>2022-03-26T00:10:16.533Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*qAPiyFZrkO4RgwF4U3LwxQ.png" /><figcaption>What seems like such a simple pattern….</figcaption></figure><p>You might be think this is just another re-hash of the ‘Lambda to RDS’ topic. However, I am going to cover topics that I have not seen all in one place. Specifically:</p><ul><li>Implementation entirely in Python.</li><li>CDK to build out the entire network architecture and services</li><li>Lock up RDS into an Isolated Subnet</li><li>Create a Bastion EC2 to tunnel database connections</li><li>Place Lambda into a Private Subnet</li><li>Use SecretsManager to manage Database Credentials.</li><li>Use Lambda environment variables and not hardcoded database strings</li></ul><p>Most examples try to simplify the architecture by taking some shortcuts, but this glosses over some important security concerns.</p><p>This article assumes you have some experience with CDK and therefore have Docker, aws cli and the aws cdk cli installed.</p><p>All of the source code for this article is on my <a href="https://github.com/youngsoul/lambda-rds-example.git">Github Repo</a>.</p><h3>Application Overview</h3><p>What are we trying to accomplish?</p><p>Create an Http Api endpoint that will read a MySql Database using a Lambda.</p><p>It sure seems simple enough, but there really is a lot going on to make this happen.</p><p>To create the tables, and insert records, we are going to use JetBrains DataGrip to manage the database DDL and DML. We are not going to expose the database with a public IP, so I will show you how to create a tunnel for the database traffic.</p><h3>AWS Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*oZ17kgKtbL8uC9B7UJe5vw.png" /><figcaption>Lambda to RDS Architecture</figcaption></figure><p>The picture above gives the high level overview of the architecture we will be putting together. Note it does not show all of the pieces such as route tables, but the CDK also does not require us to deal directly with them either. We will however show those in detail later in the article.</p><h3>Architecture Overview</h3><p>This section will cover the major AWS architectural elements.</p><h4>Lambda and the VPC</h4><p>If you are going to make direct connections to an RDS database from a Lambda, then your Lambda must be in a VPC. If you put your Lambda in a VPC, then you really need to place it in a non-Public subnet.</p><p>This seems like a simple enough restriction, until you realize all of AWS Networking that will be required.</p><p><em>NOTE: there is the Data Api for Aurora Serverless and if you use this, then you DO NOT need to place your Lambda in a VPC.</em></p><h4>Subnets</h4><p>We will need to create a Public, Private and an Isolated Subnet.</p><p>The <strong>Public Subnet</strong> will contain our NAT Gateway and the EC2 instance that will act as the bastion box to tunnel our database connection through.</p><p>The <strong>Private Subnet</strong> will contain the Lambda function. We are using a Private Subnet because we want the Lambda to have access to the internet to get to other services like the SecretsManager. We do have an option here, where we could put the Lambda in the Isolated Subnet, and then add a VPC endpoint to get to the SecretsManager. I chose the former, on the change the Lambda function needed access to the internet for other activity.</p><p>The <strong>Isolated Subnet</strong> will contain the RDS Proxy and the RDS MySQL database. The reason to use an Isolated Subnet is because no traffic should directly access the database, and the database should have no access to the outside world. You want to lock down your database.</p><h4>Security Groups</h4><p>Security groups are created for each of the elements in the subnets. The security groups are configured to allow inbound traffic to only those other security groups or outside computers that require access. For example, for the RDS Security groups, the inbound rules will allow for tcp traffic on port 3306 from the bastion security group and the lambda security group. Anything else will not be allowed to communicate with the MySQL database.</p><h4>Route Tables</h4><p>When we look at the CDK you will see that we never work with route tables directly. The CDK framework, knows to create and update route tables for each subnet as needed. We will look at the route tables later in this article.</p><h4>RDS</h4><p>We will use the RDS Proxy and make sure the Lambda function invocations go through the proxy. The proxy will help with database connection management so a burst of traffic wont exhaust the number of connections to the database.</p><h4>IAM</h4><p>There are a number of IAM roles and policies that have to be created. One of the many benefits of using CDK is that the CDK framework will recognize when an IAM roles needs to be created, or an existing role needs to be updated. For example, we never create the Lambda IAM role directly, but CDK knows to do this and add the right policies.</p><h3>Python CDK</h3><p>In this section we will look at the CDK used to create the network architecture and deploy the Lambda function.</p><h4>VPC</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37ccff50afb392c8591e608ad1f5569e/href">https://medium.com/media/37ccff50afb392c8591e608ad1f5569e/href</a></iframe><p>The above CDK will create a new VPC and the 3 subnets. We need to specify the <strong>max_azs</strong>, because the RDS setup requires at least 2. The <strong>nat_gateway</strong> is set to 1, because we need a nat_gateway for the Lambda function to get to other AWS services. This value is usually set the same as max_azs, but to keep it simple and costs down one is sufficient.</p><p>After the above CDK executes, the AWS network architecture looks like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*348XBnwqN2pvRoM_0wZoLQ.png" /><figcaption>VPC after CDK executes</figcaption></figure><p>Because we have 2 availability zones, and we specified 3 subnets, in total 6 subnets are created and each subnet has its own route table.</p><h4>Public Subnet Route Table</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*-GKCsDf-gmJ-FSI25ko6nQ.png" /><figcaption>Public Subnet Route Table</figcaption></figure><p>The Public subnet has a route that allows for local VPC traffic. However, any other traffic is routed to the internet gateway. This allows elements in the public subnet to access the internet.</p><h4>Private Subnet Route Table</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*wLA-v1hD70zUAQ_781kYtQ.png" /><figcaption>Private Subnet Route Table</figcaption></figure><p>The Private subnet has a route table that allows for local VPC traffic. It also has an entry that states for any other traffic, route that traffic to the NAT gateway. The NAT Gateway will forward traffic to the internet gateway. This allows elements in the private subnet to communicate to the internet, but will do so by having the IP address of those elements hidden behind the NAT gateway.</p><h4>Isolated Subnet Route Table</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*Qu3dsoU3FOHSifTE--feVA.png" /><figcaption>Isolated Subnet Route Table</figcaption></figure><p>The Isolated subnet has a route table that only allows for local VPC traffic. Any other traffic destined anywhere else is blocked.</p><h4>Security Groups</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f39b669d35dfb95b8494b49fe0b40772/href">https://medium.com/media/f39b669d35dfb95b8494b49fe0b40772/href</a></iframe><p>The route tables describe how traffic is routed in a subnet, the security groups are associated with network interfaces (NI) (e.g. EC2 instance, or Lambdas ) and can be thought of as stateful firewalls for the individual network interfaces within a subnet.</p><p>We create a Security Group (SG) for the Lambda function, the EC2 (bastion) and the RDS database. The only difference between the Lambda SG and the bastion SG is that the bastion SG allows for inbound SSH traffic from a very specific IP address. This locks down the SSH port to any network interface ( ie. EC2 ), to my IP address. The security group for the Lambda allows for no inbound traffic.</p><p>The DB connection SG, is setup to allow any network interface (NI) from the Lambda SG, or the EC2 bastion SG, or anything in the DB SG to communicate to the MySQL database port of 3306. By doing this we very specifically define from where database traffic can come from in the VPC. Notice also we specify <strong>allow_all_outbound=False</strong> for the DB connection SG. There is no outbound traffic from the database elements.</p><h4>Secrets Manager for Database Credentials</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b659bcb4dfa1e11638eaf5ef18922b8a/href">https://medium.com/media/b659bcb4dfa1e11638eaf5ef18922b8a/href</a></iframe><p>Use the SecretsManager to store a password secret. This will keep the plaintext representation of the password hidden and only those individuals and services granted IAM permissions will be able to see the password. It is never recommend to store the sensitive data in environment variables or local config files or hardcoded into the source code. Obvious? sure, but its done all of the time.</p><h4>Create RDS MySQL Database</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69f33b106614c7f0760b36af5e749769/href">https://medium.com/media/69f33b106614c7f0760b36af5e749769/href</a></iframe><p>The above CDK will create a MySQL database instance. Note on Line 10, we are creating the RDS instance in the ISOLATED subnet.</p><ul><li>Line 5 — We provide a reference to the secret we created above. No where in the CDK is the password for the database ever exposed.</li><li>Line 10 — we are creating the RDS instance in the ISOLATED subnet.</li><li>Line 14 — for the purpose of this article, the removal policy is to destroy the database when we destroy the stack.</li><li>Line 16 — set the security group to the db_connection_sg, which will only allow certain NIs to access the database port.</li><li>Line 21 — add a RDS Proxy to the MySQL database to manage connections. This will</li></ul><h3>EC2 Bastion Box</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa0a46ec01a35ccb6983e732f2ee3e78/href">https://medium.com/media/aa0a46ec01a35ccb6983e732f2ee3e78/href</a></iframe><p>The bastion box is the only publicly accessible machine and will act as the machine that will tunnel database connections from outside the AWS cloud. Many times, we would like to use database IDEs to interact with out database and most examples expose a public IP, and then tell you never to do that. It is easy, but it is also insecure. So I suggest you never you do that. Later in this article I would show you how to setup DataGrip to SSH tunnel through the bastion box, to the database.</p><ul><li>Line 10: you must have already created a keypair. This parameter is where you specify the name of the keypair.</li><li>Line 11–13: Specify that the EC2 box should go into the Public subnet.</li><li>Line 14: Specify that we should use the bastion_sg security group. This security group allows for incoming SSH traffic from a very specific IP address. It is recommend that you do not open this up to all IP addresses.</li></ul><h4>Lambda Function</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83b6bf9b1bf9c68cf80886492f8e1649/href">https://medium.com/media/83b6bf9b1bf9c68cf80886492f8e1649/href</a></iframe><p>Create a Lambda function that will make queries against the RDS MySQL database.</p><ul><li>Lines 7–9: Specify that the Lambda function should go to the Private subnet. This private subnet allows no traffic in, however traffic can get out because of the route table which routes traffic from the NAT to the IGW. In addition, the security group is setup to allow outbound traffic. If you do not place the Lambda into a Subnet with access to the internet, it will not be able to connect to the SecretsManager to get the database credentials. The other way to handle this is to setup a VPC Endpoint to the SecretsManager.</li><li>Lines 10–12: Set the security group for the Lambda. Recall that this security was granted inbound TCP on port 3306 by the db_connection_sg. This is required for the Lambda to communicate with the database.</li><li>Line 14–19: The environment variables needed to configure the Lambda to know about the database. Most examples show these values hardcoded into the Lambda, but best practice is to externalize them in environment variables even place them in SSM. Note that we are sending the proxy.endpoint for the RDS_HOST and NOT the actual RDS endpoint. We are also passing the name of the secret. This will be used to get the database credentials when establishing a connection. The Lambda is never configured with the database username nor the database password.</li></ul><p>For the actual Lambda code, see the <a href="https://github.com/youngsoul/lambda-rds-example.git">Github repo.</a> Look for <strong>rds_lambda/rds_lambda.py.</strong></p><h4>API Gateway, HttpApi</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ea52a0e91a62e631e7e674224372e8d/href">https://medium.com/media/4ea52a0e91a62e631e7e674224372e8d/href</a></iframe><p>The last element is the HttpApi definition. For this we are using CDKV2 constructs.</p><p>Please notice we have not secured the endpoint.</p><h4>IAM Permissions</h4><p>Notice so far we have not talked about IAM permissions at all.</p><p>This is because CDK takes care of most of the IAM roles/policies in this example. There is one that has to be setup explicitly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9113bf3fda6942a839240a3e093391b6/href">https://medium.com/media/9113bf3fda6942a839240a3e093391b6/href</a></iframe><p>This is handled in CDK with a method call on the secrets reference from the CDK. This will add read permissions to the Lambda role. We dont have to do this explicity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vz998ULEeT8s1wV15vULJA.png" /><figcaption>IAM Permissions created by CDK for Lambda</figcaption></figure><p>In addition, CDK will add the VPC Lambda execution role and the standard Lambda Execution role to the newly created Role for the Lambda. All of this is handled by CDK. It is very handy that it does, but if you don’t know that, it appears very magical. If something appears magical, it means we don’t understand it yet.</p><h3>Deploy the CDK Stack</h3><p>execute:</p><pre>cdk deploy --profile &lt;profilename&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yPYrA_fsLVt3a9KDeuXZ0Q.png" /><figcaption>Output from CDK deploy</figcaption></figure><p>This output most of the information you will need.</p><h3>Setup JetBrains DataGrip</h3><p>These steps should be similar to any database IDE that supports SSH tunneling.</p><p><strong>Create new MySQL DataSource</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*P0tJPZTur4Ee52oHBCUYqw.png" /></figure><p><strong>Select ‘SSH/SSL’ tab</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*SSzb3eGIdg3cAhMPDb1r_w.png" /></figure><p><strong>Select the ‘Use SSH tunnel’</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*6J875QADP0H3Ej3Dqp6aEw.png" /></figure><p><strong>Add SSH Configuration</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*KiuBzlDmRRuWE4Y9wmalqQ.png" /></figure><p>Use the IP address from the CDK Output LambdaRdsExampleStack.PublicIp</p><p>Make sure to select the pem file that you specified in the CDK stack, and use ec2-user.</p><p><strong>Test SSH Connection</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*PwmIV7O2JQ1megL2HN24bg.png" /></figure><p><strong>General Tab — complete DB form</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*OolU_YvAAJGO_exBQuLCIA.png" /></figure><p>EDIT 3/25/2022: I wanted to clarify that the ‘Host’, should be the Proxy host name which is shown as proxyDbEndpoint from the CDK output.</p><p>To complete this form, you will need the database user and password. The username was specified in the CDK so that should be known. The password is stored in the secret manager.</p><p>It is assumed you have access to the AWS console with enough permission to access the password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2NqwMmzzkM1YoYe7ePU8YQ.png" /></figure><p><strong>Test Connection</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*UCHeGNay8ZvA9I55f41lVA.png" /></figure><p><strong>Open console window</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DbOige0eKqLMSOpwXlGTfg.png" /></figure><p><strong>Test HttpApi GET</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WG-_HQASyfnpnSMxaSRliA.png" /></figure><h3>A Gotcha</h3><p>I had one gotcha that really stumped me for a little while. I received the following error when trying to deploy the stack:</p><pre>Resource handler returned message: &quot;RDS is not authorized to assume service-linked <br>        role arn:aws:iam::488518594239:role/aws-service-role/rds.amazonaws.com/AWSServiceRoleForRDS</pre><p>I tred to find the <strong>AWSServiceRoleForRDS </strong>role but it was not in my AWS Account.</p><p>I had to add the following policy to my user:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor0&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;iam:GetServiceLinkedRoleDeletionStatus&quot;,<br>                &quot;iam:CreateServiceLinkedRole&quot;,<br>                &quot;iam:UpdateRoleDescription&quot;,<br>                &quot;iam:DeleteServiceLinkedRole&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:iam::*:role/aws-service-role/rds.amazonaws.com/AWSServiceRoleForRDS&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringLike&quot;: {<br>                    &quot;iam:AWSServiceName&quot;: &quot;rds.amazonaws.com&quot;<br>                }<br>            }<br>        }<br>    ]<br>}</pre><p>After doing this and redeploying, the <strong>AWSServiceRoleForRDS </strong>did appear, and I was able to deploy the stack.</p><h3>Wrap up</h3><p>When I started with this example project, I thought it would be more straight forward than it was. As soon as you try to access RDS from your Lambda, a much deeper understanding of fundamental AWS networking will be required.</p><p>If you made it this far, I hope you found something of interest and new to you in this article. You can find the source code for this article on my <a href="https://github.com/youngsoul/lambda-rds-example.git">Github Rep</a>o.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e41e4ff4331" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/aws-lambda-access-to-rds-mysql-architecture-pattern-4e41e4ff4331">AWS Lambda access to RDS MySql Architecture Pattern</a> was originally published in <a href="https://awstip.com">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Lambda/EFS to run Scikit-Learn Machine Learning models]]></title>
            <link>https://awstip.com/aws-lambda-efs-to-run-scikit-learn-machine-learning-models-d6cbc3b950a3?source=rss-517be808296c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6cbc3b950a3</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Patrick Ryan]]></dc:creator>
            <pubDate>Mon, 07 Mar 2022 21:12:01 GMT</pubDate>
            <atom:updated>2022-03-10T07:11:08.587Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2jTs3waTmeSCpJsIKAOPHw.png" /><figcaption>Potpourri of technology</figcaption></figure><p>Do you need to run a <a href="https://scikit-learn.org/stable/">Scikit-Learn</a> machine learning model behind an HTTP endpoint on AWS? Are you considering using an AWS Lambda, but not sure how to package everything?</p><p>Using EFS ( Elastic File System ) provides a compelling option.</p><p>In this article, I will show you how to do just that using the AWS Python CDK.</p><h3>Where is the code?</h3><p>My github repo for this article can be found <a href="https://github.com/youngsoul/lambda-efs-machinelearning.git">here</a>.</p><h3>Architecture</h3><p>The diagram below shows the AWS networking architecture.</p><p>To connect a Lambda to EFS, you must place the Lambda in a VPC. For this article I am not going to use the default VPC but instead create a new VPC.</p><p>I decided to create a single subnet to put all of the other services into. If your Lambda needed access to the internet, then you would need to put the Lambda in a private subnet, and NAT the traffic out.</p><p>The EC2 instance is in a security group that allows access from a specific IP address, and the EC2 instance is used to initialize the Python execution environment for the Lambda and used to get the model loaded to the mounted file system. The EFS Access Security Group is setup to allow access from the Bastion Security Group.</p><p>The Lambda and EFS are in their own security group to allow the Lambda to access the NFS mounted EFS volume.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nek8fzt1bZKcfn1kz1gjZw.png" /><figcaption>Lambda/EFS ML architecture</figcaption></figure><h3>Which Python Version?</h3><p>This was a little trickier than anticipated. The EC2 instance has Python 3.7.x installed. I initially setup my Lambda to use Python 3.9.x. However, if you install packages like ‘numpy’ using Python 3.7, you cannot use a Python 3.9 Lambda to load the numpy packages. The bottom line is the Lambda Python version and the EC2 Python version have to match so all installed packages match. Instead of upgrading Python on EC2, I just specified Python 3.7 for the Lambda.</p><h3>What Machine Learning Model?</h3><p>The machine learning model I am going to use is from the <a href="https://www.kaggle.com/fedesoriano/heart-failure-prediction">Kaggle DataSet for Heart Failure</a>.</p><p>My Github repo, that I used to build and train the model, can be found <a href="https://github.com/youngsoul/kaggle-heart-failure.git">here</a>. This article is not going to cover the model development, but instead just use the resulting trained model.</p><h3>CDK build out</h3><p>This section will cover the CDK elements that were used to build out the above architecture. The CDK shown here is tightened, comment-less, version to talk through the salient parts. See the github repo for the complete treatment.</p><p>To see the full stack implementation see the file: api_lambda_example/api_lambda_example_stack.py</p><h4>VPC</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3d3226708ff90e0eac5957f2fd62ad5/href">https://medium.com/media/c3d3226708ff90e0eac5957f2fd62ad5/href</a></iframe><p>Create a new VPC, and in this case include just a Public subnet. Note nat_gateways is None ( which is the default ). Do not provide a number here if you do not need it, because there is a cost associated with nat_gateways that can add up.</p><h4>Security Groups</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45dd1274be65bb9cbd2c3a9527b4be67/href">https://medium.com/media/45dd1274be65bb9cbd2c3a9527b4be67/href</a></iframe><p>Create the two security groups. The bastion sets up an inbound rule to allow SSH traffic from a specific IP address, instead of just being wide open.</p><p>The efs_access_sg adds an inbound rule that says, anything in that security group can access port 2049 which is the NFS port for the file system.</p><p>Notice that we have not provided an inbound rule allowing the the bastion_sg to send traffic on 2049. This is because we will use a CDK function on the filesystem to grant access to the (yet to be created) EC2 instance.</p><h3>EC2 Instance</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a66731796717a24fb71ad8b94d281200/href">https://medium.com/media/a66731796717a24fb71ad8b94d281200/href</a></iframe><p>Create the EC2 instance which we will use to setup the EFS environment for the Lambda. Note that it assumes you have a created a key_name prior. This CDK will associate the EC2 instance with the new VPC, in the public subnet, using the bastion security group which grants SSH access from a particular IP address.</p><h3>EFS</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/736a07c1c50a0b998f273e9596e140bf/href">https://medium.com/media/736a07c1c50a0b998f273e9596e140bf/href</a></iframe><p>Create the EFS and the AccessPoint. When created the FileSystem we specify the efs_access_sg.</p><p>When creating the access point, note we use user_id: 1000. This happens to be the ec2-user so when we create directories in EC2 and when the access point creates them we have access to them. You can, if desired pick a different uid/gid and create the user on the EC2 instance.</p><p>Last, on <strong>line 12</strong>, this is where we allow the bastion EC2 instance to access the EFS. We could have used ingress security group rules, or use this function.</p><h3>Lambda Function</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25e84d9c84bcc024682facaacffd0017/href">https://medium.com/media/25e84d9c84bcc024682facaacffd0017/href</a></iframe><p>Create the Lambda function, using the v2 CDK API.</p><ul><li><strong>Line 5</strong>: we specify Python 3.7 because that is what the EC2 instance uses.</li><li><strong>Line 6</strong>: associate the Lambda with the new VPC</li><li><strong>Lines 7–9</strong>: Add the efs access security group so the Lambda can access the EFS.</li><li><strong>Line 11</strong>: This flag is only needed to let CDK know that, yes — we know we dont typically put the Lambda in a public subnet.</li><li><strong>Line 12</strong>: Provide a reference to the FileSystem access and provide the path used in the Lambda function to the access point. Within the Lambda, ‘/mnt/model’, is a mapping to ‘/export/lambda’.</li><li><strong>Lines 13–15</strong>: Setup an environment variable for the Lambda, to add ‘/mnt/model/venv’ which is where we will install all of the necessary packages. This is what makes all of the Python magic happen when installing dependencies.</li></ul><p><em>UPDATED 3/8/2022: Added information on the Lambda IAM permissions</em></p><p>It should be noted that using CDK will automatically create the necessary IAM permission for the Lambda to execute. Specifically an IAM role is created with the following:</p><ul><li>AWSLambdaBasicExecutionRole</li><li>AWSLambdaVPCAccessExecutionRole</li><li>Custom Policy with elasticefilesystem:ClientMount and elasticfilesystem:ClientWrite</li></ul><p>CDK will also create a Resource-based policy to allow the HttpApi to invoke the Lambda function.</p><p>All of this IAM work is recognized as needed by the CDK and is automatically handled for you.</p><h3>Http Api</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4986c517b35c988269b6f1b7909f441a/href">https://medium.com/media/4986c517b35c988269b6f1b7909f441a/href</a></iframe><p>The last construct to create the HttpApi setting up the Lambda integration. Again, this uses the CDK V2 constructs which could change in the future.</p><h3>Use EC2 instance to initialize the EFS</h3><p>Once you deploy the CDK Stack, the next step is to initialize the EFS. This means we have to:</p><ul><li>Create a venv directory in the shared access point</li><li>Install the Python dependencies into the venv directory</li><li>Update the model .pkl file. This file will be loaded by the Lambda.</li></ul><p>Log into the EC2 instance as the ec2-user.</p><p>Execute the following commands:</p><pre>sudo mkdir /mnt/efs<br>sudo yum install -y amazon-efs-utils<br>sudo mount -t efs &lt;fs-ID&gt;:/ /mnt/efs<br>sudo mkdir /mnt/efs/export/lambda/venv<br>sudo pip3 install --target /mnt/efs/export/lambda/venv pandas<br>sudo pip3 install --target /mnt/efs/export/lambda/venv scikit-learn</pre><p>NOTE: to see export/lambda under the /mnt/efs mount directory, we need to hit the Lambda once with a GET or test. (I tried to get this access point to show via CDK but could not figure it out. If anyone knows how, please leave a comment ).</p><p>These commands will mount the file system, and install pandas and scikit-learn to the venv directory. The venv directory is where the Lambda environment assumes packages will be installed.</p><p>I would normally setup a UserData script to perform the commands on deployment but I wanted to run through each command so I could make sure I knew what was going on.</p><h3>Copy model file to EFS</h3><p>The next step is to copy the trained model .pkl file to EFS so it is available to the Lambda. This is just a scp and it looks like:</p><pre>scp -i ~/.ssh/pryan-aws.pem /Users/patrickryan/Development/aws/cdk-sandbox/api-lambda-example/ml-model/heart_model.pkl ec2-user@34.200.255.190:/mnt/efs/export/lambda</pre><p>Obviously changing the IP address and location to the actual .pkl file.</p><h3>Lambda Function Implementation</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35167d9796a017c3163a7ab3763c00ac/href">https://medium.com/media/35167d9796a017c3163a7ab3763c00ac/href</a></iframe><p>Because of the way the model was created, it expects a dataframe with columns so it run through the pipeline of column transformers.</p><p>The model is loaded with the following line:</p><pre>heart_model = joblib.load(f&quot;{mount_dir}/heart_model.pkl&quot;)</pre><p>If we don’t have a reference to the model, load the model from the mount point which in the lamba is defined as “/mnt/model”, and that maps to “/export/lambda” which was used with the EC2 to upload the .pkl file.</p><p>Once we have the model loaded we can create a dataframe and predict using the model.</p><p>With the HttpApi endpoint created, I can issue a POST request like:</p><pre>POST {{host}}<br><em>Content-Type</em>: application/json<br><br>{<br>  &quot;Age&quot;: 54,<br> &quot;Sex&quot;: &quot;M&quot;,<br> &quot;ChestPainType&quot;: &quot;NAP&quot;,<br> &quot;RestingBP&quot;: 150,<br> &quot;Cholesterol&quot;: 195,<br> &quot;FastingBS&quot;: 0,<br>  &quot;RestingECG&quot;: &quot;Normal&quot;,<br> &quot;MaxHR&quot;: 122,<br> &quot;ExerciseAngina&quot;:  &quot;N&quot;,<br> &quot;Oldpeak&quot;:  0.0,<br> &quot;ST_Slope&quot;: &quot;Up&quot;<br>}</pre><p>with a result like:</p><pre>{&quot;message&quot;: &quot;heart failure prediction&quot;, &quot;prediction&quot;: &quot;[0]&quot;}</pre><h3>Finally… the end…</h3><p>That was a lot, but I hope you found it helpful. None of this is ever straightforward and I found twists and turns in areas like the security group setup, different Python versions and setting up the EC2 instance to access the EFS and mount the right directories.</p><p>I am sure my future self will thank me for writing this down some day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6cbc3b950a3" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/aws-lambda-efs-to-run-scikit-learn-machine-learning-models-d6cbc3b950a3">AWS Lambda/EFS to run Scikit-Learn Machine Learning models</a> was originally published in <a href="https://awstip.com">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS CDKv2 Python Lambda with dependencies — the quick read]]></title>
            <link>https://patrick-ryan.medium.com/aws-cdkv2-python-lambda-with-dependencies-the-quick-read-ffe87e555a18?source=rss-517be808296c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffe87e555a18</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <dc:creator><![CDATA[Patrick Ryan]]></dc:creator>
            <pubDate>Fri, 04 Mar 2022 21:01:50 GMT</pubDate>
            <atom:updated>2022-03-04T21:01:50.712Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS CDKv2 Python Lambda with dependencies — the quick read</h3><p>Around Nov of 2021, AWS released the experimental constructs into the CDKv2.</p><p>You can get these experimental constructs by installing the ‘xxx-alpha’ package. Keep in mind that this is the bleeding edge and the api could change.</p><p>Goal: Create a Python Lambda function with dependencies, and front it with an HttpApi.</p><p>“Back in my day….” packaging a Python Lambda function with dependencies and multiple python file dependencies was… a bit cumbersome.</p><p>The new constructs make this much easier.</p><p>Source code can be found on my <a href="https://github.com/youngsoul/api-lambda-example.git">Github Repo</a>.</p><p>I am assuming you have the following already installed:</p><ul><li>Docker</li><li>AWS CLI</li><li>AWS CDK CLI</li></ul><h3>CDK Setup Info</h3><p>Skip this if you are familiar with CDK.</p><pre>mkdir api-lambda-example<br>cd api-lambda-example<br>cdk init app --language python<br>source .venv/bin/activate<br>pip install -r requirements.txt</pre><p>if you have never bootstrapped your AWS account to run the cdk you will needed to run:</p><pre>cdk bootstrap --profile &lt;name of profile to use if not default&gt;</pre><h3>Add CDK Alpha packages</h3><p>Add the following to the requirements.txt and pip install again. We need these to create the PythonFunction and HttpApi constructs and integrate the two.</p><pre>aws-cdk.aws-apigatewayv2-alpha<br>aws-cdk.aws-apigatewayv2-integrations-alpha<br>aws-cdk.aws-lambda-python-alpha</pre><h3>Create a folder for the Lambda function</h3><p>I created a folder called lambda1 and in that folder I added:</p><ul><li>hello_world.py — this is the typical Python Lambda function. This Lambda function has a dependency on ‘requests’ and another Python script in the same folder</li><li>requirements.txt — this file specifies the packages required for the Lambda function. You can specify other Python package dependency files, but I went the stand by one.</li><li>utils.py — just a dependent Python script to make sure all of the files where built together.</li></ul><h3>CDK Stack</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db5eed1e541f4fb92d36468fcd72e820/href">https://medium.com/media/db5eed1e541f4fb92d36468fcd72e820/href</a></iframe><p><strong>Line 19</strong>. This is all you need to do to build your Python Lambda function. The CDK will package up all of the files in the ‘entry’ directory and look for the requirements.txt and build a Python 3.9 Lambda function distribution.</p><p><strong>Line 2</strong>7. This is all you need to do to specify the HttpApi and integrate with the Lambda function.</p><p><strong>Line 31</strong>. This will print the url you need to hit to execute your lambda function.</p><p>The rest of code in the repo was generated by the cdk init command.</p><h3>Deploy/Destroy</h3><p>Deploy the stack:</p><pre>cdk deploy --profile &lt;your profile if not default</pre><p>Hit the url end point and see the Lambda output.</p><p>Destroy the stack</p><pre>cdk destroy --profile &lt;your profile if not default&gt;</pre><h3>The End</h3><p>I hope that was helpful… now I am off to build something bigger and better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffe87e555a18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Honey, there are deer at the bird feeder again! ( Keras, OAK-1 and a RaspberryPi to detect deer)]]></title>
            <link>https://patrick-ryan.medium.com/honey-there-are-deer-at-the-bird-feeder-again-keras-oak-1-and-a-raspberrypi-to-detect-deer-11a9bd56237?source=rss-517be808296c------2</link>
            <guid isPermaLink="false">https://medium.com/p/11a9bd56237</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[opencv]]></category>
            <dc:creator><![CDATA[Patrick Ryan]]></dc:creator>
            <pubDate>Wed, 02 Feb 2022 01:23:35 GMT</pubDate>
            <atom:updated>2022-02-02T01:23:35.628Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*eno6l80ECU8TufkgKAqevw.gif" /><figcaption>OAK-1 running on RPI using a Keras model to detect presence of deer</figcaption></figure><p>( Please take no offense to the use of <a href="https://www.pyimagesearch.com/raspberry-pi-for-computer-vision/">PyImageSearch Raspberry Pi book</a>s to elevate the camera. These books are handy on my bookshelf as I have been reading through them and I highly recommend them. These books are a big factor in my understanding of how to apply computer vision using the Raspberry Pi. )</p><p>If you have been following my posts on using the OpenCV AI Kit (OAK-1) camera, I am going to build upon those articles and create a deer detector to alert me when the deer have eaten all of the food from the bird feeder so we can feed the birds.</p><p>Previous articles:</p><ul><li><a href="https://patrick-ryan.medium.com/custom-keras-model-running-on-opencv-ai-kit-oak-1-72bb46ebd6df">custom-keras-model-running-on-opencv-ai-kit-oak-1</a></li><li><a href="https://patrick-ryan.medium.com/walk-through-of-opencv-ai-kit-using-the-mobilenet-detection-algorithm-fdbfe9531e54">walk-through-of-opencv-ai-kit-using-the-mobilenet-detection-algorithm</a></li><li><a href="https://patrick-ryan.medium.com/the-opencv-ai-kit-oak-super-simple-video-streamer-starter-fff707630f16">the-opencv-ai-kit-oak-super-simple-video-streamer-starter</a></li></ul><p>In this article I will take you through the steps necessary to create a deer detector system that runs on a RaspberryPi.</p><p>From finding the necessary datasets, creating training, validation and testing datasets, using transfer learning to train a model to detect the presence of deer to evaluation to deployment.</p><p>You can find all of the code and write up on my <a href="https://github.com/youngsoul/deer-detector.git">github repo.</a></p><h3>Step 1: Downloading a dataset of Deer images and Landscape images from Kaggle</h3><p>Two Kaggle datasets were used; deer dataset and a landscape background dataset.</p><ul><li><a href="https://www.kaggle.com/faisalakhtar/images-of-deer-for-svm-classifier">Kaggle Deer Dataset</a></li><li><a href="https://www.kaggle.com/arnaud58/landscape-pictures">Kaggle Landscape Dataset</a></li></ul><h3>Step 2: Create a script to currate a train/validation/test dataset of the Kaggle images</h3><p>From the raw dataset, create a new dataset of train/validation/test images and create the supporting folder structure.</p><p>See the script, <em>make_datasets.py</em></p><h3>Step3: Using transfer learning, train a Keras model to detect the presence of deer.</h3><p>See the script, <em>model_train.py</em></p><p>We start with a MobileNetV3 model, using the imagenet weights and remove the top fully connected portion. We create a new fully connected dense top model and retrain the top section.</p><h3>Step 4: Evaluate the model on the test data</h3><p>See the script, <em>evaluate_model.py</em></p><p>In this script, we use the test data that we created in Step 2, along with images and video collected from the backyard bird feeder. I purposefully did not use images from the actual backyard because I wanted to see if I could train the model and have it generalize to the actual location without seeing images of the actual location.</p><p>Normally you want to train with data that is as close to your ‘production’ environment as possible. Again, I used this as an experiment.</p><h3>Step 5: Test with video</h3><p>See the script, <em>detect_video.py — video-file datasets/backyard/movies/test_deer.MOV</em></p><p>So far all of this has been executed on my MacBook Pro — but I really want to deploy to the OAK-1 device and run it from my Raspberry Pi.</p><p>When you run this detect_video.py script locally, make a mental note of the performance. You will see running it on the OAK-1 is much faster.</p><h3>Step 6: OAK-1 and Raspberry Pi</h3><p>We need to install three additional libraries</p><pre>pip install openvino-dev<br>pip install blobconverter<br>pip install depthai</pre><p>See the script, <em>create_openvino.sh</em></p><p>In my <a href="https://patrick-ryan.medium.com/custom-keras-model-running-on-opencv-ai-kit-oak-1-72bb46ebd6df">previous article</a>, I covered the details of how to convert a Keras model to an OpenVINO format to run on the OAK-1.</p><p>When deploying to the Raspberry Pi. If you try to run the OAK-1 and the RaspberryPi does not recognize the device. Try running the following:</p><pre>echo &#39;SUBSYSTEM==&quot;usb&quot;, ATTRS{idVendor}==&quot;03e7&quot;, MODE=&quot;0666&quot;&#39; | sudo tee /etc/udev/rules.d/80-movidius.rules<br>sudo udevadm control --reload-rules &amp;&amp; sudo udevadm trigger</pre><p>You can find information on this issue on the <a href="https://docs.luxonis.com/en/latest/pages/troubleshooting/">Luxonis Troubleshooting page</a></p><h3>Wrap up</h3><p>I am going to call this project a success. While I would now pull images from the backyard, and from the OAK-1 from where I would have it setup to better train on ‘production’ like images, I thought the performance of the model was acceptable and the performance of the system using the OAK-1 was great.</p><p>You can find a more detailed writeup, the source code and all of training data on my <a href="https://github.com/youngsoul/deer-detector.git">Github repo</a>.</p><p>Now how to automatically fill the deer, umm I mean, bird feeder…..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11a9bd56237" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Keras model running on OpenCV AI Kit (OAK-1)]]></title>
            <link>https://patrick-ryan.medium.com/custom-keras-model-running-on-opencv-ai-kit-oak-1-72bb46ebd6df?source=rss-517be808296c------2</link>
            <guid isPermaLink="false">https://medium.com/p/72bb46ebd6df</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Patrick Ryan]]></dc:creator>
            <pubDate>Sat, 22 Jan 2022 22:32:04 GMT</pubDate>
            <atom:updated>2022-01-22T22:32:04.792Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*VVrJ2-NQYrvVnEkVVaBhMg.png" /><figcaption>Running custom Keras models on the OAK-1</figcaption></figure><p>You have the peanut butter ( TF/Keras model ), and you have the chocolate ( OAK-1) — now how do you get them to work together so the combination is amazing.</p><p>In this article I am going to take you through all of the steps I went through to run a custom built Keras model from a previous project, on the OAK-1 device. There may well be better ways to handle this process, and if you know of a better way, please leave a comment.</p><h3>Building a Face Mask Detector</h3><p>Wait, don’t leave — I realize the world does not need another face mask detector — however this article is really about how to migrate the model to run on an OAK-1. Once we understand the process we can start to look at different models.</p><p>The model I am going to use came the PyImageSearch blog, “<a href="https://www.pyimagesearch.com/2020/05/04/covid-19-face-mask-detector-with-opencv-keras-tensorflow-and-deep-learning/">COVID-19: Face Mask Detector with OpenCV, Keras/TensorFlow, and Deep Learning</a>” by Adrian Rosebrock. I am not going to cover anything about the development of the model, but if you are interested to see how to use transfer learning and build this detector, then please take a look at his blog.</p><p>I am going to pick up where his blog ends.</p><h3>High Level Process</h3><p>The documentation from Luxonis, the company the created the ‘OpenCV AI Kit’ devices has <a href="https://docs.luxonis.com/en/latest/pages/model_conversion/">documentation</a> on how to convert a model to run on the ‘MyriadX’ processor.</p><p>Image below (from <a href="https://docs.luxonis.com/en/latest/pages/model_conversion/">Luxonis documentation </a>( from <a href="https://opencv.org/courses/">OpenCV Courses site</a>)) where I have highlighted the steps we are going to cover.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3F0RvhtVeR1fvQryLifuUA.png" /></figure><p>As you can see, there are not a great deal of steps involved. However making sure you get each step correct can be challenging at first.</p><h3>Step 1: Start with a frozen trained TensorFlow Model</h3><p>This is where you should follow along with with the <a href="https://www.pyimagesearch.com/2020/05/04/covid-19-face-mask-detector-with-opencv-keras-tensorflow-and-deep-learning/">PyImageSearch blog</a> and then come back here when you are done.</p><p>The only thing we need to change is the way we save the model. In the original blog post, Adrian saved the model like so:</p><blockquote># serialize the model to disk<br>print(“[INFO] saving mask detector model…”)<br>model.save(args[“model”], save_format=”h5&quot;)</blockquote><p>I added another line:</p><blockquote>model.save(‘mask_detector’)</blockquote><p>This creates a directory called mask_detector which contains a file called saved_model.pb This is the frozen TensorFlow model that we need to start with.</p><h3>Step 2: Use OpenVINO Model Optimizer</h3><p>The VPU ( vision processing unit ) that powers the OAK is the MyriadX from Intel and uses the OpenVINO platform. As such we need to convert TensorFlow models into the format understood by OpenVINO.</p><p>There are a couple of great resources for background material.</p><ul><li><a href="https://towardsdatascience.com/openvino-start-optimizing-your-tensorflow-2-models-for-intel-cpus-with-docker-ce59f5e1ce64">Towards Data Science Medium Article</a>. In this article the author covers the parameters needed to runthe model optimizer.</li><li><a href="https://docs.openvino.ai/latest/openvino_docs_MO_DG_prepare_model_convert_model_Converting_Model.html">OpenVINO Converting a Model to Intermediate Representation (IR)</a></li></ul><p>In this step we are going to use the OpenVINO Model Optimizer to generate an intermediate representation, with a model config file that has the .xml extension, and a model weights file that has a .bin extension.</p><p>Before we can look at the command line to run the model optimizer we have to understand a little about the model used and the preprocessing that happened.</p><p>The Luxonis devices cameras output values as:</p><ul><li>BGR color format</li><li>Pixel values in the 0 to 255 range</li></ul><p>The base model used was a MobileNetV2 along with the Keras MobileNetV2 preprocessing. This means the image characteristics need to be:</p><ul><li>Image size of 224x224</li><li>Image must be in RGB format</li><li>Input pixel values are scaled between -1 and 1</li><li>Input shape to the model is [1,224,224,3]</li></ul><p>The image size requirement will be handled when we created the DepthAI pipeline. The color format, pixel scaling and input shape will be handled with the model optimzation.</p><p>In my version of the PyImageSearch blog I installed an additional OpenVINO library:</p><pre>pip install openvino-dev</pre><p>This module gives us access to the model optimizer script which can be accessed as a module like:</p><pre>python -m mo &lt;additional parameters to be discussed soon&gt;</pre><p>Lets take a look at the options for the ‘mo’ script that we will use to handle the preprocessing for your model</p><h4>must be in RGB format</h4><ul><li>— reverse_input_channels</li></ul><p>The OAK device, because it is from OpenCV and OpenCV uses BGR color format we have to reverse the input channels. We could handle this in the DepthAI pipeline but I think it makes most sense to make this part of the model optimizer conversion.</p><h4>Input pixel values are scaled between -1 and 1</h4><p>The goal is to take the 0 to 255 image values from the OAK device and scale them to -1 to 1.</p><p>This will be a combination of a couple of values. I encourage you to read the OpenVINO Model Optimizer link above and it describes the parameters that can be used to scale the input. It was not initially obvious to me how to handle the conversion and after talking with the Luxonis team and reading the Toward Data Science medium article did it become clear to me.</p><p>To handle the conversion we actually need a couple of parameters.</p><ul><li>— mean_values \[127.5, 127.5, 127.5\] — scale_values \[127.5, 127.5, 127.5\]</li></ul><p>The 3 values are for the RGB image values and the scaling happens using the following formula (using just red channel as example):</p><blockquote>RScaled = (Rvalue-mean value)/scale value</blockquote><blockquote>RScaled255 = (255–127.5)/127.5=1</blockquote><blockquote>RScaled0 = (0–127.5)/127.5 = -1</blockquote><h4>Input shape to the model is [1,224,224,3]</h4><p>There are a couple of options here.</p><blockquote>— input_shape=\[1,224,224,3\]</blockquote><p>The key here is the ‘1’ for the first dimension because we are going to pass a single image into the deployed model.</p><p>The other option is to specify the batch size</p><blockquote>— batch 1</blockquote><p>This will assume [224,224,3] for the input shape with a single image being passed through the model at a time.</p><p>You only need to specify either input_shape or batch, but not both in this case.</p><p>Finally we can call the model optimizer (‘mo’) script with the necessary parameters.</p><pre>python -m mo --reverse_input_channels --batch 1 --mean_values \[127.5, 127.5, 127.5\] --scale_values \[127.5, 127.5, 127.5\] --saved_model_dir ./mask_detector --output_dir openvino_model</pre><p>Running the above command will produce an OpenVINO Intermediate Representation (IR) that includes a .xml and .bin file in the directory ‘openvino_model’.</p><h3>Step3: Compile OpenVINO Intermediate Representation into Myriad blob</h3><p>Once we have the intermediate representation we need to compile it into an OpenVINO model blob.</p><p>There are two ways to do this:</p><ul><li><a href="http://blobconverter.luxonis.com">Luxonis Online Myriad Blob Converter</a></li><li>Luxonis blobconverter module</li></ul><p>The first option uses the Luxonis online blob converter web application. You can select the .xml and .bin files and it will convert the model to a Myriad blob and allow you to save that.</p><p>If you would like to use a local script to make part of local build process you install the blobconverter and call that directly.</p><p>First install the blobconverter package</p><blockquote>pip install blobconverter</blockquote><p>You can find information on the options on the <a href="https://pypi.org/project/blobconverter/">blobconverter pypi page</a>.</p><pre>blobconverter --openvino-xml ./openvino_model/saved_model.xml --openvino-bin ./openvino_model/saved_model.bin --shaves 6 --output-dir ./openvino_model --no-cache</pre><p>The script I used to convert the trained model can be found at my gist:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0901419515a14b8d10674061b7be8b38/href">https://medium.com/media/0901419515a14b8d10674061b7be8b38/href</a></iframe><p>This script is part of my <a href="https://github.com/youngsoul/pyimagesearch-face-mask-detector.git">Github repo</a> which contains my work going through the <a href="https://www.pyimagesearch.com/2020/05/04/covid-19-face-mask-detector-with-opencv-keras-tensorflow-and-deep-learning/">PyImageSearch blog post</a>. You can find the OpenVINO IR files, and Myriad blob file in the openvino_models directory.</p><h3>Step 4: Run the custom model on OAK device</h3><p>Once we have a Myriad blob file, we are ready to run the model on an OAK device.</p><p>For this, I have the example file in my <a href="https://github.com/youngsoul/depthai-sandbox.git">depthai-sandbox repo</a> in the custom_models/face_mask directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5gp2JsOr4fJkx46uvVOdNw.png" /><figcaption>Custom TF2 Model Pipeline</figcaption></figure><p>Since we covered most of this pipeline in previous articles, I want to focus on the new nodes: ImageManip and NeuralNetwork</p><h4>ImageManip</h4><p>In this pipeline, the ColorCamera was setup to produce images 400x400 for display purposes. However the model expects 224x224, therefore the ImageManip node was added to resize the image.</p><pre>manip = pipeline.create(depthai.node.ImageManip)<br>manip.initialConfig.setResize(224, 224)</pre><h4>NeuralNetwork</h4><p>The NeuralNetwork is created and the path to the MyriadX blob file is set.</p><pre>custom_nn = pipeline.create(depthai.node.NeuralNetwork)<br>custom_nn.setBlobPath(&quot;./saved_model_openvino_2021.4_6shave.blob&quot;)</pre><p>The last element, is to read the predictions from neuralnet queue. To do that we need to read the values from the last layer of the model. There are two ways to get the name of the last layer as known by the OpenVINO IR layer.</p><ul><li>Open the .xml representation and and search for a layer with name ‘softmax’.</li></ul><pre>&lt;layer id=&quot;290&quot; name=&quot;StatefulPartitionedCall/model/dense_1/Softmax&quot; type=&quot;SoftMax&quot; version=&quot;opset1&quot;&gt;</pre><ul><li>Run the face_mask_tf.py script with the following line:</li></ul><pre>[print(f&quot;Layer name: {l.name}, Type: {l.dataType}, Dimensions: {l.dims}&quot;) for l in in_nn.getAllLayers()]</pre><p>This will print the name of the last layer. Using that name of the last layer, call the function on the returned NeuralNetwork message, ‘getLayerFp16’ with the name of the layer. This will return the mask, no mask probabilities.</p><pre># read the prediction from the output layer of the custom model<br>mask, no_mask = in_nn.getLayerFp16(&#39;StatefulPartitionedCall/model/dense_1/Softmax&#39;)<br># print the results of the prediction<br>print(f&quot;Mask[{round(mask,1)}], No Mask[{round(no_mask,1)}]&quot;)</pre><h3>Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ooQd_KojZazjpVoSNobVnQ.gif" /><figcaption>Left: OAK running TF2 model. Right: TF2 model on MacOS</figcaption></figure><p>Running the OAK version on the left, and the model from my MacBookPro you can see that the models are predicting the mask/nomask really well. It was not my intention to make both visually equal — just to see if I could run the same model from the OAK device as from my MacBook.</p><h3>Closing Thoughts</h3><p>If you made it this far, thank you for reading this article and I hope you found it helpful.</p><p>While I believe the process to convert another model would follow the same steps, the details — especially around what the model expects for input and how the data needs to be prepared will likely change.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72bb46ebd6df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Walk-through of OpenCV AI Kit using the MobileNet detection algorithm]]></title>
            <link>https://patrick-ryan.medium.com/walk-through-of-opencv-ai-kit-using-the-mobilenet-detection-algorithm-fdbfe9531e54?source=rss-517be808296c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdbfe9531e54</guid>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[opencv-ai]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <dc:creator><![CDATA[Patrick Ryan]]></dc:creator>
            <pubDate>Tue, 18 Jan 2022 01:43:03 GMT</pubDate>
            <atom:updated>2022-01-18T01:43:03.281Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*u8Q3-efGJboT8hYqck7T_Q.jpeg" /></figure><p>This article builds upon my <a href="https://patrick-ryan.medium.com/the-opencv-ai-kit-oak-super-simple-video-streamer-starter-fff707630f16">previous article</a> where I went over a simple example of how to displaying the video feed from the OAK-1.</p><p>In this article I am going to show how to incorporate the MobileNet Detection Network. The Luxonis documentation is really good and what I am going to do is combine a couple of their tutorials and provide some explanatory commentary which I hope will make the process a little clearer. The hello-world.py Did not include the labels and confidence, so my version of hello-world.py, does include those so we can see how to pull those out of the detections.</p><p>The two tutorials I am going to combine and walk through are:</p><ul><li><a href="https://docs.luxonis.com/projects/api/en/latest/tutorials/hello_world/">Hello World</a></li><li><a href="https://docs.luxonis.com/projects/api/en/latest/samples/MobileNet/rgb_mobilenet/#rgb-mobilenetssd">RGB MobileNet SSD</a></li></ul><p>I have also put together a YouTube walk through as well if you interested in that. You can find that on <a href="https://www.youtube.com/watch?v=iUNQPspeUA8">YouTube here</a>.</p><h3>OAK Processing Pipeline</h3><p>Recall from the previous article, that the OAK using a processing pipeline on the device. The pipeline processes <a href="https://docs.luxonis.com/projects/api/en/latest/components/nodes/">Nodes</a> in the order the Nodes are linked together.</p><p>In this article we are going to add a <a href="https://docs.luxonis.com/projects/api/en/latest/components/nodes/mobilenet_detection_network/">MobileNetDetectionNetwork</a> Node to the pipeline from the previous article.</p><h4>MobileNetDetectionNetwork Node</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*khvA-w9Gu1xwcuPBa9ZbbA.png" /><figcaption>MobileNetDetectionNetwork Node</figcaption></figure><p>This node performs the MobileNetDetection algorithm on the input data and returns a collection of detections.</p><p>The ‘input’ should take the output of the ColorCamera so the MobileNet network can try to detect objects. We use the ‘preview’ output of the ColorCamera Node.</p><p>The ‘out’ values are a collection of ‘<a href="https://docs.luxonis.com/projects/api/en/latest/components/messages/img_detections/#imgdetections">ImgDetection</a>’ objects. Each detection has the following properties:</p><ul><li>label — MobileNet label index</li><li>confidence — Confidence, or probability of that label</li><li>xmin,ymin,xmax,ymax — Upper left and lower right corners of the bounding box. These values are normalized values and therefore we have to multiply the values by the shape of the frame, which for MobileNet is 300x300.</li></ul><p>For us to display the detections we need to read the frames as we did in the previous article, and use the ImgDetection data to write the additional information and then display the frame.</p><h4>MobileNet OAK Pipeline</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wvl-6NTd9R2xcBk9i4sg_w.png" /><figcaption>OAK Pipeline for a MobileNet Network</figcaption></figure><h3>Implementation</h3><p>You can find this particular examples and others in my ‘<a href="https://github.com/youngsoul/depthai-sandbox.git">DepthAI Sandbox Repo’</a>. Look in the tutorials directory.</p><p>However here is the version of the hello-world.py as of the writing of this article.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98ece4a80aa5c96513def8fced805969/href">https://medium.com/media/98ece4a80aa5c96513def8fced805969/href</a></iframe><p>To run the script, after you activate your Python virtual environment just execute:</p><blockquote>python hello_world.py</blockquote><p>You should see something like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*k3OfywGm0vhq0X7X2q8aSA.gif" /></figure><h3>RaspberryPi</h3><p>I typically run these scripts from my Mac, however I have also tested this running from a RaspberryPi. There are a couple of things to know if you want to run from your Raspberry Pi.</p><ul><li>You will need to install OpenCV. I have a repo where I keep scripts that can build and/or install OpenCV on a RaspberryPi. You can find that script in this <a href="https://github.com/youngsoul/rpi_opencv_install">repo</a>. The file I typically run is pi_install_imagelibs.sh. This script will still other image libraries that I use often — so feel free to use this as a guide.</li><li>After you install OpenCV you will need to pip install:</li><li>depthai</li><li>blobconverter</li></ul><p>If you try to run the script and you get an error like:</p><pre>RuntimeError: Failed to find device (ma2480), error message: X_LINK_DEVICE_NOT_FOUND</pre><p>Then you need to run:</p><pre>echo &#39;SUBSYSTEM==&quot;usb&quot;, ATTRS{idVendor}==&quot;03e7&quot;, MODE=&quot;0666&quot;&#39; | sudo tee /etc/udev/rules.d/80-movidius.rules<br>sudo udevadm control --reload-rules &amp;&amp; sudo udevadm trigger</pre><p>As was discussed in this <a href="https://docs.luxonis.com/en/latest/pages/troubleshooting/">troubleshooting page</a>.</p><h3>Wrap Up</h3><p>If you would like to see what else I am up to on the OAK, feel free to check out my sandbox repo.</p><p>I also have a <a href="https://www.youtube.com/watch?v=iUNQPspeUA8">YouTube video</a> walk through where I demonstrate the script.</p><p>The OAK-1 is a really impressive device and I am looking forward to exploring more of the its capability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdbfe9531e54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The OpenCV AI Kit ( OAK ) super simple video streamer starter]]></title>
            <link>https://patrick-ryan.medium.com/the-opencv-ai-kit-oak-super-simple-video-streamer-starter-fff707630f16?source=rss-517be808296c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fff707630f16</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[opencv-python]]></category>
            <category><![CDATA[opencv]]></category>
            <dc:creator><![CDATA[Patrick Ryan]]></dc:creator>
            <pubDate>Sat, 15 Jan 2022 02:47:20 GMT</pubDate>
            <atom:updated>2022-01-15T02:47:20.258Z</atom:updated>
            <content:encoded><![CDATA[<p>I know the OAK has been out for a little while now, but I am just starting to really dig into this device from Luxonis. If you dont know what it is, you can find it and buy it <a href="https://shop.luxonis.com/products/megaai-kit">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*u8Q3-efGJboT8hYqck7T_Q.jpeg" /><figcaption>Luxonis OAK-1</figcaption></figure><p>The best place to start, is with the great <a href="https://docs.luxonis.com/projects/api/en/latest/">documentation</a> from Luxonis.</p><p>The programming metaphor is one of a processing pipeline. Each step in the pipeline is a ‘node’ and there are a number of ‘node’ types that are part of the API. You can find documentation on the different types of Nodes <a href="https://docs.luxonis.com/projects/api/en/latest/components/nodes/">here</a>.</p><p>The image below, from the Luxonis documentation, represents the high level architecture. The OAK devices handles all of the video and image processing, including running computer vision models and then send resulting information to the host computer to act upon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XDfuMfys2IhUT6wGQJ1img.png" /><figcaption>From Luxonis DepthAPI API Docs</figcaption></figure><p>In our simple example we need two nodes:</p><p><a href="https://docs.luxonis.com/projects/api/en/latest/components/nodes/color_camera/"><strong>ColorCamera</strong></a></p><p><a href="https://docs.luxonis.com/projects/api/en/latest/components/nodes/xlink_out/"><strong>XLinkOut</strong></a></p><h3>ColorCamera Node</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*F7Hg5kH9ytj1nXDyrRIHKg.png" /><figcaption>Luxonis documentation, ColorCamera Node</figcaption></figure><p>This node will handle reading high resolution frames from the OAK camera.</p><p>The ColorCamera node has 2 inputs, and a number of outputs. For this simple example, we will only need the output labeled ‘preview’. This output is suitable for smaller preview sized images.</p><h3>XLinkOut</h3><p>This node will handle consuming messages from nodes on the OAK device, and sending them to the host computer to an internal queue.</p><p>The application / script running on the host computer pulls data from the internal queues. In our case, the internal queue will hold image frames.</p><h3>Video Stream Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OSrNNQcTdXqb5Gvbh78Owg.png" /><figcaption>Video Stream Pipeline</figcaption></figure><h3>Where is the code?</h3><p>You can find the code on my <a href="https://github.com/youngsoul/depthai-video-stream">Github repo</a>.</p><p>Assuming you have a Python virtual environment setup, all you have to do to get started is the following:</p><pre>git clone <a href="https://github.com/youngsoul/depthai-video-stream.git">https://github.com/youngsoul/depthai-video-stream.git</a><br>cd depthAI-video-stream<br>pip install -r requirements.txt<br>python videostream.py</pre><h4>Pipeline Setup</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e93ab7f2a6b9532c8f1722c01ba0309/href">https://medium.com/media/3e93ab7f2a6b9532c8f1722c01ba0309/href</a></iframe><p>The important lines of code are:</p><p><em>Line 2 - creates the Pipeline.</em></p><p><em>Line 6 - creates the ColorCamera node</em></p><p><em>Line 11 - creates the XLinkOut</em></p><p><em>Line 13 - connects the camera node to the xlinkout node.</em></p><h4>Processing Loop</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d77a0dd3a99c994edad8ce5b7d87c0bb/href">https://medium.com/media/d77a0dd3a99c994edad8ce5b7d87c0bb/href</a></iframe><p>The loop to process messages from the internal queue looks like above.</p><p>The important lines of code are:</p><p><em>Line 1 - create a Device context manager which represents the software twin of the physical OAK device.</em></p><p><em>Line 2 - get a reference to the internal queue where frames are being sent from the OAK</em></p><p><em>Line 6 - read a frame from the queue</em></p><p><em>Line 8 - read the frame as an OpenCV frame</em></p><p><em>Line 10 - show the frame in an OpenCV windown</em></p><p>That is almost the entire file, but for those are would like to see the entire file, here it is.</p><h4>Entire Script</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73b785c82dc08c7b8df412138a9f9604/href">https://medium.com/media/73b785c82dc08c7b8df412138a9f9604/href</a></iframe><h3>Wrap up</h3><p>While this is a really simple starter, it did help me get a better understanding of the mental model used by the OAK devices. With this understanding I am now ready to tackle the more complex and interesting computer vision tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fff707630f16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using MediaPipe to detect the YMCA dance]]></title>
            <link>https://patrick-ryan.medium.com/using-mediapipe-to-detect-the-ymca-dance-1e74296ca307?source=rss-517be808296c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e74296ca307</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mediapipe]]></category>
            <dc:creator><![CDATA[Patrick Ryan]]></dc:creator>
            <pubDate>Tue, 30 Nov 2021 22:27:05 GMT</pubDate>
            <atom:updated>2021-11-30T22:27:05.288Z</atom:updated>
            <content:encoded><![CDATA[<p>Ok, this blog might not be ground breaking — but it sure was a fun way to show a group of people the kinds of problems machine learning can solve that would be very difficult with traditional techniques.</p><p>If by chance you have no idea what the YMCA dance is or what song I am referring to, you can check out the <a href="https://www.youtube.com/watch?v=CS9OO0S5w2k">official video on YouTube</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JLAnsw9NU6TFEVKKCARrCQ.gif" /></figure><p>For more details on this fun, silly project see my <a href="https://github.com/youngsoul/mediapipe-ymca.git">Github Repo</a>.</p><h3>MediaPipe</h3><p>A number of blog posts have been written about <a href="https://mediapipe.dev">MediaPipe</a>. All I am going to say about it is that it was the framework I used to capture pose landmark information.</p><p>I was able to collect a number of training samples of what a ‘Y’ pose, ‘M’ pose, ‘C’ pose, ‘A’ pose and a ‘dance’ pose look like. Each of the samples include the x,y,z values for the body landmarks of interest.</p><p>I created a script to collect frames from a webcam and append the pose landmark data to a csv file. You can see that script called, 01_pose_training-data.py <a href="https://github.com/youngsoul/mediapipe-ymca/blob/master/01_pose_training_data.py">here</a>.</p><h3>Scikit-Learn</h3><p>Once the data was collected for all of the poses, the problem became a very typical Scikit-Learn supervised machine learning problem.</p><p>We have a labeled dataset in csv format. I ran through a number of different models with GridSearchCV to determine the best model for the given data.</p><p>I created a script to run through all of the models. You can see that script called, 02_pose_model_training.py <a href="https://github.com/youngsoul/mediapipe-ymca/blob/master/02_pose_model_training.py">here</a>.</p><h3>Making Predictions</h3><p>This is where it gets fun!</p><p>Using the trained model, we can start to capture new images from the computer webcam and make predictions on the dance pose.</p><p>Because it is not much fun to dance with yourself, even though <a href="https://www.youtube.com/watch?v=FG1NrQYXjLU">Billy Idol </a>had a hit song around that theme, I decided to add an option to the prediction script to add some additional ‘virtual’ dancers to make the entire process that much more fun and silly.</p><p>I created a script to run the predictions and you can see that script called, 03_pose_predictions.py <a href="https://github.com/youngsoul/mediapipe-ymca/blob/master/03_pose_predictions.py">here</a>.</p><h3>End of the song</h3><p>My goal in putting this together was to create a fun and engaging way to show a group of people the kinds of problems that machine learning can solve. I think to spark interest and imagination in someone, the best way is to let them interact with the technology. Get them excite about the technology and the possibilities of using the technology.</p><p>Again, check out my <a href="https://github.com/youngsoul/mediapipe-ymca">github repo</a> if you would like to try this. The scripts will capture any pose, train and predict on whatever pose you would like to capture and train on. It just so happens I picked something from my past.</p><p>If you try this yourself, send me the YouTube link!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e74296ca307" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using DeepStack for Sign Language Object Detection]]></title>
            <link>https://medium.com/analytics-vidhya/using-deepstack-for-sign-language-object-detection-4478a6e7a2e6?source=rss-517be808296c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4478a6e7a2e6</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Patrick Ryan]]></dc:creator>
            <pubDate>Tue, 09 Feb 2021 16:12:04 GMT</pubDate>
            <atom:updated>2021-02-10T16:38:43.811Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*87ZljnpTL78vytS1WgIB1Q.gif" /><figcaption>Sign Language Object Detection with DeepStack</figcaption></figure><p>I recently worked through a great video by <a href="https://github.com/nicknochnack">Nicholas Renotte </a>on how to use <a href="https://youtu.be/pDXdlXlaCco">Tensorflow2 Object Detection API for sign language</a>.</p><p>Using Tensorflow 2, I re-created that project and you can read about that on my <a href="https://github.com/youngsoul/sign-language-detection-with-tfod2">Github repo</a>.</p><p>During my investigation on how to perform custom object detection, I ran across a Medium blog, “<a href="https://medium.com/deepquestai/detect-any-custom-object-with-deepstack-dd0a824a761e">Detect any custom object with DeepStack</a>”.</p><p>You can find out more information concerning <a href="http://deepstack.cc">DeepStack here</a>. The documentation for DeepStack can be found <a href="https://docs.deepstack.cc">here</a>.</p><p>I was very intrigued by their approach of using Docker containers that either come with pre-configured capability or you can train from your own data.</p><p>Below is a summary of the steps I took to create the sign language object detector you see above, using the DeepStack framework.</p><h3>Annotate DataSet</h3><p>First, I took the images I used for the TFOD that were annotated with pascal-voc, and re-annotated them in YOLO format. You find a repo of both datasets on my <a href="https://github.com/youngsoul/sign-language-dataset">sign-language-dataset repo</a>.</p><p>I used LabelImg, but any tool that you like will do the trick. You just need to use YOLO format.</p><h3>Zip the DataSet</h3><p>Create a zip file that contains the test and train directories. In each of the test and train directories is the YOLO formatted annotation files.</p><h3>Upload DataSet to Google Colab</h3><p>You can either training locally on your computer if you have a GPU, or as DeepStack recommends you can train using the Google Colab environment. They provide a starter notebook using the following link.</p><p><a href="https://colab.research.google.com/drive/1gbTr_4xpDk3cpnbAVbMVxtyp-3XuUPix?usp=sharing">Google Colaboratory</a></p><p>All of this information can be found in the DeepStack documentation under ‘Custom Models’.</p><p>When you first go to the Google Colab link the page will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8bxi0NUlrgKxDvf9iLUHuQ.png" /></figure><p>Select the upload button in the upper left and navigate to where you created your zip file of the test and train directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qa7oAi-b8fKr-XdrhLLZyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*PWM34X3yXZw2dX6zc8v2sA.png" /></figure><h3>Clone the DeepStack Trainer</h3><p>Run the code cell and clone the DeepStack Trainer repo. You will get a warning saying that the notebook was not authored by Google. Just go ahead and run anyway.</p><h3>Unzip the Archive</h3><p>Open a new code cell and type the following:</p><blockquote>!unzip /content/Archive.zip -d /content/sign_dataset</blockquote><p>When that completes the left nav should look something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*h7MQD2I0Nox9UEKX5ygPwA.png" /></figure><h3>Train the model</h3><p>Open a new code cell, and to train the model you can type:</p><pre>python3 train.py --dataset-path &quot;/content/sign_dataset&quot;</pre><p>However, there are a few parameters that the documentation highlights that you might want to be aware of. (Right from their documentation).</p><p>When I trained the model I just used the above command, however I noticed after about 110 epochs the accuracy did not improve. I could have cut it short but I let it run the full 300 epochs.</p><p>The training process took about 1.5 hours.</p><h3>Important Parameters</h3><p>The following parameters can be set to optimize your model to suit you better</p><ul><li>`--model` DeepStack trainer supports five model types, in order of increasing accuracy they are `&quot;yolov5s&quot;`, `&quot;yolov5m&quot;`, `&quot;yolov5l&quot;`, `&quot;yolov5x&quot;`. The default is yolov5m, the highest accuracy onces like yolov5l and yolov5x are much slower and will require higher end compute to deploy. The fastest yolov5s is highly recommended if deploying on the nvidia jetson.</li><li>`--batch-size` This is the number of images processed at once, you can set this to a higher number like 32 or 64 as your gpu memory allows, if you use a gpu with lower memory, you can set this to a lower number like 8 or less if you run into memory problems. The default value is 16</li><li>`epochs` This is the number of iterations over your entire dataset, the default value is 300. You can always run with lesser epochs or more epochs, accuracy increases as you run more epochs.</li></ul><h3>Download the best model</h3><p>After training has completed. You will find the best model in the directory:</p><blockquote>deepstack-trainer/train-runs/sign_dataset/exp/weights/best.pt</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*XNQNMQC9UZ1Zh6Zgw2F6TQ.png" /></figure><h3>Setup DeepStack Docker Container</h3><p>There are a number of ways to setup the DeepStack docker container and you should review their documentation for the complete list of possibilities. I am going to cover what I did to run on MacOS.</p><p>It is assume you have Docker installed.</p><p>In a terminal window</p><pre>docker pull deepquestai/deepstack</pre><h3>Run DeepStack Docker container with new model</h3><p>In a terminal window run the following command:</p><blockquote>docker run -v /path/to/directory/containing/downloaded/model/signlanguage-model:/modelstore/detection -p 5000<br>:5000 deepquestai/deepstack</blockquote><p>I used 5000 as the local computer port number instead of 80 as they recommend because I have too many things that may want to use port 80.</p><h3>Run script to capture video images for inference</h3><p>I wrote a script that would capture video frame, encode them as a jpg image and make the required post request to the running DeepStack Docker container running the newly trained model.</p><p>You can find that script on my <a href="https://gist.github.com/youngsoul/2e6a64dabbf9303103bc48b8b2ab3617">gist repo</a></p><p>Note that the url you need to access from the client script looks like:</p><blockquote><a href="http://localhost:5000/v1/vision/custom/sign">http://localhost:5000/v1/vision/custom/sign</a></blockquote><p>where 5000 is the port you exposed above. The ‘sign’ part of the url is the base name of the model that was downloaded. In my case I called the model, ‘sign.pt’</p><p>To use this client script you will need to create a Python virtual environment and install OpenCV as I used this to capture video and display images. You can of course sub out any other framework that you prefer.</p><h3>Results</h3><p>You can see the results above. Very good accuracy with no false predictions.</p><p>Using the ‘yolov5m’ model, it took about 250ms per frame to run the inference model. So not exactly real-time, but pretty good in my opinion. I will try the ‘yolov5s’ to see what the performance characteristics of this model are.</p><p>Overall I was really impressed with the workflow and ease to create a custom YOLOV5 object detection model with only really installing a Docker container.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4478a6e7a2e6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/using-deepstack-for-sign-language-object-detection-4478a6e7a2e6">Using DeepStack for Sign Language Object Detection</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[There Are No Straight Lines In Nature]]></title>
            <link>https://medium.com/analytics-vidhya/there-are-no-straight-lines-in-nature-3b255de19319?source=rss-517be808296c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b255de19319</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Patrick Ryan]]></dc:creator>
            <pubDate>Fri, 26 Jun 2020 17:36:42 GMT</pubDate>
            <atom:updated>2020-07-03T13:29:10.048Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ifeecOMXkdNh2Z7c" /><figcaption>Photo by <a href="https://unsplash.com/@ideasboom?utm_source=medium&amp;utm_medium=referral">Qingbao Meng</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Which means using linear machine learning models probably won’t model the real world very well.</p><p>This article will take a look at a non-linear data set, concentric circles, and see how we can apply a couple of machine learning and deep learning models to create a classification model.</p><p>There are many ways to approach this problem, and this article is not meant to be a complete body of work on the subject, but instead a more casual look at how to approach the problem.</p><h3>DataSet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*rE6-bpcEUw605_tPpZ8YwQ.png" /><figcaption>scikit-learn: make_circles</figcaption></figure><p>The dataset was created with Scikit-Learns, make_circles, function. This creates a 2-class classification data which can clearly not be separated by a line. In this case we will need to add some non-linearity to our models.</p><p>First — lets see what happens when we try to use a linear model to separate this data.</p><h3>LogisticRegression</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*4hj-kzy8jQRT4dgUNarwyg.png" /><figcaption>LogisticRegression</figcaption></figure><p>As you can see — LogisticRegression is only able to separate the data as best it can along a straight line. This model wont do.</p><h3>LinearSVM</h3><p>Lets look at a linear Support Vector Machine. Because this is also a linear model we would not expect it to perform any better. However we will also see that we can make Support Vector Machines perform very well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*RSw_Zw5yWPncucCV1ZXIoA.png" /><figcaption>LinearSVM</figcaption></figure><p>As expected this too does not perform well.</p><p>Support Vector Machines have a ‘kernel’ parameter which allows for the model to perform higher dimensional analysis on the data. By adding higher dimensional features to the existing data allows for the separation. There are two kernels we will look at: poly and rbf.</p><h3>Support Vector Machine with Poly Kernel</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*zYYfz7CdLxQFZly_6kzXVg.png" /><figcaption>Support Vector Machine — kernel=’poly’, degree=3</figcaption></figure><p>Using a Support Vector Classifier with a poly kernel and a degree parameter of ‘3’ we can see that the model is able to separate the data very well and has a holdout accuracy of about 98%.</p><h3>Support Vector Machine with Radial Bias Function Kernel</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*oXXeJGTXMZ3pyCL51FLocQ.png" /><figcaption>Support Vector Machine — kernel=’rbf’</figcaption></figure><p>Using a Support Vector Classifier with a ‘rbf’ kernel also performs very well with a holdout accuracy of about 98%.</p><h3>RandomForestClassifier</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*7v_tUootURhvtRn2zAgNhg.png" /><figcaption>RandomForestClassifier — n_estimators=100, max_depth=5</figcaption></figure><p>RandomForestClassifiers is another model that can handle non-linear data. As we can see in this dataset, while it does pretty well it struggles to literally fit a square peg into a round hole. The holdout accuracy for this model is about 90%. Adjusting hyperparameters can result in a higher accuracy but you have to be careful with overfitting.</p><h3>Deep Learning Neural Network</h3><p>By their very definition neural networks handle non-linear data. Using a simple Keras like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*GMqKmdVInvE89ipsw9gKXg.png" /><figcaption>Keras Model</figcaption></figure><p>Training for 600 epochs shows a loss/accuracy graph as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*_gRmQMWs32hicSrPJxB-IA.png" /><figcaption>Loss/Accuracy Curves</figcaption></figure><p>With a result like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*NysSZufP7mvy1dt2Ku0x2g.png" /><figcaption>Keras Sequential Neural Network — Epochs=600</figcaption></figure><p>As we would expect, a neural network was able to handle the non-linearity in the dataset with enough epochs.</p><h3>Summary</h3><p>To see the notebook that was used for this article see my <a href="https://github.com/youngsoul/circles-svm-nn">Github Repo</a>.</p><p>This article used a non-linear dataset of concentric circles and looked at a few different models that could be used to separate the data. For small to medium sized datasets, Support Vector Machines can be an excellent choice. For larger datasets — neural networks would work well with enough training time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b255de19319" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/there-are-no-straight-lines-in-nature-3b255de19319">There Are No Straight Lines In Nature</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>