<?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 James Andersen on Medium]]></title>
        <description><![CDATA[Stories by James Andersen on Medium]]></description>
        <link>https://medium.com/@jandersen78?source=rss-fded36c95c1f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EuTwuSSgnhUfgO665oNwVw.jpeg</url>
            <title>Stories by James Andersen on Medium</title>
            <link>https://medium.com/@jandersen78?source=rss-fded36c95c1f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:05:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jandersen78/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[Predicting Loan Grades with a Neural Network: A Machine Learning Pipeline on AWS]]></title>
            <link>https://medium.com/universal-mind/predicting-loan-grades-with-a-neural-network-a-machine-learning-pipeline-on-aws-65d5e1d2f08e?source=rss-fded36c95c1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/65d5e1d2f08e</guid>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[James Andersen]]></dc:creator>
            <pubDate>Fri, 08 Sep 2017 16:25:24 GMT</pubDate>
            <atom:updated>2017-09-08T16:25:24.903Z</atom:updated>
            <content:encoded><![CDATA[<p>In a <a href="https://medium.com/universal-mind/predicting-lending-rates-an-intro-to-aws-machine-learning-5cada982d657">previous article</a> we looked at predicting interest rates and loan grades using the managed <a href="https://aws.amazon.com/machine-learning/">AWS Machine Learning</a> service. While AWS Machine Learning offers a convenient way to build and use regression models without building an underlying processing pipeline, sometimes more customization or control may be needed. For example, you may want to use a more complex deep learning model that performs better on your dataset. Here’s a high level look at the flow we’ll explore in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e8dhhnlrTCiK1ygQOCb1fA.png" /></figure><p>As with the previous article, relevant source code is available in a <a href="https://github.com/jamesandersen/aws-machine-learning-demo">github repo</a>.</p><h3>Working on a Model Locally</h3><p>An inevitable first step in a machine learning pipeline will be getting familiar with the data. This will likely involve data cleaning and some <a href="https://en.wikipedia.org/wiki/Exploratory_data_analysis">exploratory data analysis</a>. <a href="http://jupyter.org/">Jupyter</a> notebooks have become a common way to share the results of this analysis as they allow step by step explanation of interesting findings in a dataset along side the output of the code written to analyze or process the data. Checkout <a href="https://github.com/jamesandersen/aws-machine-learning-demo/blob/master/keras-deeplearning/train-model/lending-club-loan-grades.ipynb">a sample Jupyter notebook</a> for our loan data set <a href="https://github.com/jamesandersen/aws-machine-learning-demo/blob/master/keras-deeplearning/train-model/lending-club-loan-grades.ipynb">here</a>.</p><h3>Data Preparation</h3><p>As we’re no longer using the AWS Machine Learning service, we have a little extra work to do to prepare our data to be fed into the model:</p><ul><li><a href="http://machinelearningmastery.com/why-one-hot-encode-data-in-machine-learning/"><strong>One-hot Encoding</strong></a> — We’re trying to predict a non-numeric loan grade category: “A” through “G”. Neural networks don’t do letters, only numbers. So rather than give the network a <strong>letter</strong> to predict we transform each of the possible and category values into an “on/off” switch represented by either <strong>a zero or a one</strong>. For any single in loan record only one value will be “on”:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/214c87b5cd443ca520229dfb54d35533/href">https://medium.com/media/214c87b5cd443ca520229dfb54d35533/href</a></iframe><ul><li><a href="https://en.wikipedia.org/wiki/Feature_scaling"><strong>Feature Scaling</strong></a> — This is a transformation of the continuous <em>numeric</em> features of our data so they’re all on the same scale. It was performed by the normalize() function in the AWS machine learning service previously. This prevents changes in features measured on a larger scale e.g. credit limit which could be measured in thousands of dollars from weight from weighing heavier than features on a smaller scale like number of accounts open.</li></ul><h3>Creating a Model</h3><p>As we get more familiar with the data we’ll start working on composing a model to infer/predict useful information from the data, in our case we’re going to revisit predicting a loan letter grade in the scale A — G. We’ll use <a href="https://keras.io/">Keras</a>, a python module which acts as a higher level API over some of the other popular deep learning libraries (<a href="https://github.com/tensorflow/tensorflow">Tensorflow</a>, <a href="https://github.com/Microsoft/cntk">CNTK</a> and <a href="https://github.com/Theano/Theano">Theano</a>) to build this model. Different from the linear models the AWS Machine Learning service uses, we’ll create a neural network accepting our input data, passing it through hidden layers and outputting final layer of 7 values corresponding to the likelihood that the input represents a loan in each of the possible loan grade categories A — G. This model, due to non-linear activation functions between nodes in the network, can discover more complex relationships in the data we’re looking at and, as we’ll see, can deliver more accurate predictions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6dccfff99556be0d933fb1fd2d86cdff/href">https://medium.com/media/6dccfff99556be0d933fb1fd2d86cdff/href</a></iframe><p>I used Keras and Jupyter from a local docker container (<a href="https://hub.docker.com/r/gw000/keras-full/">gw000/keras-full</a>) with a volume mapped to a local directory containing the loan data. To avoid lengthy processing of the entire dataset on my local machine, I sampled a subset of 50K records from the full 400K+ dataset. This allowed me to get a rough sense of how adjusting various hyper parameters (e.g. number of hidden layers, number of hidden nodes in each layer, batch size, number of epochs, etc.) were impacting the model performance without the delay of crunching the entire dataset each time.</p><p>While optimizing ML model hyper parameters is well outside the scope of this article, graphing the accuracy and loss of the model on the training set alongside a held-out validation set helps us see both how well the model is performing overall and how much value there is in each successive training iteration. As the accuracy and loss start to level out there is a smaller improvement with each successive training iteration. The history object returned by Keras’ <a href="https://keras.io/models/model/#fit">model.fit()</a> method provides the data we need to generate these graphs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*11bEuYnqpfGRlA67." /><figcaption>Accuracy and loss graphs of the training and validation set over 45 epochs</figcaption></figure><h3>GPU Training on a Shoestring</h3><p>With some data analysis done and a model structure that seems suitable based on our local testing, now it’s time to train the model with our full dataset. Training a neural network involves a lot of mathematical computation for which GPUs are well suited. However, high-powered GPUs aren’t cheap; renting on-demand GPU instances on which to train our model with a large dataset is a cost-effective approach because we’ll only pay for the time we need and won’t incur the cost of a purchasing GPU hardware.</p><p>However, if we can be somewhat flexible in when our training takes place we can be even more cost efficient by training on a <a href="https://aws.amazon.com/ec2/spot/">“spot” GPU instance</a>. AWS offers their unused EC2 compute capacity at a rate that is typically much lower than the on-demand pricing; for the p2.xlarge instance it’s generally less than ⅓ the on-demand price (see chart).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e__wdQrSC-43flnI." /><figcaption>Spot instance pricing for p2.xlarge instance in us-west-2 region</figcaption></figure><p>To use spot instances, you enter a bid amount and which instance types you are looking to use. You are charged the spot rate for your instances as long as the rate remains below your bid amount. If/when the rate exceeds your bid amount, AWS will automatically terminate your instances. If our model training gets interrupted we can either restart it again later or write logic to resume from where we left off. For our loan grade demo project, we’ll just keep it simple and assume that we’ll restart the training if we get interrupted; this loan data doesn’t actually take all that long to train.</p><p>So we’ve got cheap access to a GPU instance… What machine image can we use to do our training? Fortunately, Amazon provides the <a href="https://aws.amazon.com/marketplace/pp/B01M0AXXQB">Amazon Deep Learning AMI</a>, a public virtual machine image that packages several of the most popular open source deep learning frameworks including Keras and Tensorflow, along with GPU drivers compatible with Amazon’s P2 GPU instance types. This is a useful AMI at a great price: free.</p><p>Using spot instances is a little more work than simply launching a new EC2 instance but we can use <a href="https://github.com/jamesandersen/aws-machine-learning-demo/blob/master/keras-deeplearning/train-model/train-model.template">a CloudFormation template</a> to automate the process for us. The template will take in a few parameters and then provision a GPU instance and automate the training of our model. Here are the inputs and a quick description of what each controls in the creation of our model training stack:</p><ul><li><strong>InstanceType</strong> — Which variant of the GPU family do you want to run your workload on?</li><li><strong>SpotBidPrice</strong> — How much are you willing to spend per hour for your instance? The instance type and spot bid price will be used in creating a “Spot Fleet Request” which will launch your instance (provided your bid is above the going “market” rate for the instance type)</li><li><strong>KeyPairName</strong> — Key pair used to access the instance (if needed)</li><li><strong>SourceCidr</strong> — What IP address range will be allowed to access the instance? Your launched instances will be added to a new security group which allows SSH and port 8888 (Jupyter default port) access only to the IP address range you specify. SSH access will require the use of the KeyPair specified by KeyPairName.</li><li><strong>GitRepo</strong> — What Git repo contains your model logic/code?</li><li><strong>GitBranch</strong> — What branch to pull</li><li><strong>RunScript</strong> — A repository relative path to a shell script that will kick off your training logic. Once your instance is launched, a user data initialization script will handle some setup to publish logs from your instance to CloudWatch. It will also pull down code from a public facing Git repo and branch and execute a shell script to kick off your model training logic. This shell script will NOT be run as root.</li><li><strong>OutputBucket</strong> — An S3 bucket that your instance will be given access to read from and write to. Your RunScript will need to pull in data from some location, this approach assumes it will be available in an S3 bucket. The AWS CLI will be available to pull down the data and later to copy trained model and any other training artifacts back into the bucket</li></ul><p>To summarize, <a href="https://github.com/jamesandersen/aws-machine-learning-demo/blob/master/keras-deeplearning/train-model/train-model.template">the CloudFormation template</a> is going to create a GPU spot instance inside a VPC, pull down a Git repo and then execute a shell script from the repo for us. That script will perform the training and then need to save any results out to an S3 bucket for later use. At a minimum, In order to use the model subsequently for making predictions, we’ll want to save it to an HDF5 file with <a href="https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model">model.save()</a>.</p><p>If you happen to be following along in your own account, <strong>don’t forget to shutdown the CloudFormation stack when training is complete</strong> to avoid ongoing charges. This can be automated but got a little outside the scope of this article.</p><h3>How’d We Do?</h3><p>When running on the <strong>entire</strong> dataset, the Keras model was able to get accuracy (measured by the <a href="https://en.wikipedia.org/wiki/F1_score">F1 Score</a>) of .9435; a <strong>significant</strong> improvement over the 0.51 accuracy of the AWS Machine Learning service model. Here are the confusion matrices from the AWS Machine Learning service and the neural network side by side:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7D5aR7zbPC9XKau-Dq2W2w.png" /><figcaption>Comparison of the confusion matrices for AWS Machine Learning and a fairly simple neural network. The neural network model has a much higher F1 score on the same dataset.</figcaption></figure><h3>Using Our Trained Model</h3><p>At this point we’ve trained model parameters with our large dataset and saved our work (the trained model) out to S3. Taking a step back, we still haven’t improved any business process or customer experience one iota. We need to <strong>deploy</strong> the model into our systems and start using it to make loan grade predictions.</p><p>There are several options here:</p><ul><li>Use the model from an internally hosted/deployed application</li><li>Deploy the model to a fleet of EC2 instances</li><li>Build a docker image with our saved model and add it to an ECS cluster</li><li>Create a serverless Lambda function to perform predictions using our model</li><li>etc.</li></ul><p>Your own context will drive the right option; for this article we’ll look at the Lambda option. As a serverless compute option, Lambda not only scales seamlessly but it can also be triggered by a variety of sources in an AWS infrastructure. For example:</p><ul><li>When combined with an API Gateway trigger the Lambda becomes an HTTP microservice</li><li>When using the AWS SDK, the Lambda function can be invoked directly from other application logic</li><li>The Lambda function could be invoked by DynamoDB streams to update new records as they are inserted into a table</li></ul><h3>Building a Lambda Deployment Package</h3><p>However, we do have a bit of a challenge with Lambda; the maximum package size for Lambda is <a href="http://docs.aws.amazon.com/lambda/latest/dg/limits.html">50 mb compressed</a>. If you follow the instructions for <a href="http://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html#deployment-pkg-for-virtualenv">creating a Python deployment package</a> and install Keras and Tensorflow with <a href="https://pypi.python.org/pypi/pip">pip</a>, you’ll find the resultant package is quite a bit larger than 50 mb compressed; well outside the Lambda package size limit.</p><p>To get around this we have to do some surgical removal of anything in the package that is nonessential for runtime. Have a look at <a href="https://github.com/jamesandersen/aws-machine-learning-demo/blob/master/keras-deeplearning/deploy-model/build-lambda-pkg.sh">build-lambda-pkg.sh</a> which scripts the process of collecting Keras and a minimal set of runtime dependencies for inclusion in a Python Lambda deployment package. Getting under the 50mb limit was a somewhat painful process of trial and error. However, we can use the handy <a href="https://hub.docker.com/r/lambci/lambda/~/dockerfile/">lambci/lambda</a> docker images which simulates an actual Lambda runtime to quickly collect the the runtime files we need. Try launching the docker container from the directory where <a href="https://github.com/jamesandersen/aws-machine-learning-demo/blob/master/keras-deeplearning/deploy-model/build-lambda-pkg.sh">build-lambda-pkg.sh</a> resides:</p><p>docker run -it -v `pwd`:/tmp/deploy/ lambci/lambda:build-python3.6 bash /tmp/deploy/build-lambda-pkg.sh</p><p>It will start a bash shell in a container and run the script which installs Keras, Tensorflow, etc and then strips out any unnecessary bytes before creating a keras-tf-runtime.zip file with the runtime needed for deployment. Where possible, the python source is stripped out and compiled python bytecode (.pyc) is left instead to reduce the initial lambda warm-up time.</p><h3>Deploying to Lambda</h3><p>With our keras-tf-runtime.zip file created we’re almost done. We now just need to add in the actual lambda code that will grab our model from S3, load it and generate loan grade predictions from it. The handler looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1abf0979ce4d9e26cba57d39ad4a7337/href">https://medium.com/media/1abf0979ce4d9e26cba57d39ad4a7337/href</a></iframe><p>Checkout <a href="https://github.com/jamesandersen/aws-machine-learning-demo/blob/master/keras-deeplearning/deploy-model/deploy-lambda.sh">deploy-lambda.sh</a> and <a href="https://github.com/jamesandersen/aws-machine-learning-demo/blob/master/keras-deeplearning/deploy-model/lambda.template">lambda.template</a> which automate a test of the Lambda by adding handler.py into our runtime zip file, upload the zip file to S3 and then generate an API Gateway endpoint which triggers the lambda function. Finally, deploy-lambda.sh uses curl to call the API gateway function and generate predictions.</p><h3>Parting Thoughts</h3><p>A machine learning pipeline is not a trivial undertaking. Getting a well-trained model may take many train-test iterations and there is still the question of how to incorporate new data into your pipeline. On the deployment side, the lambda approach demonstrated does have a challenge with a somewhat slow “cold-start” response time of several seconds. You can mitigate this to some extent by dialing up the memory size (which also dials up the CPU capacity) but subsequent requests to a “warm” instance perform quite quickly.</p><p>The goal here is to provide an outline and some useful code/templates as a starting place for a custom machine learning model that can be deployed on the AWS cloud and incorporated into your real-world applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65d5e1d2f08e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/universal-mind/predicting-loan-grades-with-a-neural-network-a-machine-learning-pipeline-on-aws-65d5e1d2f08e">Predicting Loan Grades with a Neural Network: A Machine Learning Pipeline on AWS</a> was originally published in <a href="https://medium.com/universal-mind">Universal Mind</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Lending Rates: An Intro to AWS Machine Learning]]></title>
            <link>https://medium.com/universal-mind/predicting-lending-rates-an-intro-to-aws-machine-learning-5cada982d657?source=rss-fded36c95c1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cada982d657</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[James Andersen]]></dc:creator>
            <pubDate>Fri, 08 Sep 2017 16:03:42 GMT</pubDate>
            <atom:updated>2017-09-08T16:03:42.907Z</atom:updated>
            <content:encoded><![CDATA[<p>“Machine learning for X” is a major trend in the startup space [1]. CEOs of the largest tech companies have cited machine learning as a strategic component of their strength and future growth [2]. Jeff Bezos, while highlighting machine learning applications in Amazon’s consumer facing products, notes the “less visible” but pervasive impact on internal business processes:</p><blockquote><em>At Amazon, we’ve been engaged in the practical application of machine learning for many years now. Some of this work is highly visible: our autonomous Prime Air delivery drones; the Amazon Go convenience store that uses machine vision to eliminate checkout lines; and Alexa, our cloud-based AI assistant. … Much of what we do with machine learning happens beneath the surface. Machine learning drives our algorithms for demand forecasting, product search ranking, product and deals recommendations, merchandising placements, fraud detection, translations, and much more. </em><strong><em>Though less visible, much of the impact of machine learning will be of this type — quietly but meaningfully improving core operations.</em></strong></blockquote><blockquote><em>Jeff Bezos — </em><a href="https://www.amazon.com/p/feature/z6o9g6sysxur57t"><em>Letter to Shareholders</em></a><em> — April 12, 2017</em></blockquote><p>Let’s imagine you’re in the consumer credit business looking to grow accounts with a particular sector of the market. Savvy consumers have a myriad of choices and their key metric for discriminating among their options will be a <em>personalized</em> rate. The quicker you can provide that rate the better chance you have of converting potential applicants to customers instead of seeing them abandon you for a competitor. Perhaps your loan application process has an element of human review of applicant info and credit data before a rate can be offered to a potential customer. The delay introduced by a human review may be the difference in whether your applicants will stick around or abandon you for another alternative. A machine learning solution that predicts the appropriate rate based on data from all past applications would offer your applicants a more responsive experience and could help your conversions.</p><p>Understanding the ins and outs of selecting, applying and tuning machine learning algorithms for your business can be a daunting task. However, the AWS Machine Learning offering may be a suitable entry point for helping your business get or retain an edge. This service packages up some basic machine learning functionality in a scalable, robust solution that integrates with your existing AWS infrastructure. Let’s take a high level look at how you might use the service to build a machine learning model to predict a personalized rate for your customers in near real-time.</p><p>We’re going to use some <a href="https://www.lendingclub.com/info/download-data.action">publicly available loan applicant data</a> from Lending Club. The data set I’ve chosen contains over 420,000 loans with data such as applicant annual income, loan term, state of residence, credit score range and a number of other credit data, etc. The dataset also contains a letter grade classification of the loan in the range A — G. We’re going to use AWS machine learning to build two models, one that will predict an appropriate interest rate and a second that will infer the letter grade for the loan application. The general flow and some highlights will be presented in this article but refer to the accompanying <a href="https://github.com/jamesandersen/aws-machine-learning-demo">repo on GitHub</a> for the raw data and some additional details.</p><h3>Creating a Datasource</h3><p>AWS machine learning data sources are comma-separated (.csv) data files stored in an S3 bucket. Some integration with RedShift and RDS sources is also available but ultimately those sources will be exporting .csv files to S3. The AWS console Datasource wizard will guide you through selecting your .csv location in S3, correcting the schema it infers for you and identifying which column from your data is the “target” value that your machine learning model is going to try to predict.</p><p>After the datasource is created you’ll have access to a few descriptive statistics such as distributions of all the variables in your dataset; here’s a look at the distribution for the interest rate variable we’re trying to predict where the different loan amounts are shown on the X axis and the frequency of loans offered at each rate is on the Y axis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BqIyrb1ExJOu3Mmq.jpg" /></figure><p>Also provided are the correlation of each variable in your dataset to your target variable and warning about missing values which can negatively impact the effectiveness of your predictive model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aMJlWA9e2gfLP5Os.jpg" /></figure><h3>Data Cleaning and Feature Engineering</h3><p>Before we actually create our machine learning model, we can’t avoid the most time consuming and least enjoyable part of data science: cleaning our data [3]. In our loan data set, several variables have missing values or are not formatted so that we can use them properly. For example, our variable for “number of personal finance inquiries” (inq_fi) and “months since borrower’s last delinquency” (mths_since_last_delinq) are missing values in several rows. Replacing missing values with the mean of existing values or zero are common practices but these decisions should really be driven by knowledge of the data and business domain. For this open dataset I’ve made some judgement calls about when to replace with zero, the mean or the max value; for “number of personal finance inquiries” I’m replacing missing values with zero and for “months since borrower’s last delinquency” I’m using the max value from the dataset on the assumption that a missing value indicates there has been no delinquency and this is a continuous/numeric variable rather than categorical. We’ll take a look at how to transform certain numeric variables to categorical in the next section.</p><p>A close look at the data can also give us some ideas on additional features that might be useful in our predictive model [4] a.k.a “feature engineering”. For example, we have an earliest_cr_line variable for the month the borrower’s earliest reported credit line was opened. However, this data is in the format MMM-YYYY e.g. “APR-2011” and is treated as a categorical variable by default. It might be more useful if we presented it as a numeric “days since first credit line” variable by simply converting the month and year to a number of days prior to today. Another ratio that’s not present in the data is the proposed loan amount relative to the borrower’s income even though we have both the loan amount and the borrow income separately in the data.</p><p>This process can be iterative as we experiment with possible data transformations. The eventual outcome another data file… this time one that should be better suited for building our predictive model of loan interest rates. The cleaning work done in this step for our demo took the form of a Python script that uses <a href="http://pandas.pydata.org/">Pandas</a> to read the raw CSV file, scrub the data and save the output; it’s available in <a href="https://github.com/jamesandersen/aws-machine-learning-demo/blob/master/lending_club_clean.py">the repository</a>. At this point we’ll upload our enhanced data file to S3 and again create a Datasource using the AWS console.</p><h3>Create the Model</h3><p>With our datasource built on our scrubbed data file ready to go we’re ready to finally create a machine learning model. The AWS console walks you through the steps but we’ve got a few decisions to make beyond just selecting our datasource. AWS refers to the mix of variables, from those available in the datasource, that will be used to train the model as a “recipe” and offers a default recipe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f65wKqg8GFjfXZl-.jpg" /></figure><p>However, our loan data set, <strong>drawn from existing loans</strong>, includes some data we don’t want to incorporate into the model such as the next loan payment, whether the borrower has been late, how the principal was financed by the loan issuer, etc. <strong>We only want to use data that will be available when predicting interest rates</strong> so only applicant and credit report data is valid for use. We’re going to need to create a custom “recipe” (<a href="https://github.com/jamesandersen/aws-machine-learning-demo/blob/master/custom-model-recipe.json">see custom-model-recipe.json</a>). Check out the <a href="http://docs.aws.amazon.com/machine-learning/latest/dg/data-transformations-for-machine-learning.html">AWS docs for details on the recipe format</a>; it’s not the most straightforward and the editor in the AWS console is a little raw from a user experience standpoint but essentially the recipe consists of groups of variables you want the model to consider. There is a validation step to help identify recipe errors as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-B2Gbja2FwWPk1YG.jpg" /></figure><p>A custom recipe also allows you to use data transformations that are built into the AWS machine learning service. Here are a couple that we used in our demo:</p><ul><li><strong>normalize()</strong> — Our loan data contains some variables measured in dollars and others that are counts of open credit lines. However, comparing two applications, we know intuitively that a $10 change in a credit card balance isn’t as significant as 10 additional derogatory remarks on a credit report. The value range for these two variables are drastically different and normalize() helps the model avoid giving undue weight to variables which simply have a larger range of values.</li><li><strong>quartile_bin()</strong> — We also know that a $10 variation in the loan amount is probably not extremely influential in two otherwise equal loan applications. It may be more useful to group some of our numeric data into “bins” e.g. loans between $0 and $10K, $10K and $20K, etc and then just consider which group the application falls into. The quartile_bin() transformation creates these groups on the fly which are then treated as categorical variables rather than numeric.</li></ul><p>Next up the console will prompt for some additional training parameters such as how to divide up your data into a training set on which the model will learn to make predictions and a test set on which it will evaluate how accurate the predictions are, regularization, etc. Refer to the <a href="http://docs.aws.amazon.com/machine-learning/latest/dg/training-parameters.html">AWS training parameter docs</a> for details as discussion of these parameters is outside the scope of our demo.</p><p>Having stepped through the AWS machine learning model wizard, our newly created model will now be in a pending state for a period of time while AWS trains our model and evaluates it using the portion of our data designated as the “test set”. For the loan data set this typically took around 30 minutes.</p><p>After the training and evaluation the AWS console shows us how the interest rate predictions from our model compare with the actual interest rates from our test set. In this case, the model is “pretty good”; it predicts an interest rate that is not off by much for most of the data. It does appear to be skewed high e.g. the prediction is higher than the actual interest rate more often than not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GcxTGB1_HLNkMi-U.jpg" /></figure><p>The second model we trained for the demo attempts to predict the loan grade rather than the interest rate. In this case our model’s performance is presented as a “confusion matrix” which identifies where our model predicted the correct loan grade and where it went awry. Here the blue diagonal line is signal of the model predicting correctly most of the time. The dark orange square at the intersection of G on the left axis and F on the top axis indicates that our model <strong>incorrectly</strong> predicted a large number of G grade loans as being F. This would prompt some follow-up analysis of the data and/or discussions with domain experts who know what distinguishes between an F and a G grade. Perhaps we need additional data captured in the model or can calculate some additional features that will improve the performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5W_F9ZUYq5pZjTQQ.jpg" /></figure><p>The performance data offered here helps us determine if our model is suitable for our business needs. Are these predictions good enough for some kind of contingent loan approval that might keep customers from looking to the next option in their search results? The answer is of course a business decision but if they are not, we may need to iterate again through some analysis of the data and work to improve the quality of the model.</p><h3>Integrating our Model</h3><p>If we <strong>are</strong> at an acceptable level of predictive performance, the next step is integrating the model with our business applications and systems. There are two approaches for using our trained machine learning model.</p><ul><li><strong>Batch Predictions</strong> — We can generate predictions on a bulk set of data at once and save the results back out to S3. This option has the benefit of saving costs since we are using our AWS resources efficiently.</li><li><strong>Real-Time Predictions</strong> — In this approach our trained machine learning model is kept available for applications to invoke and make real-time predictions. For example, as a credit-seeking loan applicant perhaps I can get a real-time contingent approval based on the trained prediction of the machine learning model. Details on making real time predictions including sample request/response payloads can be found at <a href="http://docs.aws.amazon.com/machine-learning/latest/dg/requesting-real-time-predictions.html#creating-a-real-time-endpoint">Creating a Real-time Endpoint</a> in the AWS documentation.</li></ul><h3>Conclusions</h3><p>The AWS machine learning service does offer a fairly easy entry point into harness the power of machine learning for your business processes. While you won’t be spared the work of capturing and probably some amount of scrubbing your data, you do get to leverage a scalable and affordable machine learning regression pipeline and enable API endpoints that can be easily integrated with your business systems to improve their intelligence and ultimately provide better value for internal or external customers.</p><p>…</p><p><strong>References</strong></p><p>[1] <a href="http://www.cio.com/article/3145457/startups/8-tech-startup-trends-to-watch-in-2017.html">http://www.cio.com/article/3145457/startups/8-tech-startup-trends-to-watch-in-2017.html</a><br>[2] See references to machine learning in the most recent shareholder letters from <a href="https://www.microsoft.com/investor/reports/ar16/index.html">Microsoft</a> and <a href="https://abc.xyz/investor/pdf/2017_Q1_Earnings_Transcript.pdf">Alphabet</a><br>[3] Per Forbes in “<a href="https://www.forbes.com/sites/gilpress/2016/03/23/data-preparation-most-time-consuming-least-enjoyable-data-science-task-survey-says/#2858a6886f63">Cleaning Big Data: Most Time-Consuming, Least Enjoyable Data Science Task, Survey Says</a>”<br>[4] One advantage of deep neural networks are their ability to learn their own features. However, the AWS machine learning service does not currently offer a customizable deep learning service so providing some hints in terms of useful features can improve the performance of the model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cada982d657" width="1" height="1" alt=""><hr><p><a href="https://medium.com/universal-mind/predicting-lending-rates-an-intro-to-aws-machine-learning-5cada982d657">Predicting Lending Rates: An Intro to AWS Machine Learning</a> was originally published in <a href="https://medium.com/universal-mind">Universal Mind</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sudoku Solver with OpenCV 3.2 and Go]]></title>
            <link>https://medium.com/hackernoon/sudoku-solver-w-golang-opencv-3-2-3972ed3baae2?source=rss-fded36c95c1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3972ed3baae2</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[James Andersen]]></dc:creator>
            <pubDate>Tue, 18 Jul 2017 17:51:56 GMT</pubDate>
            <atom:updated>2019-05-16T10:07:50.287Z</atom:updated>
            <content:encoded><![CDATA[<p>A couple of weeks ago I had an itch to start <a href="https://hackernoon.com/tagged/learning">learning</a> Go… and OpenCV. I decided to scratch that itch by working on a Sudoku puzzle solver web app powered by OpenCV and <a href="https://hackernoon.com/tagged/go">Go</a> with a little machine learning to boot. The idea was simple enough:</p><ul><li>Upload an image and “parse” the puzzle with OpenCV e.g. find the grid and digits</li><li>Use a test set of digits from sample puzzles to train a machine learning model to identify the digits</li><li>Solve the puzzle using some constraint propagation algorithms I learned while working through the <a href="https://www.udacity.com/ai">Udacity AI nanodegree</a> program</li></ul><p>Along the way, diving into OpenCV led to cutting my teeth on C++, spending a fair amount of time understanding CGO (the bridge between Go and C/C++) and a few new nuggets of Docker knowledge. Here’s a quick demo of how it ended up:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FRHqxIRPGHIM%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DRHqxIRPGHIM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FRHqxIRPGHIM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2998c57815c6297434f7c6f07e25b9d0/href">https://medium.com/media/2998c57815c6297434f7c6f07e25b9d0/href</a></iframe><p>Read on for how it came together…</p><h3>“Parsing” Sudoku Images with OpenCV</h3><p>The current 3.x version of OpenCV exposes a C++ API so I installed the <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools">C/C++ Tools plugin</a> for Visual Studio Code and started reading sample OpenCV code. I wanted to be able to detect both “digital puzzle” images such as the one on the left and pictures of puzzles that may have some skew and poor lighting like the example on the right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*91lW1vQUaTuQldIk-yd8dg.png" /><figcaption>Original Sudoku Puzzle Images</figcaption></figure><p>I ended up with the following image processing steps:</p><p><strong>Convert to Grayscale and Resize</strong> — Subsequent steps don’t rely on color and assuming a consistent size made some of the later processing more simple</p><p><strong>Extract and “Un-warp” the Grid</strong>—The next task was detecting the Sudoku grid in the image. Supporting the “digital puzzle” images only would’ve been significantly easier but the newspaper images required more work. It started with some <a href="http://docs.opencv.org/3.2.0/d1/d79/group__photo__denoise.html#ga4c6b0031f56ea3f98f768881279ffe93">denoising</a> and <a href="http://docs.opencv.org/3.2.0/d7/d1b/group__imgproc__misc.html#ga72b913f352e4a1b1b397736707afcde3">adaptive thresholding</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*BWsvjNEG2YCkgKSJ_TA66Q.png" /><figcaption>Thresholding and Denoising Applied</figcaption></figure><p>These steps prepare for the <a href="https://en.wikipedia.org/wiki/Canny_edge_detector">Canny edge detection algorithm</a> (<a href="http://docs.opencv.org/3.2.0/dd/d1a/group__imgproc__feature.html#ga04723e007ed888ddf11d9ba04e2232de">OpenCV docs</a>) which further reduces the information in the image to just object edges like the grid we’re after.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*XCKDQq996fQeTREhkT9kDg.png" /><figcaption>Canny Edge Detection Algorithm</figcaption></figure><p>Now we can use OpenCV’s <a href="http://docs.opencv.org/3.2.0/d3/dc0/group__imgproc__shape.html#ga17ed9f5d79ae97bd4c7cf18403e1689a">findContours</a> algorithm to detect shapes in the image; the <a href="http://docs.opencv.org/3.2.0/d3/dc0/group__imgproc__shape.html#ga819779b9857cc2f8601e6526a3a5bc71">RETR_EXTERNAL</a> mode is used to limit the search to only extreme <strong>outer</strong> contours skipping any that lie <em>inside</em> other contours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*YWNI_pkHx2IXdmQ7JNV1sw.png" /><figcaption>Contour Detection (there is a single contour in the image on the left if you look close)</figcaption></figure><p>With an array of contours, which are simply lists of X/Y coordinates that “trace” the shape, the next task was to find the largest contour with the help of <a href="http://docs.opencv.org/3.2.0/d3/dc0/group__imgproc__shape.html#ga2c759ed9f497d4a618048a2f56dc97f1">contourArea</a> and then identify which X/Y coordinates are the corners of the grid by finding the outermost point in the contour within each quadrant of the area covered by the contour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*yfxMlT1G7fGlTid4mySAvA.png" /><figcaption>Detecting Perspective Transform Points for the Largest Contour</figcaption></figure><p>These corners are then used to “un-warp” the grid section of the image with OpenCV’s <a href="http://docs.opencv.org/3.2.0/da/d54/group__imgproc__transform.html#ga8c1ae0e3589a9d77fffc962c49b22043">getPerspectiveTransform</a> and <a href="http://docs.opencv.org/3.2.0/da/d54/group__imgproc__transform.html#gaf73673a7e8e18ec6963e3774e6a94b87">warpPerspective</a>. While not much has changed in the “digital puzzle”, now our newspaper photo and “digital puzzle” image are on more equal footing for subsequent processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*0b8WwSjo9OGJ1DFl0X5lQg.png" /><figcaption>Perspective Transform Applied to Detected Grid</figcaption></figure><p><strong>Eliminate Grid Lines </strong>— Before we looking for the digit regions of the image, it’s useful to get rid of the grid lines. A <a href="http://docs.opencv.org/3.2.0/d4/d86/group__imgproc__filter.html#gac342a1bb6eabf6f55c803b09268e36dc">structuring element</a> (I used 1px horizontal and vertical kernels) are passed to <a href="http://docs.opencv.org/3.2.0/d4/d86/group__imgproc__filter.html#gaeb1e0c1033e3f6b891a25d0511362aeb">erode</a> and <a href="http://docs.opencv.org/3.2.0/d4/d86/group__imgproc__filter.html#ga4ff0f3318642c4f469d0e11f242f3b6c">dilate</a> in order clean up the grid lines. <a href="http://docs.opencv.org/3.2.0/d3/dc0/group__imgproc__shape.html#ga17ed9f5d79ae97bd4c7cf18403e1689a">findContours</a> is again used but this time the contours are filtered by aspect ratio to just those that approximate horizontal and vertical lines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*0eMv7xjuhLmgzDwddUysSA.png" /><figcaption>Grid lines detected in each image (pink is just the image border)</figcaption></figure><p>Sometimes the newspaper lines were still too “curvy” or indistinct to pass as grid lines (in this implementation) as in the example here. These regions are then expanded slightly and <strong>subtracted</strong> from the image yielding the following result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*EHcdTpbLCTfmM-WQN6b3aw.png" /><figcaption>Removing Grid Lines and Denoising to Prepare for Digit Detection</figcaption></figure><p><strong>Finding Digits</strong> — Finally it’s time to detect the digit regions of the image. Once again <a href="http://docs.opencv.org/3.2.0/d3/dc0/group__imgproc__shape.html#ga17ed9f5d79ae97bd4c7cf18403e1689a">findContours</a> is used followed by another aspect-ratio filter inspired by my friend <a href="https://hackernoon.com/building-a-gas-pump-scanner-with-opencv-python-ios-116fe6c9ae8b">Kevin Kazmierczak’s article</a>. This filter allows us to skip over contours for some of the horizontal artifacts left in the newspaper image on the right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*axCOOFjflK5ZJhT_SOygWw.png" /><figcaption>Detecting Digit Regions of the Image</figcaption></figure><h3>Machine Learning with OpenCV</h3><p>Having found digit regions in the image, the next step was to identify what number was present in each digit image. I eyeballed several sample images and put together a simple csv data file of sample sudoku images and the digits they contained as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdbe5b56dc7e69634f4ac7fb47c3b9b2/href">https://medium.com/media/bdbe5b56dc7e69634f4ac7fb47c3b9b2/href</a></iframe><p>Then each sample image was fed through the “parsing” logic described earlier to find the digit regions. The center of each digit region was matched to the nearest center point of a 9x9 grid imposed on the image and then assigned a digit value based on the data in the .csv file. Each digit was then resized to a consistent size and combined into an overall “training” image where the top row contains all the “1” images, the second row contains all the “2” images, etc. This becomes our raw data to train a machine learning model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_uh0SLbs8BECcI-hx4C-0Q.png" /><figcaption>Digit regions extracted from several sample Sudoku puzzle images and combined together</figcaption></figure><p>There are plenty of digit recognition tutorials out there but I found <a href="http://www.learnopencv.com/handwritten-digits-classification-an-opencv-c-python-tutorial/">Satya Mallick’s</a> of particular value for it’s clear and detailed explanation. I adapted his approach for this project. To quickly summarize, a <a href="http://docs.opencv.org/3.2.0/d5/d33/structcv_1_1HOGDescriptor.html#a723b95b709cfd3f95cf9e616de988fc8">Histogram of Gradients Descriptor</a> (see also <a href="http://www.learnopencv.com/histogram-of-oriented-gradients/">Satya’s great explanation</a> of the HOG Descriptor) is computed for each digit image. 80% of these descriptors along with the digit label (inferred from the row in our training image) are then fed as our “observations” into <a href="http://docs.opencv.org/3.2.0/d1/d2d/classcv_1_1ml_1_1SVM.html">OpenCV’s </a><a href="http://docs.opencv.org/3.2.0/d1/d2d/classcv_1_1ml_1_1SVM.html">SVM class</a> to train the model. The trained SVM model is then used to predict the appropriate digit for the remaining 20% of the digits.</p><p>I built a <a href="https://github.com/jamesandersen/go-sudoku/blob/master/sudokuparser/cli/sudoku_parser_cli.cpp">small C++ CLI tool</a> to invoke training process and ended up with 97.73% accuracy on the <em>albeit limited</em> set of sample puzzles I gathered. The trained SVM model is saved and loaded again later for use in solving novel puzzles.</p><h3>OpenCV 3.x C++ Integration with Go via CGO</h3><p>All the work thus far was done with C++ (<em>if you look at </em><a href="https://github.com/jamesandersen/go-sudoku/tree/master/sudokuparser"><em>the code</em></a><em> be gentle, I’m a C++ newbie as of this writing</em>). Invoking this from Go turned out to be trickier than I anticipated, <em>not</em> an easy scenario for my first work in Go.</p><p><a href="https://golang.org/cmd/cgo/">cgo</a> enables Go to call C code using a special comment called a preamble to specific import of a “C” package (this import should be on a line by itself) like this. Notice that the preamble supports platform-specific values to support cross-compiling the safe codebase on different platforms e.g. darwin (my local setup) and linux (the docker container created to run this app).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a10311b4335009fa4d2ec0cff5554c09/href">https://medium.com/media/a10311b4335009fa4d2ec0cff5554c09/href</a></iframe><p>Quoting <a href="https://golang.org/cmd/cgo/">the documentation</a> (emphasis mine):</p><blockquote>When the Go tool sees that one or more Go files use the special import “C”, it will look for other non-Go files <strong>in the directory</strong> and compile them as part of the Go package. Any .c, .s, or .S files will be compiled with the C compiler. Any .cc, <strong>.cpp</strong>, or .cxx files <strong>will be compiled with the C++ compiler</strong>.</blockquote><p>That seemed simple enough but I lost time due to a couple of the points I emphasized above:</p><ul><li><strong>CGO let’s you call C code (not call C++ code)</strong> — So what’s the deal with the mention of .cpp files being compiled with the C++ compiler? Well, as a newbie to C/C++ it took me a while to understand that cgo will compile C++ that is <a href="https://isocpp.org/wiki/faq/mixing-c-and-cpp#call-cpp">referenced</a> <em>from the C code</em> that is being imported. However, you cannot directly import C++ code which means C++ types such as <a href="http://www.cplusplus.com/reference/string/string/">string</a> and <a href="http://www.cplusplus.com/reference/vector/vector/?kw=vector">vector</a> have to be converted to their C equivalent types.</li><li><strong>CGO compiles files in the same directory ONLY</strong> — My original C++ Sudoku puzzle parsing code was organized into src/ and include/ directories and my cgo preamble was trying to include a C header from a subdirectory. That did not work.</li></ul><p>I ended up with the following directory structure to get cgo properly compiling and linking my C++ OpenCV code into the imported “C” package</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Cu6duRW5z0ApUIqXPbL-g.png" /></figure><p>There were a few more notable gotchas:</p><ul><li><strong>Debugging with CGO </strong>— <a href="https://github.com/derekparker/delve">Delve</a>, the Go debugger is awesome. However, I wasn’t able get it working once I started using cgo. I couldn’t tell if it was actually supported or I just had issues. I found it easier to launch and debug the C++ code separately</li><li><a href="https://golang.org/cmd/cgo/#hdr-Passing_pointers"><strong>Watch Your Pointers!</strong></a>— Early on I was passing back a string from C++ which represented the “parsed” sudoku puzzle and getting strange garbage results intermittently. I ended up allocating C memory beforehand and passing pointers into the C code allowing it to read/write from that allocated memory. Go’s defer and C.free() ensure we free it up when we’re done. See below for an example.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e91e3a3061609f4b005569e03a2e04d7/href">https://medium.com/media/e91e3a3061609f4b005569e03a2e04d7/href</a></iframe><p>The result of this call is simply an 81 character string identifying the digits that were detected from the image:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e00b7875b7e5043bb415f1e49beec7af/href">https://medium.com/media/e00b7875b7e5043bb415f1e49beec7af/href</a></iframe><h3>Solving the Sudoku Puzzle</h3><p>Going into how to solve a Sudoku puzzle given the digits is <strong>not</strong> a primary focus of this article; if that’s what you’re after, checkout <a href="http://norvig.com/sudoku.html">Peter Norvig’s approach and explanation</a>. However, I’ll just note that the main technique is constraint propagation, where we essentially use constraints on the problem domain to limit the number of options to search. If we <strong><em>naively</em></strong> conceive of a Sudoku board as a 9x9 grid in which each cell can take a value between 1–9 then we have 9⁸¹ possible board states (over 3 billion). Of course we know there are many constraints which limit the search space:</p><ul><li>The known starting digits</li><li>Each row must contain all digits 1–9</li><li>Each column must contain all digits 1–9</li><li>etc.</li></ul><p>By applying these constraints we can drastically reduce the possible search space. Once a constraint is applied to narrow the search space we can re-evaluate other constraints to iteratively narrow in on valid values for each cell in the puzzle. Combined with a search algorithm for cases when constraints do not eliminate all possibilities, most puzzles can be solved in a few seconds or less. Check out <a href="https://github.com/jamesandersen/go-sudoku/blob/master/sudokuboard.go">sudokuboard.go</a> for the Go implementation used in this project.</p><p>In addition to the Sudoku solving code, the Go portion of the project contains some unremarkable code for serving a static directory of web content where the UI of the project lives and accepting a multipart file upload to which Sudoku puzzle images are sent. It also uses the <a href="https://github.com/nytimes/gziphandler">NY Times Gzip handler</a> to compress responses.</p><h3>Docker Deployment</h3><p>OK, so we’ve got OpenCV code to “parse” a puzzle image (passed as a byte array), we’ve integrated that with a simple Go web app that takes in a puzzle image, hands it off to be parsed by OpenCV and then solves the missing digits. Great! But where to deploy it?</p><p>The dependency on OpenCV means we do not have a self-contained binary and rules out something like the <a href="https://cloud.google.com/appengine/docs/go/">Go Standard Environment</a> on Google Cloud Platform. A containerized solution was the next logical choice so off to DockerHub…</p><p><a href="https://hub.docker.com/_/golang/">Go image</a>? ✔</p><p>OpenCV image? <a href="https://hub.docker.com/search/?isAutomated=0&amp;isOfficial=0&amp;page=1&amp;pullCount=0&amp;q=opencv+&amp;starCount=0">Plenty of ‘em</a>!</p><p>Go <strong>and</strong> OpenCV 3.x? ☹</p><p>… so I cobbled together my <a href="https://hub.docker.com/r/jamesandersen/alpine-golang-opencv3/">first contribution to DockerHub</a>, an Alpine Linux based image with Go 1.8.3 and OpenCV 3 libraries that are <a href="https://pkgs.alpinelinux.org/packages?name=opencv&amp;branch=&amp;repo=&amp;arch=&amp;maintainer=">fortunately available</a> in Alpine Linux <em>Edge. </em>There were a few difficulties here such as getting <a href="https://github.com/jamesandersen/alpine-golang-opencv3/blob/master/Dockerfile#L11-L17">symbolic links setup</a> to the version specific opencv libs but eventually this container, plus the platform specific cgo preamble seen earlier got me successfully building the app inside a docker container.</p><p>Having read Kelsey Hightower’s article on <a href="https://medium.com/@kelseyhightower/optimizing-docker-images-for-static-binaries-b5696e26eb07">tiny Docker containers for Go apps</a>, I was conscious that, while I could run my app from this image, it would be inflated because all the Go tooling was still present. Luckily for me, the Docker team added <a href="https://docs.docker.com/engine/userguide/eng-image/multistage-build/">multi-stage builds</a> in Docker 17.05 since Kelsey wrote his article and now, in a <strong>single</strong> Dockerfile I can build the app, <strong>discard the build image with SDK tools, etc.</strong> and copy the Go binary from a previous stage to a clean, lighter weight image! Great work Docker team!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea846624b3ac6b747151d3f4f416f795/href">https://medium.com/media/ea846624b3ac6b747151d3f4f416f795/href</a></iframe><p>Thanks to folks at <a href="https://hyper.sh/">Hyper.sh</a> for offering a free tier for dead-simple hosting of a docker container.</p><h3>Conclusion</h3><p>If you’ve hung in this long… thanks! I hope there’s been something valuable for you. The solver is by no means foolproof; it still has trouble with some images and either will fail to parse them or parse them incorrectly leading to failure to solve them (because it may have parsed as an invalid puzzle). The goal of course was to ramp up on some new technologies and the project has been valuable from that perspective.</p><p>The solver is live (as of this writing) at <a href="http://gosudoku.jander.me/">http://gosudoku.jander.me/</a> and <a href="https://github.com/jamesandersen/go-sudoku">source code is on GitHub</a> if you’re interested. Drop me a note if you find it useful or have any follow-up questions. Thanks!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3972ed3baae2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/sudoku-solver-w-golang-opencv-3-2-3972ed3baae2">Sudoku Solver with OpenCV 3.2 and Go</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>