<?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 Chong Jing Ting on Medium]]></title>
        <description><![CDATA[Stories by Chong Jing Ting on Medium]]></description>
        <link>https://medium.com/@chongjingting?source=rss-f96ad678856d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Gn0XLKCtfFF0rLHzBIw9_g.jpeg</url>
            <title>Stories by Chong Jing Ting on Medium</title>
            <link>https://medium.com/@chongjingting?source=rss-f96ad678856d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:24:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chongjingting/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[Two-Objective Portfolio Optimization]]></title>
            <link>https://medium.com/@chongjingting/two-objective-portfolio-optimization-6b3f0fbc9add?source=rss-f96ad678856d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b3f0fbc9add</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[modern-portfolio-theory]]></category>
            <dc:creator><![CDATA[Chong Jing Ting]]></dc:creator>
            <pubDate>Sun, 18 Sep 2022 03:51:52 GMT</pubDate>
            <atom:updated>2022-09-18T13:47:47.731Z</atom:updated>
            <content:encoded><![CDATA[<h4>Return vs Risk</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2tvj0eao8k0jlybG" /><figcaption>Photo by <a href="https://unsplash.com/@ricktap?utm_source=medium&amp;utm_medium=referral">Patrick Weissenberger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Return vs Risk</h4><p>A classic example of a two-objective optimization problem is the portfolio optimization model introduced by Harry Markowitz, a Nobel-Price-winning economist. He developed the <a href="https://www.investopedia.com/terms/m/modernportfoliotheory.asp">Modern Portfolio Theory</a>, an investment strategy that maximizes investors’ return within an acceptable level of risk.</p><p><em>Disclaimer: This article is not intended to give investment advice, but to provide an example of two-objective optimization.</em></p><p>Based on the Modern Portfolio Theory, we can find an <strong>efficient portfolio</strong> that maximizes return given risk tolerance. Alternatively, by having the desired amount of expected return, we can find an efficient portfolio that gives the least amount of risk. To explain it more intuitively, let us have a look at the return-vs-risk plot below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QPoEKst3YcPcOtjM9_jKvA.jpeg" /><figcaption>Pareto frontier of return-vs-risk, in blue</figcaption></figure><p>The blue curve in the diagram above is an example of an <strong>efficient frontier</strong> (or synonymously, a Pareto frontier). The efficient portfolios are the portfolios located at the frontier, marked in blue. Why are they efficient? If we are to maximize our return at a fixed level of risk, for example, at α, the efficient Portfolio A is the ideal portfolio for us as it is the portfolio that gives the maximum return. Choosing Portfolio C will be “inefficient” as with the same amount of risk, the expected return is lower than Portfolio A. Alternatively if we want to fix our target expected return at β, Portfolio B is the best choice as it gives the least amount of risk. Again, choosing Portfolio C will be “inefficient” because it imposes a higher risk with the same expected return as Portfolio B. Note that there is a trade-off between expected return and risk at the frontier — the higher the return, the higher the risk.</p><p><em>P.S. Feel free to look at my </em><a href="https://medium.com/@chongjingting/multi-objective-optimization-moo-1b29ece5b64f"><em>previous article</em></a><em>, in which I explained the concept of two-objective optimization, what is a Pareto frontier, and how to analyze the trade-off between two objectives.</em></p><h4><strong>Finding Efficient Portfolios</strong></h4><p>Now, let’s say that we have a long list of assets of interest, how can we find combinations of those assets that are efficient?</p><p>We can solve a two-objective return-vs-risk optimization problem using the weighted sum method. (There are other methods available, but too much to be covered in a single article!) In the weighted sum method, we combine two objectives into one by weighted sum. In each iteration, we change the weights given to each of the objectives, thus yielding different efficient portfolios. Let us formulate the problem mathematically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*u86TgY8XQWCq-XjdqHLjCA.png" /><figcaption>Model formulation</figcaption></figure><p>Note that we have added two constraints: (1) The fractions of asset allocation must sum to one, and (2) the objectives’ weights must sum to one. Also notice that if we assign a weightage of zero to one of the objectives, it becomes a single objective optimization problem. For example, if we give the weightage of zero to the risk term, we are essentially finding a portfolio that maximizes the expected return without considering the risk.</p><h4>A Peek into the Market Data</h4><p>Time to have some fun! Let us create an experiment to construct efficient portfolios using real market data. The idea of this experiment is to analyze historical price data, extract information on risk and return for each asset of interest, and then allow the optimization model to suggest a portfolio that matches our risk/return appetite.</p><p>First of all, we need data. The good news is, that we can download free historical price data from <a href="https://pypi.org/project/yfinance/">Yahoo! Finance’s API</a>. Here I have downloaded 3 years of historical daily price data from 5 different asset classes:<br>1. SPY, EEM (equities)<br>2. IGOV (bonds)<br>3. GLD (commodities)<br>4. VNQ (REITs)<br>5. BTC-USD (cryptocurrency)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*QeAeMSCprnKMPu_tY5-wdw.png" /><figcaption>Daily price data downloaded from yfinance</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QpT8urZkaP66eHelhe5Tfw.png" /><figcaption>Daily price data downloaded from yfinance</figcaption></figure><p>Next, we need to extract the risk and return information of each asset from the data we have downloaded. To quantify return, we obtain the annual expected return by taking the 3-year average on the log return.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*BPJFVVbBR74kY61Qd1pRqQ.png" /><figcaption>Log return</figcaption></figure><p>An explanation of the calculation of the log return can be found <a href="https://quantivity.wordpress.com/2011/02/21/why-log-returns/">here</a>. Then, the annual expected return values calculated are as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*vL84f_6dpTDQ0gcCPnUVQA.png" /></figure><p>We see that the BTC-USD gives the highest average return, about 20%. Hmm, should we invest all our money in BTC-USD? Imagine if we invest $1000 today, the compounding return will result in 6x more money in 10 years!</p><p>But — no investment is risk-free. Remember that often there is a trade-off between return and risk. A quick way to extract the amount of risk for each asset is to look at the distribution of the daily return and inspect its variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ttDWAvdwpzXua5XQUZ0gZA.png" /><figcaption>Return variance</figcaption></figure><p>While BTC-USD yields the highest average return, it has the highest variance. What does variance imply? Variance tells us how volatile the prices are, fluctuating up and down daily. The higher the variance, the more volatile it is. Hence, assets with higher variance in daily return are higher at risk, while assets with lower variance in daily return are lower at risk. We can say that for the past 3 years, the BTC-USD price fluctuated more aggressively than the others as seen in the comparison of the variances, hence potentially imposing higher investment risks in the future.</p><blockquote>Expected return a desirable thing and variance of return an undesirable thing. <br> — Harry Markowitz —</blockquote><h4>Not just Variance, but Covariance!</h4><p>Looking at individual variance gives us an idea of how volatile the price is. However, more interesting is the overall volatility of the entire portfolio. That being said, the relationship between the asset prices is more important — it impacts the portfolio&#39;s performance more than individual asset performance. Instead of investing in a single stock, Harry Markowitz argued that diversification has its benefit, and the performance of a single stock is not as important as its impact on the performance of the entire portfolio. This is when covariance (or we can also use correlation) comes into play, where we inspect the combined risk of asset pairs. Note that a positive covariance means the asset returns are moving in the same direction, and vice versa. For example, if asset A and asset B have positive covariance, then both asset prices generally go up or down together.</p><p>On the other hand, if assets C and D have negative covariance, their asset prices move in opposite directions. For example, a rising interest rate usually impacts bonds negatively, however, it may increase the prices of commodities and rents. If we select a combination of assets with small or even negative covariance, we can reduce the portfolio&#39;s overall risk. Let us now look at the covariance of the assets we have selected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*DRAqarbz6Rn4mE0eID7dLw.png" /><figcaption>Return covariance</figcaption></figure><p>Notice that BTC-USD &amp; SPY pair has relatively high covariance, indicating that the price movement between the two historically went up / down together. We should avoid this if we want to reduce the overall portfolio risk. In contrast, a combination like SPY and IGOV has relatively low covariance, thus more desirable.</p><h4>Example in Python</h4><p>That’s enough of an explanation, let’s code along! First, let us download the data from <strong><em>yfinance</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fad2cb9514ea8d85327e9edf39fd839d/href">https://medium.com/media/fad2cb9514ea8d85327e9edf39fd839d/href</a></iframe><p>Then, we calculate the expected annual return and covariance. Note that I have created two functions here: <strong><em>get_expected_return</em></strong> and<em> </em><strong><em>get_covariance</em></strong>. These two functions will be used later to access the return and covariance values in the optimization model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc4b7db8118166a9317942884c092060/href">https://medium.com/media/fc4b7db8118166a9317942884c092060/href</a></iframe><p>Then, we can create our optimization model using an optimization modelling library/package of choice. The example below uses the <strong><em>Pyomo</em></strong> package (my favourite!). You may compare the code below with the mathematical model I have shared in the third figure of this article. Note that in objective 2, the risk is <strong><em>negated </em></strong>— this is because we are solving a maximization problem and we want the minimized risk.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44ab1ac040cbbfb9bb0e2f34a0843704/href">https://medium.com/media/44ab1ac040cbbfb9bb0e2f34a0843704/href</a></iframe><p>Finally, we iterate through a list of varying weights, solve the optimization problem, and yield a set of <strong><em>efficient solutions, </em></strong>one from each iteration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64a74dcaf8c38a37ad3b27c57531e1c0/href">https://medium.com/media/64a74dcaf8c38a37ad3b27c57531e1c0/href</a></iframe><h4>Results</h4><p>Finally, let’s view the results! The plot below shows the return-vs-risk of the efficient portfolios we have obtained from solving the two-objective optimization problem iteratively. How beautiful! Have a look at the asset allocations at different return/risk levels — validate it against the return &amp; variance/covariance we have seen earlier. I’ll let you examine it further - hope it makes sense to you better now!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fWXQ65Ok0u-w17PBpBlnIQ.png" /></figure><h4><strong>A Little Extra</strong></h4><p>To convince you further, let me show you why our efficient portfolios are <em>efficient</em>. I have created 500 random combinations of the assets — and plotted the risk vs return with the efficient portfolios we have obtained. None of the random portfolios dominates any efficient portfolio!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*iFy5fSUKJgW7arEWMcGtjg.png" /></figure><h4>Summary</h4><p>In this article, we started with a discussion on risk and return in investments, and what an efficient portfolio means. Then, we look at how efficient portfolios can be obtained from solving a two-objective optimization problem iteratively. Finally, we created a Python script to experiment with the optimization problem. Let me know your thoughts in the comments!</p><h4>References</h4><ol><li><a href="https://www.math.hkust.edu.hk/~maykwok/courses/ma362/07F/markowitz_JF.pdf">Portfolio Selection, Harry Markowitz</a></li><li><a href="http://www.math.pitt.edu/~anitescu/TEACHING/ATKINSON/m1100new.dir/vanderbei/onlinebook.pdf">Chapter 23: Quadratic Programming. In Linear Programming: Foundations and Extensions</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b3f0fbc9add" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Objective Optimization (MOO)]]></title>
            <link>https://medium.com/@chongjingting/multi-objective-optimization-moo-1b29ece5b64f?source=rss-f96ad678856d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b29ece5b64f</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[multi-objective]]></category>
            <category><![CDATA[pareto]]></category>
            <dc:creator><![CDATA[Chong Jing Ting]]></dc:creator>
            <pubDate>Sat, 19 Mar 2022 13:38:43 GMT</pubDate>
            <atom:updated>2022-03-19T13:38:43.373Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/@chongjingting/a-simple-introduction-to-optimization-1329b82a8061">Optimization</a> is finding the best solution out of many possible solutions, in order to achieve some objective. In many real-life situations, often we have more than one objective to achieve at the same time. However, it is usually impossible to have one unique optimal solution in a multi-objective setting.</p><p>Problems like, how can we maximize return while minimizing risk in investment? Which is the fastest route to reach my destination with the minimum cost? How can I design a machine learning algorithm that gives the best accuracy while preventing overfitting? When we have more than one objective, usually we have no single best solution — we need to consider trade-offs between the objectives. This is when multi-objective optimization comes into play. In this article, I will discuss the basic concepts of multi-objective optimization. Let’s get started!</p><h4>Single-objective optimization</h4><p>Let’s assume that we have an objective to achieve, expressed by f1 below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*nRwYzEqwBzkFh9awPfSpEw.jpeg" /></figure><p>To solve min f1, we need to find the values of x1 and x2 that give the minimum of the objective function f1. The objective function is just an equation of a circle, and we can quickly identify that the best solution is x1 = 5 and x2 = 5, which gives f1 = 0.</p><h4>Two-objective optimization</h4><p>Let’s say we have another objective to achieve, to minimize f2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*o51Lc4mx3qaoJ_hA-41npA.jpeg" /></figure><p>Again, we can easily identify that the best solution is x1 = 10 and x2 = 10 which gives f2 = 0. However, if we consider the two objectives together, f1 and f2, we soon notice that no solution gives f1 = 0 and f2 = 0 at the same time. The best solution to f1 is not the best solution to f2 and vice versa. Unfortunately, we can’t have the best from both simultaneously in this case. If you find it hard to visualize, imagine that we are playing the game of archery — however, with two targets. You can’t have two bullseyes in one shot, can you?</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*pyZXbmFaH94PYke39-xBoA.jpeg" /><figcaption>A scenario where we have two objectives to achieve: min f1 and min f2</figcaption></figure><h4>A Pareto Optimal Solution</h4><p>While we can’t have one unique optimal solution, we can have a set of Pareto optimal solutions. Having a Pareto optimal solution means that we are in a situation where we can’t improve one objective without sacrificing another. In the figure below, let us look at an example of a Pareto optimal solution, point A.(I’ll explain how to get Pareto optimal solutions later on).</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*pQrwuShLonqmCDuPqko2gw.jpeg" /><figcaption>A Pareto Optimal Solution, point A</figcaption></figure><p>Standing at point A (x1 = 8, x2 = 8), we get f1 = 18 and f2 = 8. If we move our solution closer to (x1 = 5, x2 = 5), we will improve f1 but sacrifice f2. Similarly, if we move our solution closer to (x1 = 10, x2 = 10), we will improve f2 at the expense of f1. There is no other solution that improves both f1 and f2 simultaneously.</p><h4>A Non-Pareto Optimal Solution</h4><p>On the other hand, we want to avoid getting non-Pareto optimal solutions. Having a non-Pareto optimal solution means that we can still find a better solution to improve one or more objectives without sacrificing any other. Solution point B in the figure below is an example of a non-Pareto optimal solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*-233dQC01NPQxV824J9nKw.jpeg" /><figcaption>A non-Pareto Optimal Solution, point B</figcaption></figure><p>Standing at point B (x1 = 10, x2 = 5), we get f1 = 25 and f2 = 25. Notice that we can move closer to (x1 = 5, x2 = 5) and (x1 = 10, x2 = 10), and improve both f1 and f2 at the same time. This means that we can have better solutions than B. Comparing solution A (Pareto optimal) and solution B (non-Pareto optimal), we can also see that solution A is better as it gives better objective value for both f1 and f2. Note the following terminologies:</p><ul><li>Solution A is <strong>Pareto optimal</strong>. (There is no other solution where one objective can improve without sacrificing another)</li><li>Solution B is <strong>not Pareto optimal</strong>. (There exists better solution(s) where one or more objective values can improve without sacrificing another)</li><li>Solution A <strong>dominates</strong> solution B.</li><li>Solution A is a <strong>Pareto improvement</strong> to solution B.</li><li>The set of all Pareto optimal solutions is called a <strong>Pareto frontier</strong>.</li></ul><h4>Finding Pareto Optimal Solutions</h4><p>The goal of multi-objective optimization is to find (or approximate) a set of Pareto optimal solutions, use it to construct the Pareto frontier (the trade-off curve), then choose a solution that matches our preference. There are many ways to find Pareto optimal solutions. Few classical approaches are the weighted sum method and the e-constraint method. Note that we do not discuss non-convex multi-objective optimization problems here (which can involve heuristics).</p><p>Using the weighted sum method, let us try to solve our two-objective archery problem. First, we assign a weight to each objective function. Then, we aggregate the objectives into a single objective function and solve the weighted sum. The value of the weights, w, generally reflects the importance of the objectives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*uG47yiKGFwLA5fZGSWDXjw.jpeg" /></figure><p>If all the weights are equal, i.e. w1 = w2, then all the objectives have the same importance. Usually, we don’t solve the problem once, but we alter the weights systematically in many iterations to obtain a set of Pareto optimal solutions. For example, for the first iteration, we can set w1 = 0.0 and w2 = 1.0; for the second iteration, we can set w1 = 0.2 and w2 = 0.8; and so on. Then, we will get a set of Pareto optimal solutions out of the iterations with varying weights. You don’t have to solve the problem by hand — see how I solved it with Python <a href="https://github.com/jingtingchong/hobby_projects/blob/main/optimization/multiobjective_optimization_weighted_sum_example.ipynb">here</a>. Let’s skip to the good part.</p><p>After 6 iterations of varying weights, we have arrived at 6 different solutions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*N2tQGKbEJqZYTpbnERXzIg.png" /></figure><p>Plotting the solutions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*wuI0XMadgoAmPoGCe2Lmng.jpeg" /><figcaption>The 6 solutions obtained from 6 iterations of the weighted sum method</figcaption></figure><h4>Visualizing the Trade-Off</h4><p>It’s time to make a decision! Now that we have 6 solutions to choose from, we can visualize the trade-off curve, known as the <strong>Pareto frontier</strong>, by plotting the objective values of f1 and f2 we obtained in the previous step. Have a look at the figure below. Notice that moving from one solution to the other will improve one objective at the expense of another objective. Are you willing to lose more from f1 to achieve better f2? Do you want to treat both f1 and f2 equally? I’ll leave it to you to pick your final solution. Have fun exploring!</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Z9rBa4M7uVK5s0HobIKhHA.jpeg" /><figcaption>Pareto frontier constructed using the 6 solutions obtained</figcaption></figure><h4>Recap</h4><p>In this article, we discussed the concept of multi-objective optimization and looked into an example with two objectives. Then, we took a step further to understand Pareto optimality and how we can obtain Pareto optimal solutions. Finally, we visualize the trade-off curve by plotting the Pareto Frontier. In my next article, I’ll demonstrate a use case of multi-objective optimization using real-life data with Python. Too-da-loo!</p><h4>References</h4><ol><li><a href="https://www.academia.edu/36025470/INTRODUCTION_TO_OPTIMUM_DESIGN">Chapter 17: Multi-Objective Optimum Design Concepts and Methods</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b29ece5b64f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 Ways to Solve Linear Programming in Python]]></title>
            <link>https://medium.com/@chongjingting/4-ways-to-solve-linear-programming-in-python-b4af36b7894d?source=rss-f96ad678856d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4af36b7894d</guid>
            <category><![CDATA[pyomo]]></category>
            <category><![CDATA[linear-programming]]></category>
            <category><![CDATA[scipy]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[google-or-tools]]></category>
            <dc:creator><![CDATA[Chong Jing Ting]]></dc:creator>
            <pubDate>Sun, 06 Mar 2022 04:58:04 GMT</pubDate>
            <atom:updated>2022-03-10T17:08:47.038Z</atom:updated>
            <content:encoded><![CDATA[<p>SciPy | PuLP | Pyomo | Google OR-Tools</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*XW7AL2kRrftINATZZgbIhQ.png" /></figure><p>In my previous <a href="https://medium.com/@chongjingting/a-simple-introduction-to-optimization-1329b82a8061">article</a>, I have demonstrated how to solve linear programming problems using the graphical method. This article will show you how to solve linear programming problems in Python using four different open-source libraries — Scipy, PuLP, Pyomo, and Google OR-Tools.</p><p>Note: These libraries do not solve optimization problems directly. Instead, they allow us to solve optimization problems by interfacing with open-source solvers like Cbc, Glpk, HiGHS and commercial solvers like Gurobi.</p><h4>The model formulation</h4><p>Let us solve the following linear programming problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dO8iZUUliQYy6U96tsps6Q.jpeg" /><figcaption>Model formulation</figcaption></figure><h4>SciPy</h4><p>The first option is SciPy’s <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linprog.html">optimize.linprog</a>. It is quite easy to use, considering many Python users are familiar with the SciPy library. A plus point is that it interfaces with <a href="https://www.maths.ed.ac.uk/hall/HiGHS/">HiGHS</a>, a high-performance linear programming solver. However, SciPy’s linprog only solves minimization problems. Therefore, we need to provide our objective function in minimization form. To do that, we need to “flip” the sign of the coefficients of our objective function — the equivalent of maximizing 10x1 + 5x2 is minimizing -10x1 - 5x2. Note that the linprog function also does not support lower bounded constraints. Any lower bounded constraints (Ax &gt;= b) have to be reformulated (-Ax &lt;= -b). Let’s look at the code example below:</p><pre>from scipy.optimize import linprog<br><br># declare the decision variable bounds<br>x1_bounds = (0, None)<br>x2_bounds = (0, None)<br><br># declare coefficients of the objective function <br>c = [-10, -5]<br><br># declare the inequality constraint matrix<br>A = [[1,  1], <br>     [10, 0], <br>     [0,  5]]<br><br># declare the inequality constraint vector<br>b = [24, 100, 100]<br><br># solve <br>results = linprog(c=c, A_ub=A, b_ub=b, bounds=[x1_bounds, x2_bounds], method=&#39;highs-ds&#39;)<br><br># print results<br>if results.status == 0: print(f&#39;The solution is optimal.&#39;) <br>print(f&#39;Objective value: z* = {results.fun}&#39;)<br>print(f&#39;Solution: x1* = {results.x[0]}, x2* = {results.x[1]}&#39;)</pre><pre>The solution is optimal.<br>Objective value: z* = -170.0<br>Solution: x1* = 10.0, x2* = 14.0</pre><p>Hooray! The optimization terminated successfully. Hold on — our initial model is a maximization problem! Don’t forget to “flip” the sign of the objective value, -170, to 170.</p><h4>PuLP</h4><p><a href="https://coin-or.github.io/pulp/index.html">PuLP</a> is one of my favourites for solving simple linear programming problems. Unlike SciPy, PulP does not require us to provide inputs in the form of matrices or vectors. Instead, we can declare the objective function and constraints explicitly. Besides that, PuLP is more flexible than SciPy in model formulation. It supports both minimization and maximization objective functions. The constraints can also be either lower bounded or upper bounded.</p><pre>from pulp import *<br><br>model = pulp.LpProblem(&#39;linear_programming&#39;, LpMaximize)<br><br># get solver<br>solver = getSolver(&#39;PULP_CBC_CMD&#39;)<br><br># declare decision variables<br>x1 = LpVariable(&#39;x1&#39;, lowBound = 0, cat = &#39;continuous&#39;)<br>x2 = LpVariable(&#39;x2&#39;, lowBound = 0, cat = &#39;continuous&#39;)<br><br># declare objective<br>model += 10*x1 + 5*x2<br><br># declare constraints<br>model += x1 + x2 &lt;= 24<br>model += 10*x1 &lt;= 100<br>model += 5*x2 &lt;= 100<br><br># solve <br>results = model.solve(solver=solver)<br><br># print results<br>if LpStatus[results] == &#39;Optimal&#39;: print(&#39;The solution is optimal.&#39;)<br>print(f&#39;Objective value: z* = {value(model.objective)}&#39;)<br>print(f&#39;Solution: x1* = {value(x1)}, x2* = {value(x2)}&#39;)</pre><pre>The solution is optimal.<br>Objective value: z* = 170.0<br>Solution: x1* = 10.0, x2* = 14.0</pre><h4>Pyomo</h4><p><a href="https://pyomo.readthedocs.io/en/stable/index.html">Pyomo</a> is a good choice for modelling complex optimization problems. It interfaces a wide range of optimization solvers, not just limited to linear solvers. For simple LP problems, we can declare expressions explicitly like the example below. We can also generate rule-based expressions for the objective function and constraints using Python functions (not covered in this article). One disadvantage of Pyomo is that we need to install the solvers (such as <a href="https://github.com/coin-or/Cbc/releases">Cbc</a> for linear programming) before running the optimization.</p><pre>from pyomo.environ import *<br><br>model = ConcreteModel(&#39;linear_programming&#39;)<br><br># declare decision variables<br>model.x1 = Var(domain = NonNegativeReals)<br>model.x2 = Var(domain = NonNegativeReals)<br><br># declare objective<br>model.obj = Objective(expr = 10*model.x1 + 5*model.x2, sense = maximize)<br><br># declare constraints<br>model.c1 = Constraint(expr = model.x1 + model.x2 &lt;= 24)<br>model.c2 = Constraint(expr = 10*model.x1 &lt;= 100)<br>model.c3 = Constraint(expr = 5*model.x2 &lt;= 100)<br><br># solve<br>results = SolverFactory(&#39;cbc&#39;).solve(model)<br><br># print results<br>if results.solver.termination_condition == TerminationCondition.optimal: print(&#39;The solution is optimal.&#39;)<br>print(f&#39;Objective value: z* = {value(model.obj)}&#39;)<br>print(f&#39;Solution: x1* = {value(model.x1)}, x2* = {value(model.x2)}&#39;)</pre><pre>The solution is optimal.<br>Objective value: z* = 170.0<br>Solution: x1* = 10.0, x2* = 14.0</pre><h4>Google OR-Tools</h4><p><a href="https://developers.google.com/optimization">Google OR-Tools</a> is an exciting one — besides Python, it also supports other languages like Java and C++. In addition to interfacing with external solvers, Google has also developed in-house solvers such as Glop. Have a look at the example below:</p><pre>from ortools.linear_solver import pywraplp<br><br># get solver <br>solver = pywraplp.Solver.CreateSolver(&#39;GLOP&#39;)<br><br># declare decision variables<br>x1 = solver.NumVar(0.0, solver.infinity(), &#39;x1&#39;)<br>x2 = solver.NumVar(0.0, solver.infinity(), &#39;x2&#39;)<br><br># declare objective<br>solver.Maximize(10*x1 + 5*x2)<br><br># declare constraints<br>solver.Add(x1 + x2 &lt;= 24)<br>solver.Add(10*x1 &lt;= 100)<br>solver.Add(5*x2 &lt;= 100)<br><br># solve<br>results = solver.Solve()<br><br># print results<br>if results == pywraplp.Solver.OPTIMAL: print(f&#39;The solution is optimal.&#39;) <br>print(f&#39;Objective value: z* = {solver.Objective().Value()}&#39;)<br>print(f&#39;Solution: x1* = {x1.solution_value()}, x2* = {x2.solution_value()}&#39;)</pre><pre>The solution is optimal.<br>Objective value: z* = 170.0<br>Solution: x1* = 10.0, x2* = 14.0</pre><h4>Recap</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vESB9fqKYl5ViLFScd2EyQ.png" /><figcaption>Pros and cons of each method</figcaption></figure><p>This article has given examples of solving linear programming problems in Python using SciPy, PuLP, Pyomo, and Google OR-Tools. In short, SciPy’s linprog and PuLP are meant to solve linear programming problems and are relatively easy to use. Pyomo and Google OR-Tools support a wide range of optimization problems, not limited to LP problems. If you are not a fan of Python — you might prefer Google OR-Tools!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4af36b7894d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A simple introduction to optimization]]></title>
            <link>https://medium.com/@chongjingting/a-simple-introduction-to-optimization-1329b82a8061?source=rss-f96ad678856d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1329b82a8061</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[linear-programming]]></category>
            <dc:creator><![CDATA[Chong Jing Ting]]></dc:creator>
            <pubDate>Tue, 15 Feb 2022 16:15:35 GMT</pubDate>
            <atom:updated>2022-02-15T16:15:35.119Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Simple Introduction to Optimization</h3><h4>What is optimization?</h4><p>Optimization is finding the best solution out of all the possible solutions. The word “optimal” basically means “best possible”. In mathematics, we solve optimization problems by finding the maximum or the minimum of a function. “How can we maximize the profit?” “Which is the fastest route to reach the destination?” “What are the best parameters of my machine learning model?”</p><p>There are so many problems that we can solve with optimization. Exciting!</p><h4>The 4 main ingredients of an optimization problem</h4><p>Before we learn how to solve an optimization problem, we have to familiarize ourselves with its 4 main components:</p><ul><li><strong>Objective function.</strong> The objective function (sometimes called the cost function or loss function) is the mathematical function we wish to minimize or maximize.</li><li><strong>Decision variables.</strong> The decision variables are the unknown and controllable parameters of the optimization problem. We solve the optimization problem by finding the best values of the decision variables, giving us the maximum or minimum objective value.</li><li><strong>Feasible region.</strong> The feasible region is the solution space, i.e. all possible solutions are within the feasible region. The constraints of the optimization problem define the feasible region.</li><li><strong>Parameters.</strong> The parameters are the uncontrollable inputs (data) needed to identify the objective function and the feasible region.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*ZrJTdodj8v5A2chhBpeVjw.jpeg" /><figcaption>Ingredients of an optimization problem</figcaption></figure><h4>A graphical example</h4><p>There are many types of optimization problems and more ways to solve them. An optimization problem can be constrained or unconstrained, its variables can be discrete or continuous, and the equations can be linear or non-linear. Let’s start with a simple linear programming example. <a href="https://en.wikipedia.org/wiki/Linear_programming">Linear programming</a> is a technique to solve an optimization problem with linear objective function and linear constraints. (You might have learnt this in high school!)</p><p>Suppose that I have 2 assignments due soon; a math assignment and a biology assignment. Each assignment is worth 100 scores. Let’s assume that an hour spent on the math assignment allows me to gain 10 scores, and an hour spent on the biology assignment allows me to gain 5 scores. However, I only have 24 hours left to work on the assignments. How many hours should I spend on each assignment to maximize my total scores?</p><p>Now, we have all the <strong>parameters</strong> we need to formulate our problem. The <strong>decision variables</strong> are the number of hours spent on the math and biology assignments. Let the hours spent on the math assignment be x1 and the hours spent on the biology assignment be x2. Our objective is to maximize the total scores. Thus, the <strong>objective function</strong> is to maximize 10x1 + 5x2. Finally, our <strong>feasible region</strong> (all the possible solutions, also known as the solution space) is constrained by the number of hours I can spend on my assignments and the maximum scores I can achieve for each. Note that the number of hours must be non-negative. Let’s formulate our problem mathematically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*dO8iZUUliQYy6U96tsps6Q.jpeg" /><figcaption>Formulate the problem mathematically.</figcaption></figure><p>For linear optimization problems with two variables, we can solve them graphically. First, we plot the constraints on a cartesian plane and identify the feasible region. Note that the feasible region should satisfy all the constraints of our problem. The shaded region in the figure below is our feasible region, where all the points within this region are feasible solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*gYriX4i9hrXlIc7PIoc5Tg.jpeg" /><figcaption>Plot the constraints and find the feasible region</figcaption></figure><p>Next, we want to find a point within this feasible region that gives us the best objective value (remember, we want the maximum value). The solution always lies on one of the feasible region’s corner points (vertices) in a linear programming problem. It is not difficult to identify all the corner points using a <a href="https://www.desmos.com/calculator">graphing calculator</a> — let’s label them as A(0,0), B(0,20), C(4,20), D(10,14), and E(10,0).</p><p>To find the corner point which gives the best objective value, we need to plot the direction that maximizes 10x1 + 5x2. Then, we trace the direction of maximization up to the corner point furthest away from the origin. Let’s visualize it using the figure below. The red arrow shows the direction of maximization. Following the direction of maximization, we notice that corner point D(10, 14) is furthest away from the origin. Thus, it gives us the highest objective value. To verify this, we can calculate the objective value at each corner point, and we will end up with the same solution at D(10, 14):</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*lrPo0GAYLondcVEU0A8vCw.jpeg" /><figcaption>Find the corner point (vertex) that maximizes the objective function (method 1, graphically)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*yR_W5kqhEHvpq71wSQaonA.jpeg" /><figcaption>Find the corner point (vertex) that maximizes the objective function (method 2, exhaustively)</figcaption></figure><p>Based on the graphical method above, we have found the optimal value, z* =170, and the optimal solution is x* = (10, 14). It means that to obtain maximum total scores, I should spend 10 hours on the math assignment and 14 hours on the biology assignment. This will give me a total of 170 scores.</p><h4>Do we always have a unique optimal solution?</h4><p>No. Optimization problems can have a unique optimal solution, multiple optimal solutions, and unbounded or infeasible.</p><ul><li><strong>Unique optimal solution.</strong> An optimization problem with a unique optimal solution has only one optimal solution. Like the example given above, there is no other solution equally as good.</li><li><strong>Multiple optimal solutions.</strong> It is also possible for an optimization problem to have more than one optimal solution. However, using the same example above, what if my objective is only to maximize my math assignment scores? Then, our objective function would instead be max x1. If we solve the problem, we will have more than one solution. It doesn’t matter if I spend 1 hour, 2 hours, or 5 hours on the biology assignment — as long as I spend 10 hours working on the math assignment, I can achieve my objective.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*2IMxSvUzrYpV770RhWym5g.jpeg" /><figcaption>A scenario where we have more than one solution</figcaption></figure><ul><li><strong>Unbounded.</strong> If a solution is unbounded, it means that the objective value can be made infinitely large (or infinitely small for a minimization problem) without violating any of its constraints. Let us assume a scenario where there is no upper limit to the scores that I can obtain for the biology assignment, and also, there is no limit to the amount of time I can spend. Then, we can remove the constraints 5x2 ≤ 100 and x1 + x2 ≤ 24. In this case, our feasible region will be unbounded, and we can have infinitely many solutions. Furthermore, we can find a better solution for every solution — we can still find a better solution even if we allocate 100,000 hours working on the biology assignment.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*4FbOSxiC9ujV_tBcPIPMVw.jpeg" /><figcaption>A scenario where the solution is unbounded</figcaption></figure><ul><li><strong>Infeasible.</strong> An infeasible solution means that there is no solution that satisfies all the constraints. Using the same example again, suppose that I set a target to score at least 90 scores for each assignment. Then, we would have additional constraints 10x1 ≥ 90 and 5x2 ≥ 90. However, when we plot the constraints, we will realize that there is no feasible region satisfying all the constraints that we have defined. There is no way to score at least 90 scores each, given our time constraints. Thus, we do not have a feasible solution.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*wlrEt7Veu8kPl_KZp0IBEA.jpeg" /><figcaption>A scenario where there is no solution (infeasible)</figcaption></figure><ul><li><strong>Extra.</strong> Well, what if there is no time constraint? Then, we do not need the constraint x1 + x2 ≤ 24. We will have a feasible region by removing this constraint, as shown in the figure below. Congratulations, it is now possible to score at least 90 marks each! So, don’t leave your assignment till the last 24 hours if you want to get perfect scores :)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*dp0Nl5Z1LX8vSHrUu6d5PA.jpeg" /><figcaption>Another scenario with a unique optimal solution</figcaption></figure><h4>Recap</h4><p>This article discussed the 4 main components of an optimization problem — the objective function, decision variables, constraints, and parameters. We also worked on a simple linear programming problem using the graphical method. Finally, we covered scenarios where we obtain a unique optimal solution, multiple optimal solutions, unbounded solutions, and no solution (infeasible). In the upcoming articles, I will demonstrate how to solve optimization problems using Python. Stay tuned!</p><h4>References</h4><ol><li>The University of Edinburgh, MATH11111 Fundamentals of Optimization</li><li><a href="https://web.stanford.edu/group/sisl/k12/optimization/#!index.md">https://web.stanford.edu/group/sisl/k12/optimization/#!index.md</a></li><li><a href="https://en.wikipedia.org/wiki/Linear_programming">https://en.wikipedia.org/wiki/Linear_programming</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1329b82a8061" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>