<?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 Adam Davis on Medium]]></title>
        <description><![CDATA[Stories by Adam Davis on Medium]]></description>
        <link>https://medium.com/@slowandsteadybrain?source=rss-94f02f6b5f5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*o3keD-IA5nYfmpwjd1j8MA.png</url>
            <title>Stories by Adam Davis on Medium</title>
            <link>https://medium.com/@slowandsteadybrain?source=rss-94f02f6b5f5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 04:49:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@slowandsteadybrain/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[How To #12: From Natural Language to SQL: Building a Text-to-SQL System with HuggingFace]]></title>
            <link>https://slowandsteadybrain.medium.com/how-to-12-from-natural-language-to-sql-building-a-text-to-sql-system-with-huggingface-8eab541c7484?source=rss-94f02f6b5f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8eab541c7484</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[text-to-sql-generative-ai]]></category>
            <dc:creator><![CDATA[Adam Davis]]></dc:creator>
            <pubDate>Mon, 13 Oct 2025 23:32:53 GMT</pubDate>
            <atom:updated>2025-10-13T23:32:53.120Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*YPdtLWxwAuicdTyxEBVARg.png" /></figure><p>“Whenever you see a successful business, someone once made a courageous decision.” ― Peter F. Drucker</p><h3>The Problem</h3><p>Data analysts and scientists often spend significant time converting business questions into SQL queries, especially when exploring unfamiliar datasets. The challenge is twofold:</p><ol><li>Understanding the structure of a new dataset (tables, columns, data types).</li></ol><p>2. Translating a natural language question into an accurate SQL query.</p><p>To streamline this, I created a system that:</p><ul><li>Reads a CSV into a database</li><li>Generates SQL from a natural language question</li><li>Executes the SQL and returns results</li></ul><p>All powered by HuggingFace’s <strong>Llama 2</strong> model (free tier — I’m cheap).</p><h3>How It Works</h3><p>I wrapped the solution in a Python class, TextToSQLRAG. Here’s the workflow:</p><h3>1. Load Data into SQLite</h3><p>The system starts by taking a CSV and loading it into a SQLite database. This gives a structured schema to query.</p><pre>self.df = pd.read_csv(csv_path)<br>self.connection = sqlite3.connect(self.db_path)<br>self.df.to_sql(self.table_name, self.connection, if_exists=&#39;replace&#39;, index=False)</pre><p>This ensures that any CSV can be turned into a queryable database table instantly.</p><h3>2. Build the Schema</h3><p>Next, the system extracts column names and data types to generate a schema:</p><pre>CREATE TABLE data_table (<br>  cust_id INTEGER,<br>  purchase_count INTEGER,<br>  first_purchase_price REAL,<br>  ...<br>)</pre><p>This schema is sent to the language model to help it generate accurate SQL queries.</p><h3>3. Generate SQL with HuggingFace</h3><p>Using the HuggingFace <strong>Llama 2</strong> API, the system converts natural language questions into SQL:</p><pre># model is meta-llama/Llama-2-70b-chat-hf<br>response = self.client.chat_completion(<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>    max_tokens=400,<br>    temperature=0.1<br>)<br>sql = response.choices[0].message[&quot;content&quot;].strip()</pre><p>A sample input and output:</p><ul><li><strong>Question:</strong> &quot;What is the average first_purchase_price for a purchase_count of 1?&quot;</li><li><strong>Generated SQL:</strong></li></ul><pre>SELECT AVG(first_purchase_price) <br>FROM data_table <br>WHERE purchase_count = 1</pre><h3>4. Execute and Return Results</h3><p>Finally, the SQL is executed against the SQLite database, and the results are returned as a Pandas DataFrame:</p><pre>result_df = pd.read_sql_query(sql_query, self.connection)</pre><p>For example:</p><pre>Average single first purchase price: 24.96<br>Count of customer ids with purchase count of 2: 37</pre><h3>Benefits</h3><ol><li><strong>Accessibility:</strong> Anyone can query a dataset without needing to know SQL.</li><li><strong>Speed:</strong> Analysts save time translating questions into SQL manually.</li><li><strong>Flexibility:</strong> Works with any CSV and can handle complex queries.</li></ol><h3>Next Steps</h3><p>Some ideas for extending this system:</p><ul><li><strong>Multiple table joins:</strong> Generate SQL that joins multiple tables.</li><li><strong>Query optimization:</strong> Improve performance for very large datasets.</li><li><strong>Fine-tuned models:</strong> Use a smaller model specialized in SQL for faster inference.</li></ul><h3>Conclusion</h3><p>By combining a structured SQLite backend with a modern LLM from HuggingFace, I built a system that bridges the gap between natural language and SQL. This is a practical example of how generative AI can enhance data exploration and empower analysts to focus on insights rather than query syntax.</p><p>Code here:</p><p><a href="https://github.com/adavis-85/Text-to-SQL-System-with-HuggingFace">https://github.com/adavis-85/Text-to-SQL-System-with-HuggingFace</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8eab541c7484" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To #11: Hybrid Recommendation System — Online Platform]]></title>
            <link>https://slowandsteadybrain.medium.com/how-to-11-hybrid-recommendation-system-online-platform-51c477d7a515?source=rss-94f02f6b5f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/51c477d7a515</guid>
            <category><![CDATA[content-based-filtering]]></category>
            <category><![CDATA[hybrid-recommendation]]></category>
            <category><![CDATA[collaborative-filtering]]></category>
            <dc:creator><![CDATA[Adam Davis]]></dc:creator>
            <pubDate>Thu, 17 Oct 2024 18:03:18 GMT</pubDate>
            <atom:updated>2024-10-17T19:11:19.569Z</atom:updated>
            <content:encoded><![CDATA[<h3>How To #11: Hybrid Recommendation System-Online Platform</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*l3nTqdf_eFDm8IoCYrX-6A.png" /><figcaption>Factories Painting — Ginie Ruitenbeek</figcaption></figure><p>“It is not the employer who pays the wages. Employers only handle the money. It is the customer who pays the wages.” — Henry Ford</p><p><strong>Collaborative Filtering</strong></p><p>Collaborative filtering is a technique used in recommendation systems that predicts a user’s preferences based on the preferences of similar users or items. It operates on the principle that if two users agree on one issue, they are likely to agree on others as well. There are two main approaches: user-based filtering, which identifies users with similar tastes and recommends items they liked, and item-based filtering, which focuses on finding items that are similar to those a user has previously liked. This method leverages vast amounts of user interaction data to uncover hidden patterns and preferences, making it widely used in platforms like Netflix and Amazon to enhance user experience by providing personalized recommendations.</p><p><strong>Content Based Filtering</strong></p><p>Content-based filtering is a recommendation technique that suggests items to users based on the attributes of the items and the user’s past preferences. It analyzes the features of items — such as genre, director, or cast in movies, or keywords in articles — and matches them with the characteristics of items that the user has previously liked or engaged with. By focusing on the intrinsic properties of items rather than relying on the behavior of other users, content-based filtering helps create personalized recommendations tailored to an individual’s tastes. This method is particularly effective in scenarios where user data is sparse or when new items are introduced, as it relies solely on the content itself.</p><p><strong>Hybrid Filtering</strong></p><p>Hybrid filtering combines multiple recommendation techniques, typically integrating both collaborative and content-based filtering, to enhance the accuracy and effectiveness of recommendations. By leveraging the strengths of each method, hybrid filtering can mitigate the limitations inherent in using a single approach. For instance, it can address issues like the cold start problem, where new users or items lack sufficient data for reliable recommendations. By synthesizing user behavior data with item attributes, hybrid systems provide more personalized and relevant suggestions, leading to improved user satisfaction and engagement. This approach is widely used in various platforms, such as streaming services and e-commerce sites, to create a richer and more tailored user experience.</p><p>For our purposes we will combine collaborative and content based filtering into a hybrid model.</p><p><strong>Preprocessing</strong></p><p>The amazon data contains multiple entries (user ids) for each review. To be able to index a single user we’ll need to flatten these ids and also repeat the same purchases that they made.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bdcdcb4e32671a6cf873ca1e1de816c/href">https://medium.com/media/9bdcdcb4e32671a6cf873ca1e1de816c/href</a></iframe><p>This will be the data frame that we’ll index for our hybrid model. Let’s take a look at the distribution of ratings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*AeB-5SV8Ha9rxlcAE_Bszw.png" /></figure><p>Wow. Most rated the products above 4. A lot of satisfied customers.</p><p><strong>Functions</strong></p><p>Collaborative Filtering:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92882432d7507db16b1ca506e4e2f4c5/href">https://medium.com/media/92882432d7507db16b1ca506e4e2f4c5/href</a></iframe><p>Content Based:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8126d17a0f3cd4b80a4616c0445297cf/href">https://medium.com/media/8126d17a0f3cd4b80a4616c0445297cf/href</a></iframe><p>Hybrid Filtering:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca5be423e6e8f66e6e4f6ea5d9877d5c/href">https://medium.com/media/ca5be423e6e8f66e6e4f6ea5d9877d5c/href</a></iframe><p>Now to call our function to get a recommendation for our user. The amount of recommendations is kept at 10 for now.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/687e9bddeaaf5c2554a435df59854edb/href">https://medium.com/media/687e9bddeaaf5c2554a435df59854edb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*AgokJHrbHzwK7fp5YaEB5A.png" /></figure><p>One thing that could be added in here is the recommendation based off of the last purchase. We have an overall recommendation here based off of all content and all users. Most users viewed computers and accessories and that is where most recommendations are coming from.</p><p>Code available here:</p><p><a href="https://github.com/adavis-85/Hybrid-Filtering---Online-Data/tree/main">GitHub - adavis-85/Hybrid-Filtering---Online-Data</a></p><p><a href="https://medium.com/@anilcogalan/practical-guide-to-building-scalable-recommender-systems-in-python-b175547e6fce">https://medium.com/@anilcogalan/practical-guide-to-building-scalable-recommender-systems-in-python-b175547e6fce</a></p><p><a href="https://www.kaggle.com/datasets/lokeshparab/amazon-products-dataset?select=Amazon-Products.csv">https://www.kaggle.com/datasets/lokeshparab/amazon-products-dataset?select=Amazon-Products.csv</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51c477d7a515" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to #10: What To Do With Average Treatment Effects and Data]]></title>
            <link>https://slowandsteadybrain.medium.com/how-to-10-what-to-do-with-average-treatment-effects-and-data-4ce2a483dd59?source=rss-94f02f6b5f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ce2a483dd59</guid>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[harabasz-calinski]]></category>
            <category><![CDATA[causal-inference]]></category>
            <dc:creator><![CDATA[Adam Davis]]></dc:creator>
            <pubDate>Thu, 17 Oct 2024 16:56:42 GMT</pubDate>
            <atom:updated>2024-10-20T00:10:01.203Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*TVKPSzbcmtQ7lNCnkOHHMw.png" /><figcaption><em>The Manneport,</em> 1883 — Claude Monet</figcaption></figure><p>“A good impression is lost so quickly.” — Monet</p><p>In #9 of this How To series I showed how to find the average treatment effect of an intervention on subjects. What to do with that data? How would we segment our groups in order to study who would be affected the most from said intervention? Let’s explore.</p><p>On the tail end of our analysis we have the upper and lower bound of each treatment effect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*bPkm0gYwNcIHdzHh468w0w.png" /></figure><p>How could these treatment effects be best grouped? We’ll test out Kmeans and Harabasz-Calinski clustering.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a14168ce56cca558b89e9b6c6656eec5/href">https://medium.com/media/a14168ce56cca558b89e9b6c6656eec5/href</a></iframe><p>We have the original dataset concatenated to the ATE. The elbow test over time has been proven to not always work. That’s where Harabasz-Calinski comes in. We have a score per grouping and basically pick the greatest score and that is the amount of groups that we have. For our data we have the following chart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*AIUhjmeHWogew8oBxVIw7g.png" /></figure><p>We see that we have the highest score at two clusters. The chart is similar to what one would see for a standard Kmeans with elbow included. This chart also tracks according to our ATE as is is non-linear and is almost appearing as an exponential function. Let’s visualize the two clusters on our ATE vs. our data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa74b0502e21ae08a2862ffc1743121c/href">https://medium.com/media/fa74b0502e21ae08a2862ffc1743121c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*gaBN3QhVSvN884By6rIf5A.png" /></figure><p>We can see that there is a defined grouping. It appears that the slope changes for the blue cluster. Let’s take a look at another parameter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*thGy2omPn49042hAqcOxiw.png" /></figure><p>Still a clear division.</p><p>The last step would be to do some data analysis on these defined groups and see where and why they differ. The ultimate goal is to provide valuable insights and take the analysis a step beyond simply saying that the intervention has a causal effect or not.</p><p>Code available here:</p><p><a href="https://github.com/adavis-85/Deep-IV-and-CausalForestDML-Example-Notebook/blob/main/Causal%20Forest%20Demo%20with%20Clusters%20-%20KMeans%20and%20Harabasz%20Calinski.ipynb">Deep-IV-and-CausalForestDML-Example-Notebook/Causal Forest Demo with Clusters - KMeans and Harabasz Calinski.ipynb at main · adavis-85/Deep-IV-and-CausalForestDML-Example-Notebook</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ce2a483dd59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To # 9: Causal Inference Methods-DeepIV against Causal ForestDML]]></title>
            <link>https://slowandsteadybrain.medium.com/how-to-9-causal-inference-methods-deepiv-against-causal-forestdml-403d833f0a55?source=rss-94f02f6b5f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/403d833f0a55</guid>
            <category><![CDATA[causal-forest]]></category>
            <category><![CDATA[econml]]></category>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[deepiv]]></category>
            <dc:creator><![CDATA[Adam Davis]]></dc:creator>
            <pubDate>Mon, 09 Sep 2024 17:58:58 GMT</pubDate>
            <atom:updated>2024-09-09T17:58:58.220Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*QaiLSHyy87BVkd24W5pdEQ.png" /><figcaption>Casting Sand Spun Pipes — David Ghilchik 1940</figcaption></figure><p>“Art is not what you see, but what you make others see.”- Edgar Degas</p><p>Everyone can copy and paste some generic code but few know what to truly do with the results of the code. In the real world most datasets are not normalized and there isn’t always a positive correlation with data that fits distributions. Using someone’s code isn’t horrible but due some due diligence and learn how to actually <strong>use</strong> it.</p><p>Professionally I am a data scientist. I’m working on causal inference examples for our data science team built off of analyzing training taken by users and their pre and post training scores. As said above there isn’t a positive correlation and that is fine: but what will we do with that information? It doesn’t stop at spitting out numbers. We have to prove it to a reasonable statistically sound degree. Here I will show some examples of what I have used with a perfect distribution but delve deeper into what the results mean instead of regurgitating code as most tutorials do.</p><p>I first analyzed with DoWhy to see what estimand I would need (past post). Estimator reccomended instrument variable but I needed to know what the treatment effect was for each user. I found the below model that uses two neural networks, one for the treatment and one for the outcome.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c9570e3834c23823a3d938868f05bbc/href">https://medium.com/media/4c9570e3834c23823a3d938868f05bbc/href</a></iframe><p>This data was random and normalized so should work at each stage. Using this as more of a pipeline for possible analysis.</p><p>We can see that the conditional average treatment closely fits the train dataset. What this can be used for is future predictions as long as the confounders are fit with the training. The double neural networks fit the data well and discover the causal effect well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cac30a48186e06e58bda421139c0ae9/href">https://medium.com/media/8cac30a48186e06e58bda421139c0ae9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*7TTI4XOtomwK8ruuWDnyPg.png" /><figcaption>Comparison of CATE to outcome</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*wFsS9SKfy7sU7_W2oxNuxQ.png" /><figcaption>Prediction against outcome</figcaption></figure><p>When analyzing the summary for both the OrthogonalForest algorithm and the CausalForestDML algorithm its evident that the distributions are fairly tight. The ‘point_estimate’ is the ATE or ATT depending on where it is getting read. The ‘ci_lower’ and ‘ci_upper’ are the confidence intervals for each treatment affect. These are stored as their own arrays for easier visualization as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*a579INwTUAZj6Z3C_HVXJQ.png" /><figcaption>summary of algos</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*2Qxf1KVbpvPxbXDDbs1W6g.png" /><figcaption>estimate against true</figcaption></figure><p>After the models learn the causal effect of the treatment on the outcome along with the confounders and controls, new predictions can be made with new controls. The way to look at these charts is to think of the ‘x’ array as different possible controls be they floats or ints. The treatment on the vertical axis is the possible treatment effect that would be given to each specific control. The treatment effect is the average of the possible effects on the outcome having taken ‘treatment’ or not. This can also be visualized with the following charts with fewer different controls. Above controls were from 0–1 and bottom is 0–5. There is a separate treatment for each control entry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*MLSWWFYA5vM4mXNmvZFqhA.png" /></figure><p><a href="https://github.com/adavis-85/Deep-IV-and-CausalForestDML-Example-Notebook">https://github.com/adavis-85/Deep-IV-and-CausalForestDML-Example-Notebook</a></p><p><a href="https://github.com/py-why/EconML/blob/main/notebooks/Causal%20Forest%20and%20Orthogonal%20Random%20Forest%20Examples.ipynb">https://github.com/py-why/EconML/blob/main/notebooks/Causal%20Forest%20and%20Orthogonal%20Random%20Forest%20Examples.ipynb</a></p><p><a href="https://towardsdatascience.com/causal-ml-for-data-science-deep-learning-with-instrumental-variables-96e5b7cc0482">https://towardsdatascience.com/causal-ml-for-data-science-deep-learning-with-instrumental-variables-96e5b7cc0482</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=403d833f0a55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to #8: Multi-treatment and optimal policy with EconMl and DoWhy]]></title>
            <link>https://slowandsteadybrain.medium.com/how-to-8-multi-treatment-and-optimal-policy-with-econml-and-dowhy-eb30bac11718?source=rss-94f02f6b5f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb30bac11718</guid>
            <dc:creator><![CDATA[Adam Davis]]></dc:creator>
            <pubDate>Thu, 22 Feb 2024 21:05:09 GMT</pubDate>
            <atom:updated>2024-02-24T20:53:34.148Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*KEd_dUN2SZswtjMzI3WMCQ.png" /><figcaption>Claude Monet. Vétheuil en été, 1879</figcaption></figure><p>“I’m hard at it, working stubbornly on a series of different effects, but at this time of the year the sun sets so fast that it’s impossible to keep up with it” — Claude Monet</p><h3><strong>Breakdown:</strong></h3><p>Building off of the previous entry of the How To series, we take a look at using multiple treatments or investments. The goal would be to maximize the potential revenue for the hotel which is the room rate multiplied by the total stay. The treatments will be allowing the deposit to be refundable as well as a discount of 10% of their room rate.</p><p>As this is from a previous project I will include what is specific to this problem. The code is at the bottom of the article.</p><p>Treatments and outcome with heterogeneous variable/s:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91a52f10aa4122fe47b0c58c92104f23/href">https://medium.com/media/91a52f10aa4122fe47b0c58c92104f23/href</a></iframe><p>Let’s see the average lead time average for each treatment combination:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*uUZwURD_BuYm5W0hhcVdxw.png" /></figure><p>Next is to encode the multiple treatments into one array:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d0c31a5da0aec37f5d62e4d7d217ba1/href">https://medium.com/media/6d0c31a5da0aec37f5d62e4d7d217ba1/href</a></iframe><p>Following to set the model as well:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/445c66cad184cbebfef633b327f2aa03/href">https://medium.com/media/445c66cad184cbebfef633b327f2aa03/href</a></iframe><p>The resulting graph created with DoWhy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*_5xpkz7monAGH7DwwCa5zw.png" /></figure><h3><strong>Treatment Plan:</strong></h3><p>It is up to us to create a treatment plan. This could be a flat fee or credit that we give to both the refund and discount. This is essentially the cost to the business of instituting each treatment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b71e2397bae016fef14dbb8dc2640693/href">https://medium.com/media/b71e2397bae016fef14dbb8dc2640693/href</a></iframe><p>The cost of the refund or not goes off of the previous cancellations. As it is a negative value it is a penalty to the customer based off of the amount of cancellations that they have. No previous cancellations, no penalty. Each one is $10. The discount for the customer is 10% off of their total charge. A way to visualize this is we are giving them 10% of their room charge back to them. This comes from the average total charge.</p><p>We can see the allocations of the optimal treatment plan:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*RGE5_Om22fZ0cseRLzPX0Q.png" /></figure><p>We can see that most have only Discount as a strategy followed by Refund &amp; Discount followed by Refund_Status in third. The metrics to test the robustness of the model are the same as previously so they will not be listed here.</p><h3><strong>To End:</strong></h3><p>Using both EconMl and DoWhy enables us to more closely find the causal effects of a causal model without using solely regression methods. The end output for this method is how to best treat the customers to maximize our revenue. We have the data of booked guests who have not paid yet. We have their information on the type of hotel as well as if they have previous cancellations as well. Who received the discount as well as the refund status.</p><p>The point of the model learning from the data is to gauge the effect of the treatments of the penalty on the cancellations and the discount on the total charge. This can allow us to look at who was recommended for which treatment and better understand that group as well. This depends on the business needs.</p><p><a href="https://github.com/adavis-85/Multi-treatment-and-optimal-policy-with-EconMl-and-DoWhy">GitHub - adavis-85/Multi-treatment-and-optimal-policy-with-EconMl-and-DoWhy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb30bac11718" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to #7: A/B testing with DoWhy and EconML]]></title>
            <link>https://slowandsteadybrain.medium.com/how-to-7-a-b-testing-with-dowhy-and-econml-fa90825b404d?source=rss-94f02f6b5f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa90825b404d</guid>
            <category><![CDATA[dowhy]]></category>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <dc:creator><![CDATA[Adam Davis]]></dc:creator>
            <pubDate>Mon, 12 Feb 2024 18:54:27 GMT</pubDate>
            <atom:updated>2024-09-07T01:26:51.611Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How to #7: A/B testing with DoWhy and EconML</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*7RlcCnvaLQXSHZtekvTrgg.png" /></figure><p>“It is not knowledge, but the act of learning, not possession but the act of getting there, which grants the greatest enjoyment.”-Carl Frederich Gauss</p><p>Causal inference allows us to draw conclusions about data. It can help us to know how groups would respond to treatment by measuring the potential impact on the outcome of an experiment. A/B testing is one area of causal inference where two groups are compared. One group receives a certain treatment and the other is the control group which receives no treatment. The outcomes of each are measured and a conclusion is drawn.</p><p><strong>Background</strong></p><p>Normally for an A/B test a trial or experiment is completed prior to the test. This can get a little costly as the cost of treatment can increase each at scale. Using an intent to treat strategy can help alleviate the need to apply treatment to as many subjects. Intent to treat uses an instrumental variable that is applied to a random segment of the population; i.e. not everybody gets it.</p><p>This experiment deals with data from a hotel group and contains points such as room rate, length of stay and the type of hotel or resort. The experiment is as follows:</p><p>We want to see if giving someone the ability to refund their deposit causes them to become a repeat guest (re-book) and the effect that has on the average length of stay.</p><p>Instrumental variable is the refundable deposit.</p><p>Treatment is becoming a repeat guest.</p><p>Outcome is the length of stay.</p><p>Confounding variables in this case is the guest previously cancelling, how many previous bookings not cancelled as well as the type of hotel or resort. The impact once found out can be fine-tuned through closer analysis on where the split happens for treatment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*iGeRAHvtVCwZz_1MYD3eUQ.png" /><figcaption>Causal Graph of Model</figcaption></figure><p>First to select the model parameters. Three models are needed as we are using three variables:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f00ca210b2f20c1bf001cb46bb27e169/href">https://medium.com/media/f00ca210b2f20c1bf001cb46bb27e169/href</a></iframe><p>Next to initialize and fit the model, identify the estimand and visualize the models performance on the test set. This will give us the conditional average treatment:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04ca96fe0ebc29ee14be1548c6ae72bd/href">https://medium.com/media/04ca96fe0ebc29ee14be1548c6ae72bd/href</a></iframe><p>The estimate for the CATE is 4.57 or an increase in 4.57 days stayed by guests on average. We don’t know what confounding variables have an effect on this but first we will need to refute the accuracy of this estimate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*_QgF2F_u85v7RDDLSWnSRQ.png" /><figcaption>Coefficients Results Table for Model</figcaption></figure><p><strong>Refutation</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7ca8c563804ff65e5c35ff4724a58a2/href">https://medium.com/media/a7ca8c563804ff65e5c35ff4724a58a2/href</a></iframe><p>The goal of refutation is to confirm the accuracy of the CATE that the model has found. Output of these in this case are as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57703b7352af5e15bb0d7439bc3eefc1/href">https://medium.com/media/57703b7352af5e15bb0d7439bc3eefc1/href</a></iframe><p>We can see that the estimates are close to the original. One way to get them closer is to increase the number of simulations for each refuter. If the p values of all are consistently under .05 then the hypothesis that giving a customer a refundable ability for their deposit can be rejected. We would be able to assume that keeping deposits non-refundable could ultimately increase the number of stays stayed.</p><p><strong>Policy Interpretation</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cb5ff0bfa4b5dbd3f8dfa7589006390/href">https://medium.com/media/4cb5ff0bfa4b5dbd3f8dfa7589006390/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*cIpdF9lSROd9AFJpdRCCZA.png" /><figcaption>Model Uncertainty Graph</figcaption></figure><p>Tree interpreter shows which segment should have the strongest possible impact on the outcome.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c082f7293d7ef77a8e047343f24e0d26/href">https://medium.com/media/c082f7293d7ef77a8e047343f24e0d26/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*D3iEwX2JZO6v575LggU5Cw.png" /><figcaption>Policy for Treatment Effect</figcaption></figure><p>The policy interpreter states the results if the predicted treatment effect is applied to each class. We can see that the segment that could use more analyzation are hotels that aren’t CityHotels. It’s important to remember that the point of this test is to see if a first time guest can add more value than repeated guest. Depending on what is most important to the business different metrics can benefit others more.</p><ul><li><a href="https://github.com/adavis-85/Causal-Inference-using-DoWhy-and-EconML-for-Repeat-Hotel-Guests-A-B-Test-/tree/main">GitHub - adavis-85/Causal-Inference-using-DoWhy-and-EconML-for-Repeat-Hotel-Guests-A-B-Test-</a></li><li><a href="https://www.kaggle.com/datasets/jessemostipak/hotel-booking-demand">Hotel booking demand</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa90825b404d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to #6: Solving an imbalanced multi-commodity transportation problem]]></title>
            <link>https://slowandsteadybrain.medium.com/how-to-6-solving-an-imbalanced-multi-commodity-transportation-problem-5d9aa7f51762?source=rss-94f02f6b5f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d9aa7f51762</guid>
            <category><![CDATA[transportation-problem]]></category>
            <category><![CDATA[minimization]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[shipping]]></category>
            <dc:creator><![CDATA[Adam Davis]]></dc:creator>
            <pubDate>Fri, 23 Jun 2023 19:08:22 GMT</pubDate>
            <atom:updated>2023-06-23T19:08:22.394Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*gI0H2ojQfFGzvsCTfKKc-A.png" /><figcaption><em>The Gare St-Lazare</em> -Claude Monet</figcaption></figure><p>“I have such a desire to do everything, my head is bursting with it.” — Monet</p><p>In the field of operations research there is a common situation to get past known as a transportation problem. The problem starts with a group of locations with a demand of a product that is held in supply at a group of suppliers. The goal generally is to minimize the amount of time that it takes for the demanded products to come from the suppliers to the end locations. This seen as the “cost” to minimize, which can be either money or time.</p><p>This article is on solving a multi-commodity which means multiple different products sent from the supplier to the locations with orders. In this case one of the main purposes is to remove the need for explicitly programming the demand greater than the supply or vice versa. The model should be able to adjust itself accordingly. This was written in Python with PuLP as it is a standerd linear program which lends itself well to using PuLP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*JvMpVsAq_B7nWnsu7riisw.png" /><figcaption>Example of possible cost of shipping to destination from supplier</figcaption></figure><p>A dummy variable is needed for supply if demand is greater than supply. A dummy variable is needed for demand if supply is greater than demand. A good way to think about this is by having an extra supplier and destination be inventory or a category to let the destination know to order more product and in what amount.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*-FCm50bIvE3c4WoAmrNeiQ.png" /></figure><p>This will make sense in reverse: the DEST variable if short of supply in a category will then enter the remaining product amount needed as “Order_More”. Conversely if a supplier has extra unused supply in a category that will appear in the results as “Inventory”. A sample of each is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9304bd4e4a6c9e7a516b358089fb0158/href">https://medium.com/media/9304bd4e4a6c9e7a516b358089fb0158/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/003f409bd968b8501ec4aa1f623fd411/href">https://medium.com/media/003f409bd968b8501ec4aa1f623fd411/href</a></iframe><p>This is achieved by solving the problem in the standard way in PuLP:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*44BLRayzHb8udXVCtqnmog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*iL1CzgmxTUPSlcITVni5eg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*6DogumIJhQzsOkES7D5k_g.png" /></figure><p>By using two dummy variables both possible imbalanced cases are handled. The “Order_more” supplier will then show up for each destination if the supply needed is more for any good that demand exists. The “Inventory” variable then also shows what supply there still exists left over.</p><p>Another aspect of this is the way that the end results will be disseminated . A possibility is to have one csv file for each destination and also one for all the suppliers in case there is inventory left over. Code is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*mg4SvEy_Rqaz8gmfKIK8Sg.png" /></figure><p>The above will out put the preceding tables showing for each destination as well as the amount needed to order by each separate destination of each separate product as well as the possible inventory per supplier per product if there is any.</p><p><a href="https://github.com/adavis-85/Imbalanced-Multi-commodity-Transportation-Problem">GitHub - adavis-85/Imbalanced-Multi-commodity-Transportation-Problem</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d9aa7f51762" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to #5: 3D Bin Packing]]></title>
            <link>https://slowandsteadybrain.medium.com/how-to-5-3d-bin-packing-89e1fed3eaf0?source=rss-94f02f6b5f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/89e1fed3eaf0</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[3d-bin-packing]]></category>
            <category><![CDATA[operations-research]]></category>
            <dc:creator><![CDATA[Adam Davis]]></dc:creator>
            <pubDate>Mon, 12 Jun 2023 06:27:40 GMT</pubDate>
            <atom:updated>2024-10-20T00:30:21.203Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*XrfrucnB3d_7CP8ROLWZDA.png" /><figcaption>Composition in Red, Blue and Yellow — Piet Mondrian</figcaption></figure><p>“The rhythm of relations of color and size make the absolute appear in the relativity of time and space” — Piet Mondrian</p><p>Optimization and operations research is a complex field. It’s one thing to want to know how to improve a business or process but it is another to put a business problem together using mathematics. Bin packing is a common area of operations research by where a container of items are fit into one or more containers in such a way as to minimize unused space. One dimensional bin packing can be seen as fitting items with the same width but differing heights into one container. This is normally a part of solving a larger problem. Two dimensional bin packing reimagines the first problem in two dimensions usually dealing with the base of an item without the height taken into effect. This is useful for metal cutting to cut an arbitrary amount of items from a sheet of metal. The final is a three dimensional bin packing. This uses both one dimensional and two dimensional bin packing . Items can be grouped into layers by and then the layers fit into an appropriate container.</p><p>3D bin packing is an NP hard problem. There could be a trade off or a point where the given results are “good enough” and the problem can bee seen as solved. The sources for the algorithms are from two papers by the same authors [1] and [2]. The first algorithm used is “Height first-Area second”(page quote). The algorithm has two parts:</p><p>1. Partition the items into clusters by non-increasing height and then construct optimal bins using a 1D bin packing problem.</p><p>2. The items are then re-sorted by non-increasing base area (width by depth) and a second solution is obtained using a 1D bin packing problem.</p><p>The optimal solution is then chosen as the minimum bins used for the items between the height sorted and area sorted.</p><p>The algorithm in [2] gives a partition percentage of possibly 0.75 which was used in the code. This partition value determines the way that the items are partitioned into clusters. This number can be thought of as a continuous lower bound. After partitioning the layers are constructed to minimize the amount of layers by implementing a 2D bin problem. The 2D problem is explained in depth by [1] but is as follows:</p><p>1. Sort the items by non-increasing height.</p><p>2. Place the items with the first at the bottom left corner of the container.</p><p>3. Add items sharing an edge as close as possible to the right edge of the container</p><p>4. Place the next item on the minimum height item with the right edge touching the right edge of the container.</p><p>5. Place items sharing edges consecutively until none can fit or the left edge of the last item touches the left edge of the container with it’s left edge.</p><p>6. Alternate placing items left to right and right to left until none can be placed in either direction.</p><p>7. Start a new bin if necessary.</p><p>As the layers are built in two dimensions the next step is to optimally stack the layers in bins in such a way to minimize the overall amount of bins used. This is done using a simple 1D bin packing problem written with PuLP and Python. The problem is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*g3KjDDKpiC8H5hqemU5LpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*7hPKBVl7N9CBjBbqLPnmhA.png" /></figure><p>The choice was made to print out the layers in folders by each bin. Again both the height and base area are used to complete the problem and the solution with the minimum amount of bins is chosen as a solution. A layer is a 2D representation of the items sorted by width and then put through the Alternating Directions algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*4Mfx3gHa71gFxM423D946g.png" /></figure><p>The results can be tailored to a specific situation if needed. A 3D representation would only be needed to visualize the clusters and layers in each bin. Two dimensional was chosen as the layers can be built easier. The labeled layers for each bin are then saved in a pdf which bears the bin number.</p><p>Code:</p><p><a href="https://github.com/adavis-85/3D-Bin-Packing">GitHub - adavis-85/3D-Bin-Packing</a></p><p>[1] A. Lodi, S. Martello, D. Vigo,<br><em>Recent advances on two-dimensional bin packing problems</em>,<br>Discrete Applied Mathematics,<br>Volume 123, Issues 1–3,<br>2002,</p><p>[2] A. Lodi , S. Martello, D. Vigoet , <em>Heuristic algorithms for the three-dimensional bin packing problem</em>, European Journal of Operational Research 141 (2002) 410–420, 2000</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89e1fed3eaf0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HOW TO #4: MULITPLE SHOOTING WITH DIFFEQFLUX.JL]]></title>
            <link>https://slowandsteadybrain.medium.com/how-to-4-mulitple-shooting-with-diffeqflux-jl-9ec91fd838d7?source=rss-94f02f6b5f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ec91fd838d7</guid>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[julialang]]></category>
            <category><![CDATA[diffeqflux]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[differential-equations]]></category>
            <dc:creator><![CDATA[Adam Davis]]></dc:creator>
            <pubDate>Wed, 01 Feb 2023 07:22:02 GMT</pubDate>
            <atom:updated>2023-04-10T13:20:41.114Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to #4: Multiple Shooting Training with DiffeqFlux.jl</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*FV2QZGx3leire1n1-04RIQ.png" /><figcaption>Jackson Pollock — Number 1, 1949</figcaption></figure><p><em>“There is no accident, just as there is no beginning and no end” — J. Pollock</em></p><p>On this part 4 of the How To series, I’m diving deep into the topic of multiple shooting. Multiple shooting is training data is split into overlapping intervals which are then trained in tandem to join these overlaps. This can be extremely helpful when data has visual evidence of some oscillation. Here it is fit to a common Hare and Lynx population dataset to see if we can solve for the oscillation and predict what the population of each could be over time.</p><p>DiffeqFlux is an extremely useful way to use differential equation solvers fit to neural networks to in turn approximate data. Multiple shooting is also a part of DiffeqFlux and can also handle differential equation solvers. Multiple shooting is helpful because it allows for a solver to break out of a local minima and to approximate data that is non-linear or noisy.</p><h3>DATASET:</h3><p>This started as needing a better way to approximate data using Julia. I had read the attached paper by Steven Frank on using Multiple Shooting to solve for approximations to forecast future population levels. He had written his own loss functions and most of the code and only used DiffeqFlux to solve the model. I am using an example of multiple shooting for a simple ODE and instead of generating data from a known ODE, I’m using the Hare and Lynx dataset which is attached at the end of this post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*oTp-BfOXl4uJEl0C5D8LYw.png" /><figcaption>Populations from 1845 to 1935</figcaption></figure><p>The populations don’t always follow the same rules so there is a bit of noise in the data. Smoothing is a great way to deal with some of the noise. I followed Steven’s lead on first taking the log of the data and de-meaning it. After this it is then fit to a cubic spline for each layer for a little more smoothness. The model is trained on 60 years/time steps of the data. This is then tested later on against the last 30 years which are the test set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*Pvew3IHnYHNxRZXvgV9_dQ.png" /></figure><p>Not all functions will be shown here as they are rather long. A link to the code is at the end as well as the dataset and Mr. Frank’s paper.</p><p>An important aspect of using DiffeqFlux to remember is that you don’t need to use a standard ODE to generate your data. If you have data to use then that can be handled in the loss function generally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*GcOTm1IoN-oCeqzDRMnrHg.png" /></figure><p>Above the group_size stands for the amount of points attached to each separate neural network in the multiple shooting objective. The continuity_term is the penalizing amount for each step of the optimization and is smaller in this case as there are more groups and many small penalizations may add up to one large one and could keep the model from converging optimally. The solver used is the AutoTsit5(Rosenbrock23()) as I left the default tolerances as-is.</p><p>The neural network architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*ulE2ny-60D5OFHwmXuXyyw.png" /></figure><p>The nn is initialized with random parameters that will be trained later on. The training functions are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*TeXZqk5JfOfm16hWpwLlsw.png" /></figure><p>These optimization problems/solver train the model.</p><h3><strong>RESULTS:</strong></h3><p>Results of the solver can be visualized as following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*INRJPxYZl6eqH9J1dBAFLQ.png" /></figure><p>The solver is set to solve with the optimal parameters that provided the minimum loss from training. The term “set_tsteps” tell the new solver to save the prediction at each single step which is each year data was provided for.</p><p>The training set for the model is the first sixty years solved for at 3 month timesteps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*rrzwBQ2pQLL7GMXDj8FFdA.png" /><figcaption>NN approximation of training set for Hare</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*us65E1v_HsO-pW4HtGFYmw.png" /><figcaption>NN approximation for Lynx</figcaption></figure><p>The solver was able to approximate the data fairly well. It is not perfect but perhaps many more iterations would also help the training along. As for the predicted levels:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*DpYiUQumO1Dhx2MKVtr3xQ.png" /><figcaption>Trained and forecasted Hare</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*WkrSou5HdcTeDRTtFGHq3A.png" /><figcaption>Trained and forecasted Lynx</figcaption></figure><p>We can see that the model was able to reproduce a fairly accurate approximation of the next thirty years of the model. This was with a 66/33 percent split for training to compare a longer prediction window. It is visible in the first 60 years that the data is not absolute and certain years increase faster or decrease or do not have a sharp drop off as other years. More data possibly for climate or possible important local events might help to better explain why the populations don’t always line up together. The model learns the general ebb and flow from the data. To follow the training the optimal parameters for the nn are then able to fit to a solver to make the predictions from above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*dFLYj0z92xrnzSE67cGTTQ.png" /></figure><h3><strong>CONCLUSION:</strong></h3><p>This was an example of how to use common multiple shooting algorithms that are fit to custom data. We will not always know that there is a relationship present in our data and instead would like to find out if there is one. Using neural networks to solve for differential equations can greatly improve our accuracy of approximations. The algorithms and solvers would be suitable for other data as well. The first step is to know the data well enough to know if this is the right procedure to use or not. After that, the sky’s the limit.</p><ul><li><a href="https://github.com/adavis-85/Hare-Lynx-Multiple-Shooting-with-DiffeqFlux">GitHub - adavis-85/Hare-Lynx-Multiple-Shooting-with-DiffeqFlux</a></li><li><a href="https://docs.sciml.ai/DiffEqFlux/stable/examples/multiple_shooting/">Multiple Shooting</a></li><li><a href="https://github.com/evolbio/FitODE/blob/unified/input/lynx_hare_data.csv">FitODE/lynx_hare_data.csv at unified · evolbio/FitODE</a></li><li><a href="https://arxiv.org/abs/2204.07833">Optimizing differential equations to fit data and predict outcomes</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ec91fd838d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to #3 : Tree Optimization for XGBoost.]]></title>
            <link>https://slowandsteadybrain.medium.com/how-to-3-tree-optimization-for-xgboost-ee8a7eb6f8c2?source=rss-94f02f6b5f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee8a7eb6f8c2</guid>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[matisse]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Adam Davis]]></dc:creator>
            <pubDate>Mon, 16 Jan 2023 22:20:43 GMT</pubDate>
            <atom:updated>2023-01-16T22:20:43.971Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to #3 : Tree Optimization for XGBoost.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*HmQ3zMUUzBVQslRMTSJjkg.png" /><figcaption>Henri Matisse. The Codomas (Les Codomas), 1943</figcaption></figure><p>“Exactitude is not truth” — Henri Matisse</p><p>How do we know that XGBoost is training correctly? Is there a way to visualize what it is scoring as it is training? Short answer is, yes.</p><p>Typically visualizing training and test accuracy, AUC or f-scores during training/testing is left up to neural networks or Tensorflow. It is expected and knowing the amount of iterations (epochs) is very helpful. We are able to tell if our model needs more training or if it will still predict effectively with fewer epochs.</p><p>If no maximum estimator, or trees to be used, are specified the algorithm is set to 100 estimators. We are able to set the estimators ourselves. This can be helpful to break through possible local minima or maxima. There is also an early stopping metric that can be set as well where if a score doesn’t change for a specific number of metric the training terminates. Either would work in this situation depending on what is needed. Here we are trying to maximize the AUC (area under the curve).</p><h3><strong>Setting up the training:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*rqJIvJPWRbioSSwfOqP_lg.png" /></figure><p>We first do a standard split for our pre-processed data of 30% for testing. The model is only trained on the specific training data that we allotted for of 70% total data. The training and test sets are combined so that the metric is visible during the amount of estimators that we have chosen which is 1,000. The output of this will be similar to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*PM3F4MhJb1IfrEwg-s2CeA.png" /></figure><p>Validation_0-auc is the AUC of the training data and the other is the test data evaluated at each specific tree during training. The results of this training are able to be indexed as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*fXPAjdBT3Pxrx4Z2hOHrew.png" /></figure><p>The resulting plot of the training cycle of the 1,000 estimators:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*LMLJvty40x88EoabpM8YJA.png" /></figure><p>It is visible that more estimators don’t equal an improvement in our AUC. In this case the fewer the better. As the cycle is able to be indexed the maximum AUC on our test set is able to be given:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*_57iCvnCUIkDeTIo0yiYtw.png" /></figure><p>Training is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*DPU_8nK-1VUb-CT9lSOG1Q.png" /></figure><p>Only seven trees were needed to effectively train our model. We can then view the metrics through a confusion matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*L7deWdFHj68pb5DkNp6x-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*5pJW67sC33WHPZSYwiR5tA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*9qf3T_vUJ_tQrrN4oby6QQ.png" /></figure><p>Accuracy could of course be better though is not always the best metric for binary classification. In this case we will use our f score for desired metric. Most out of the box algorithms will have a .5 threshold in probability of belonging to one class or not for binary classification problems. It is possible to affect the predictions by tuning this probability threshold as well.</p><h3><strong>Tuning threshold probability:</strong></h3><p>The probability threshold will be checked 1,000 times between 0 and 1 in intervals of .001. Each specific metric (AUC, accuracy and f-score) is tabulated at each iteration so the threshold can be chosen which produces the maximum metric possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*pec0nbe3m6q9dQx14FWUGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*VUgCDEpHZ82zGVV9dlPGVg.png" /><figcaption>Maximum of each metric</figcaption></figure><p>In this case we will choose the threshold of .267 to maximize our f score. The following code does that as well as displays the resulting confusion matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*VVTPMJ8aMirAflbrZ3GHbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*Od6M3iwIIve5g0afrP2rLw.png" /></figure><p>This improves the model. The f score is improved almost two full percentage points. We can see that the negative case was predicted almost perfectly while the positive class has 84% accuracy. This would be a good starting point to think about a direction to proceed and how the model is able to be used. Ideally we would like to have 100% accuracy but that is highly unlikely. As we would like to maximize our positive cases that is one of the most important. We can see that the actual positive cases were predicted at almost 100%. A majority of the actual negative cases however were predicted incorrectly. This is still an improvement. Without this model all cases would essentially be counted as positive. We are able to handle a little bit of negative cases to go along with our positive cases as long as the model is able to predict the negative cases with a high accuracy. The metrics are up to the user and can be adjusted according to what saves the most resources.</p><p><a href="https://github.com/adavis-85/XGBoost-Estimator-Optimization">GitHub - adavis-85/XGBoost-Estimator-Optimization</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee8a7eb6f8c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>