<?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 Sayali Dalvi on Medium]]></title>
        <description><![CDATA[Stories by Sayali Dalvi on Medium]]></description>
        <link>https://medium.com/@dalvisayali97?source=rss-3af8c5eb4615------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qpQTiLV5aR2y1T74MXsxlg.jpeg</url>
            <title>Stories by Sayali Dalvi on Medium</title>
            <link>https://medium.com/@dalvisayali97?source=rss-3af8c5eb4615------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:48:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dalvisayali97/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[Neural Networks from Scratch in Python]]></title>
            <link>https://medium.com/@dalvisayali97/neural-networks-from-scratch-in-python-9caa2b4b726d?source=rss-3af8c5eb4615------2</link>
            <guid isPermaLink="false">https://medium.com/p/9caa2b4b726d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[math]]></category>
            <dc:creator><![CDATA[Sayali Dalvi]]></dc:creator>
            <pubDate>Thu, 11 May 2023 22:33:02 GMT</pubDate>
            <atom:updated>2023-05-11T22:33:16.317Z</atom:updated>
            <content:encoded><![CDATA[<h3>Neural Network from Scratch in Python</h3><p>Understanding the Math!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*n1LaAXd3TQlTchN5JjPfzA.png" /></figure><p>Neural networks are powerful machine learning models that have revolutionized the field of artificial intelligence. A neural network can be thought of as the functional unit of deep learning, which mimics the behavior of the human brain to solve complex data-driven problems. They can be used to solve a wide range of problems, including image and speech recognition, natural language processing, and predictive modeling. But how do the neural networks actually work? Do they really mimic our brain neurons?</p><p>In this article, we will talk about the basic construction of neural networks and learn how mathematics helps this wonder actually become a reality.</p><h3><strong>Intuition</strong></h3><p>Let’s say that you are learning a new sport. Firstly, you will take the beginner&#39;s training and get familiar with the basic rules of the sport. Similarly, a neural network is also trained based on the basic parameters and dataset given to it. This is called “<strong>Feed Forward</strong>”.</p><p>Now once your training is done, your coach makes you play a game. During your first game, you actually understand how the game should be played by observing other players and yourself. You evaluate the gameplay by spotting the differences between your actions and those of other players, who are actually skilled at the sport. Similarly, our neural network also calculates how far our prediction is from the actual result and tries to correct it by adjusting the parameters. This is called “<strong>Back Propagation</strong>”, where performance evaluation and error correction are done.</p><p>Lastly, you will become a pro player only by practicing the game. Our neural network also repeats this iterative process of feedforward and backpropagation until it predicts the output correctly. So the ultimate goal is to minimize the error and increase the accuracy by training continuously.</p><p>Just like a beginner athlete who practices and repeats their movements until they become automatic, a neural network needs to be trained on a large dataset repeatedly to learn patterns and relationships between inputs and outputs.</p><h3>The Network</h3><p>A neural network is composed of multiple layers of interconnected neurons. By stacking multiple layers of neurons together, a neural network can learn to model complex functions that map input data features to output predictions. Let’s try to predict the output of an XOR gate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*afUlZh-rPP_XOi4JBwyqvA.png" /><figcaption>XOR Gate Input</figcaption></figure><h3>The Architecture</h3><p>Consider the below neural network. It contains an input layer, 1 hidden layer and an output layer. The input layer contains 3 neurons, the hidden layer contains 4 and the final output layer contains a single neuron.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*bvGxacDBssy78fq0WNKt5w.png" /><figcaption>2 Layer Neural Network</figcaption></figure><h3>1. Neurons</h3><p>Every neuron is a mathematical function that accepts inputs and produces an output that is passed on to other neurons in the next layer. The output is produced based on certain parameters called weights and biases. The input to each neuron is the weighted sum of datapoints and the bias 𝑊𝑥+𝑏. Let’s define a class with these basic components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jmzhz3FHFO_Zw7P4ECrJ7A.png" /><figcaption>Neuron</figcaption></figure><h3>2. Weights and Biases</h3><p>Weights define the importance or contribution of that particular feature to the output. They can be thought of as the parameters of our data model. We have 2 sets of weights, one between the input layer and the hidden layer, and another between the hidden layer and the output layer.</p><pre>class NeuralNetwork:<br>    def __init__(self, x, y):<br>        self.input      = x<br>        self.weights1   = np.random.rand(self.input.shape[1],4) <br>        self.weights2   = np.random.rand(4,1)                 <br>        self.y          = y<br>        self.output     = np.zeros(y.shape)</pre><h3>3. Activation Function</h3><p>An activation function is a mathematical function that is applied to the output of a neuron in a neural network. There are several activation functions like sigmoid, hyperbolic tangent, and ReLu and the choice depends on the nature of the problem. We will use the <em>sigmoid</em> function in our example. It turns out to be a good approximation of the real activation function in human neurons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCsWUisYbHehrlb-gKUQGA.png" /><figcaption>The sigmoid function</figcaption></figure><pre>def sigmoid(x):<br>    return 1.0/(1+ np.exp(-x))</pre><h3>4. Feedforward</h3><p>If the input is 𝑥, the output ŷ of a simple 2-layer Neural Network like the one above is, for each of our two layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*D-79OA23b-CnKWANd-eyzw.png" /><figcaption>2 layer feed forward equations</figcaption></figure><p>Here, 𝑦1 is the output of first layer which is being passed as an input to the second layer. <strong>W1 and W2</strong> are the weights and <strong>b1 and b2</strong> are the baises. Combining the two equations above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*eksiFSTzA-Ntq5up8s5_nA.png" /></figure><p>But these variable aren’t just numbers. Here we are dealing with vectors and matrices. In order to code these equations, let’s understand the <strong>dimensions</strong>.</p><ul><li>Input layer: (3,1) — XOR inputs</li><li>Weights 1: (3,4) — They lie between the input layer having 3 neurons and the hidden layer having 4 neurons</li><li>Weights 2: (4,1) — They connect from hidden laye rwith 4 neuron to the output layer with single neuron</li><li>Bais 1: (4,1) — This bias is applied on the hidden layer with 4 neurons</li><li>Bias 2: (1,1) — It is applied on the output layer with one neuron</li></ul><pre>def feedforward(self):<br>        self.layer1 = sigmoid(np.dot(self.input, self.weights1))<br>        self.output = sigmoid(np.dot(self.layer1, self.weights2))</pre><p>Nice! We have built the basic training network. Well done! Now it’s time for to know and rectify the wrong learnings, error correction.</p><h3>5. Loss Function</h3><p>The loss function, also called the cost function, is a mathematical function that measures the difference between the predicted output of a neural network and the actual output, also known as the ground truth. It evaluates the performance of the model and indicates the adjustments to be made in weights and biases to increase the accuracy. The goal is to find the optimum set of weights and baises in order to minimize the loss function. The choice of loss function depends on the category of the problem. Here, we’ll use a simple <strong>sum-of-squares</strong> error as our loss function: The sum-of-squares error is simply the sum of the difference between each predicted observation 𝑦̂ and the actual observation 𝑦. The difference is squared, so that we measure the <em>absolute value</em> of the difference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*jZhz0PUW21lIXJiObukwPw.png" /><figcaption>The Loss function</figcaption></figure><h3>6. Backpropagation</h3><p>Here comes the important step! Now we that we have our measure of the goodness of predictions, which is the loss function, we will update the weights and biases with the goal of minimizing the error. For this, we will take the derivative (<strong>gradient descent</strong>) of the loss function with respect to weights and baises. The gradient descent gives the slope of the function and tells us how far we are from the minima. So we will update our weights (and biases) thusly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*ZtwwODZz9AOBDT-cPY8hQA.png" /><figcaption>Weights and biases updation</figcaption></figure><p>where ∂ is the partial derivative and L=Loss(𝑦,𝑦̂ )</p><h3>7. The Math!</h3><p><strong>Updating the Weights: </strong>Since we have <em>two</em> sets of weights, we need <em>two</em> derivations of Loss(𝑦,𝑦̂):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*uyBKEvgw3DkTmCTp244BJQ.png" /></figure><p>The Loss function is dependent on y and 𝑦̂ and not on the weights. But y and 𝑦̂ are itself functions of weights. So we can rewrite the equations as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3DuOmJ0MP_1XSCB-uu05zA.png" /></figure><p>Let’s solve for the common term first,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_RET51u1eDe5EIORfJGzdg.png" /></figure><p>Substituting this and the equations for 𝑧 and 𝑦̂ we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R_TtrZGgJYt2fL5CTAkA0g.png" /></figure><p>In order to take the derivatives, we will apply the chain rule. The chain rule is stated as: 𝑑/𝑑𝑥[𝑓(𝑔(𝑥))] = 𝑓′(𝑔(𝑥)) ∗ 𝑔′(𝑥)</p><p>So with the change of variable 𝑊2→𝑞:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*al1OiY4SFy6KXN2tgIGn7w.png" /></figure><p>So the first equation becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*3i6VtFR6g_WqQ8SlofRFmg.png" /><figcaption>Derivative of Loss function wrt W2</figcaption></figure><p>Similarly, changing variable 𝑊1→𝑞:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HA3O4vV4pv40mtOnRIz1MA.png" /></figure><p>And the second equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*unQ0to_cnURt2dVY2WJtkA.png" /><figcaption>Derivative of Loss function wrt W1</figcaption></figure><p><strong>Updating the Biases: </strong>Similarly we have <em>two</em> biases to adjust</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*etuwEeczgHBL9HgX6MjldA.png" /><figcaption>Updation for Biases</figcaption></figure><p>We can rewrite the equations as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*m5ueReX77cwTkfhpCUvgZg.png" /></figure><p>Solving for individual terms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vSypt3GpS7LRgiXV4H2J6A.png" /></figure><p>As previously calculated, we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fg5CQ65R7bD69BgCE-pRUA.png" /></figure><p>So the first equation becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*loTDLFi2-tOuTp400DK9Mw.png" /><figcaption>Derivative of Loss wrt b2</figcaption></figure><p>And the second equation becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*nJZH_YddVs75IoXm__2HDQ.png" /><figcaption>Derivative of Loss wrt b1</figcaption></figure><p>Whoosh! That was a lot of complicated math! Congrats! We are done with the difficult part. Now, let’s add the backpropagation function to our python code.</p><pre>#function to calculate the deivative of sigmoid activation function<br>def sigmoid_derivative(x):<br>    return sigmoid(x) * (1.0 - sigmoid(x))<br><br>def backpropagation(self):<br>        # application of the chain rule to find derivative of the loss function with respect to weights2 and weights1<br>        sigmoid_derivative_1 = self.sigmoid_derivative(self.z1) #sigma&#39;(W1 x + b1)<br>        sigmoid_derivative_2 = self.sigmoid_derivative(self.z2) #sigma&#39;(W2 z + b2)<br>        d_weights2 = np.dot(self.layer1.T, <br>                            (2*(self.y - self.output) * sigmoid_derivative_2))<br>        d_weights1 = np.dot(self.input.T,  <br>                            np.dot(2*(self.y - self.output) * sigmoid_derivative_2, self.weights2.T) * <br>                            sigmoid_derivative_1)<br><br>        # update the weights<br>        self.weights1 += d_weights1<br>        self.weights2 += d_weights2<br>        <br>        d_bias2 = np.sum((2*(self.y - self.output) * sigmoid_derivative_2), axis=0)<br>        d_bias1 = np.sum((np.dot(2*(self.y - self.output) * sigmoid_derivative_2, self.weights2.T)), axis=0)<br><br>        # update the biases <br>        self.bias1 += d_bias1<br>        self.bias2 += d_bias2</pre><h3>8. Training</h3><p>Let’s put everything together into a class and train our neural network</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>class NeuralNetwork:<br>    def __init__(self, x, y):<br>        self.input      = x<br>        self.weights1   = np.random.rand(self.input.shape[1],4) <br>        self.bias1      = np.random.rand(4) <br>        self.weights2   = np.random.rand(4,1)<br>        self.bias2      = np.random.rand(1)                            <br>        self.y          = y<br>        self.output     = np.zeros(self.y.shape)<br><br>    def feedforward(self):<br>        self.z1     = np.dot(self.input, self.weights1) + self.bias1<br>        self.layer1 = self.sigmoid(self.z1)<br>        self.z2     = np.dot(self.layer1, self.weights2) + self.bias2<br>        self.output = self.sigmoid(self.z2)<br>        return self.calculate_loss()<br>        <br>    def reload(self, x):<br>        self.input = x<br>        <br>    def predict(self):<br>        return self.output<br>    <br>    def calculate_loss(self):<br>        return (self.y - self.output) ** 2<br>    <br>    def sigmoid(self,x):<br>        return 1.0/(1+ np.exp(-x))<br>    <br>    #function to calculate the deivative of sigmoid activation function<br>    def sigmoid_derivative(self,x):<br>        return self.sigmoid(x) * (1.0 - self.sigmoid(x))<br><br>    def backprop(self):<br>        # application of the chain rule to find derivative of the loss function with respect to weights2 and weights1<br>        sigmoid_derivative_1 = self.sigmoid_derivative(self.z1) #sigma&#39;(W1 x + b1)<br>        sigmoid_derivative_2 = self.sigmoid_derivative(self.z2) #sigma&#39;(W2 z + b2)<br>        d_weights2 = np.dot(self.layer1.T, <br>                            (2*(self.y - self.output) * sigmoid_derivative_2))<br>        d_weights1 = np.dot(self.input.T,  <br>                            np.dot(2*(self.y - self.output) * sigmoid_derivative_2, self.weights2.T) * <br>                            sigmoid_derivative_1)<br><br>        # update the weights with the derivative (slope) of the loss function<br>        self.weights1 += d_weights1<br>        self.weights2 += d_weights2<br>        <br>        d_bias2 = np.sum((2*(self.y - self.output) * sigmoid_derivative_2), axis=0)<br>        d_bias1 = np.sum((np.dot(2*(self.y - self.output) * sigmoid_derivative_2, self.weights2.T) * <br>                            sigmoid_derivative_1), axis=0)<br><br>        # update the weights with the derivative (slope) of the loss function<br>        self.bias1 += d_bias1<br>        self.bias2 += d_bias2</pre><p>We are training on XOR dataset. So our X and y will be as below:</p><pre>X = np.array([[0,0,1],<br>              [0,1,1],<br>              [1,0,1],<br>              [1,1,1]])<br>y = np.array([[0],[1],[1],[0]])</pre><p>Let’s Train !!!</p><pre>nn = NeuralNetwork(X,y)<br>for i in range(1500):<br>    nn.feedforward()<br>    nn.backprop()<br>print(nn.output)</pre><h3>Results</h3><p>Let’s look at the final prediction (output) from the Neural Network after 1500 iterations. Predictions after 1500 training iterations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*hRgGGTYlcxzvitvOnhrU1A.png" /></figure><p>Congratulations, you now have a fully functional, 2-layer neural network for a binary classification task.</p><p>You can find the entire running code <a href="https://github.com/Dalvisayali/Neural-Network-from-scratch"><strong>here</strong></a>.</p><p>Thanks to <strong>Professor Dino</strong> for giving me this understanding and being supportive!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9caa2b4b726d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Weighted Interval Scheduling Problem]]></title>
            <link>https://medium.com/@dalvisayali97/weighted-interval-scheduling-problem-8117eecb521a?source=rss-3af8c5eb4615------2</link>
            <guid isPermaLink="false">https://medium.com/p/8117eecb521a</guid>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[job-scheduling]]></category>
            <dc:creator><![CDATA[Sayali Dalvi]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 00:30:53 GMT</pubDate>
            <atom:updated>2023-04-25T00:30:53.403Z</atom:updated>
            <content:encoded><![CDATA[<p>Job Scheduling</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3ya0Z_9-72Ovfdz9" /><figcaption>Photo by <a href="https://unsplash.com/@giorgiograni?utm_source=medium&amp;utm_medium=referral">Giorgio Grani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Interval scheduling is a specific type of scheduling problem where a set of tasks, each with a start and end time, need to be scheduled on a resource with limited capacity. The goal is to select the maximum number of non-overlapping tasks that can be scheduled on the resource. This problem is also known as the “maximum number of intervals” or “activity selection” problem.</p><h3><strong>The Problem</strong></h3><p>The <em>Weighted Interval Scheduling Algorithm</em> is a dynamic programming algorithm that solves the interval scheduling problem with weights. In addition to the start and end times of each interval, each interval also has an associated weight or value. The goal of WIS is to find a subset of non-overlapping intervals that maximizes the total weight or value.</p><h3><strong>The Solution</strong></h3><p>The basic idea behind WIS is to sort the intervals by their end times and then recursively compute the maximum weight that can be obtained by including or excluding each interval in the sorted list. Specifically, for each interval <em>i</em>, we compute the maximum weight that can be obtained by either including i or excluding <em>i</em>. The maximum weight for the entire set of intervals is then the maximum weight obtained by including or excluding the first interval in the sorted list.</p><h3><strong>The Algorithm</strong></h3><p>The algorithm works by constructing a table of optimal solutions for subproblems. Let OPT(j) be the maximum total weight that can be achieved by selecting a subset of non-overlapping intervals from I1, I2, …, Ij. The table can be computed using dynamic programming as follows:</p><ol><li>Initialize OPT(0) = 0.</li><li>For each interval Ij in the input set, compute OPT(j) as follows:</li></ol><ul><li>Find p(j) which is the largest index i &lt; j such that fi ≤ si. If no such index exists, set p(j)= 0.</li><li>Set OPT(j) = max{wi + OPT(p(j)), OPT(j-1)}</li></ul><p>3. The optimal solution is given by OPT(n).</p><p>The time complexity of the algorithm is O(n²) due to the nested loop used to find the largest index i. However, the algorithm can be optimized using binary search to find i in O(log n) time, reducing the overall time complexity to O(n log n).</p><h3><strong>The Example</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fTmzLuBxfHvoMaE2kQNnYg.png" /><figcaption>Job intervals</figcaption></figure><p>Let’s fill in the values in the table for each interval. We have filled in the weights or profits of each interval. Note that the intervals are already sorted according to their finish times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cfsqNQfPQd8l5BG5BvvGRA.png" /></figure><p>We will calculate p(j) by looking at the last non-overlapping interval before j. From the 1st to the 3rd interval, there are no previous non-overlapping intervals. For j=4, we see that the last non-overlapping interval is 1, for j=4 it is 2. Let’s complete the p(j) values in a similar manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X1b6p9ZgfdI40C7SAe7kkA.png" /></figure><p>Next, we will fill the OPT(j) values using the below formula:</p><p><strong>OPT(j) = max{ Wj + OPT(p(j)) , OPT(j-1) }</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5SxZVZ8thfQew0emQ-XOGg.png" /></figure><p>Finally, we will use backtracking to find the optimal set of intervals that maximize the weights or profits. First, find the optimum OPT(n) yielding the highest weights or profits, which is OPT(8) in our example.</p><ol><li>We pick interval j if wj + OPT(p(j)) ≥ OPT(j-1) and proceed to p(j)th interval</li><li>Else we ignore j and proceed to OPT(j-1)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rbKCLTk5AM_1A1nC2xqSDA.png" /></figure><p>Hence we get the optimal set of {1,6} with the maximum weight/profit of 8.</p><h3><strong>The Implementation</strong></h3><p>The input will be a list of intervals, where each interval will be a tuple of (start_time, end_time, weight).</p><p>We will find the p(j) values using bisect, a variant of binary search. Given a sorted sequence seq and a value x, the bisect.bisect(seq, x) function returns the index in seq where x should be inserted to maintain the sorted order. If x is already in seq, the function returns the index of the rightmost occurrence of x.</p><pre>import bisect<br><br>seq = [1, 2, 4, 5, 6]<br>index = bisect.bisect(seq, 3)<br>seq.insert(index, 3)<br>print(seq)  # output: [1, 2, 3, 4, 5, 6]</pre><p>As we want to find the index of the finish time which is less than the start time, we will use bisect and then subtract one to get the previous index. If there is no such index, it will return -1.</p><pre>def previous_intervals(self):<br>    # all start times<br>    start = [task[0] for task in self.I]<br>    # all finish times<br>    finish = [task[1] for task in self.I]<br>    p = []<br>    for i in range(len(self.I)):<br>        idx = bisect.bisect(finish, start[i]) - 1<br>        p.append(idx)<br>     return p</pre><p>Next, we will write a function to compute the OPT(j) using recursion.</p><pre>def compute_opt(self, j):<br>    if j == -1:<br>        return 0<br>    # if OPT is already calculated, reuse it <br>    elif (0 &lt;= j) and (j &lt; len(self.OPT)):<br>        return self.OPT[j]<br>    else:<br>        # max(Wj + OPT(p(j)), OPT(j-1))<br>        return max(<br>            self.I[j][2] + self.compute_opt(self.p[j]), self.compute_opt(j - 1)<br>        )</pre><p>Finally, to find the optimal set, we will backtrack using the below function</p><pre>def find_solution(self, j):<br>    if j == -1:<br>        return<br>    else:<br>        # compare Wj + OPT(p(j)) with OPT(j-1)<br>        if (self.I[j][2] + self.compute_opt(self.p[j])) &gt; self.compute_opt(j - 1):<br>            self.solution.append(self.I[j])<br>            # proceed to p(j)<br>            self.find_solution(self.p[j])<br>        else:<br>            # proceed to j-1<br>            self.find_solution(j - 1)</pre><p>Below is the final function to perform the scheduling which returns the maximum weight or profit and the optimal set of intervals.</p><pre>def weighted_interval(self):<br>    if len(self.I) == 0:<br>        return 0, self.solution<br>    # calculate p(j)<br>    self.p = self.previous_intervals()<br>    # calculate OPT(j)<br>    for j in range(len(self.I)):<br>        opt_j = self.compute_opt(j)<br>        self.OPT.append(opt_j)<br>    <br>    self.find_solution(len(self.I) - 1)<br>    # return the last OPT as it is the maximum and solution in reverse order<br>    return self.OPT[-1], self.solution[::-1]</pre><p>Putting it all together in a single class!</p><pre>import bisect<br><br><br>class WeightedIntervalScheduling(object):<br>    def __init__(self, I):<br>        self.I = sorted(I, key=lambda tup: tup[1])  # (key = lambda tup : tup[1])<br>        self.OPT = []<br>        self.solution = []<br><br>    def previous_intervals(self):<br>        start = [task[0] for task in self.I]<br>        finish = [task[1] for task in self.I]<br>        p = []<br><br>        for i in range(len(self.I)):<br>            # finds idx for which to input start[i] in finish times to still be sorted<br>            idx = bisect.bisect(finish, start[i]) - 1<br>            p.append(idx)<br><br>        return p<br><br>    def find_solution(self, j):<br>        if j == -1:<br>            return<br><br>        else:<br>            if (self.I[j][2] + self.compute_opt(self.p[j])) &gt; self.compute_opt(j - 1):<br>                self.solution.append(self.I[j])<br>                self.find_solution(self.p[j])<br><br>            else:<br>                self.find_solution(j - 1)<br><br>    def compute_opt(self, j):<br>        if j == -1:<br>            return 0<br><br>        elif (0 &lt;= j) and (j &lt; len(self.OPT)):<br>            return self.OPT[j]<br><br>        else:<br>            return max(<br>                self.I[j][2] + self.compute_opt(self.p[j]), self.compute_opt(j - 1)<br>            )<br><br>    def weighted_interval(self):<br>        if len(self.I) == 0:<br>            return 0, self.solution<br><br>        self.p = self.previous_intervals()<br><br>        for j in range(len(self.I)):<br>            opt_j = self.compute_opt(j)<br>            self.OPT.append(opt_j)<br><br>        self.find_solution(len(self.I) - 1)<br><br>        return self.OPT[-1], self.solution[::-1]<br><br> if __name__ == &#39;__main__&#39;:<br>     # They are labeled as:  (start, end, weight)<br>     t1 = (0,3,3)<br>     t2 = (1,4,2)<br>     t3 = (0,5,4)<br>     t4 = (3,6,1)<br>     t5 = (4,7,2)<br>     t6 = (3,9,5)<br>     t7 = (5,10,2)<br>     t8 = (8,10,1)<br>     I = [t1,t2,t3,t4,t5,t6,t7,t8]<br>     weightedinterval = WeightedIntervalScheduling(I)<br>     max_weight, best_intervals = weightedinterval.weighted_interval()<br>     print(&#39;Maximum weight: &#39; + str(max_weight))<br>     print(&#39;The best items to take are: &#39; + str(best_intervals))</pre><h3>The Time Complexity</h3><p>The weighted interval scheduling algorithm can be implemented using a sorted list of intervals, sorted by their finish times. This sorting can be done in O(nlogn) time complexity. After sorting the intervals, we used bisect, a variant of binary search to find the index of the latest non-overlapping interval for each interval. The bisection search takes O(logn) time for each interval, and we need to perform this operation for all n intervals, resulting in O(nlogn) time complexity. Finally, we can use dynamic programming to compute the maximum weight subset of intervals in O(n) time. Therefore, the overall time complexity of the algorithm is <strong>O(nlogn)</strong>.</p><h3>The Real World Application</h3><p>The weighted interval scheduling algorithm has various real-world applications in scheduling and resource allocation problems. Here are some examples:</p><ol><li><strong>Conference scheduling:</strong> Suppose a conference has multiple tracks and each track has multiple sessions. Each session has a start time, an end time, and a weight representing the importance of the session. The goal is to select a subset of sessions that do not overlap and have the maximum total weight.</li><li><strong>Project management:</strong> In project management, the tasks of a project can be modeled as intervals with start times, end times, and weights representing the importance or priority of the tasks. The weighted interval scheduling algorithm can be used to schedule the tasks in a way that maximizes the total weight and satisfies the resource constraints.</li><li><strong>Job scheduling:</strong> In job scheduling, each job has a processing time, a deadline, and a penalty for missing the deadline. The goal is to schedule the jobs in a way that minimizes the total penalty or maximizes the total profit.</li><li><strong>Resource allocation:</strong> In resource allocation, there are multiple resources that can be allocated to tasks, each with a capacity and a cost. The tasks have start times, end times, and weights representing the importance or value of the tasks. The goal is to allocate the resources to the tasks in a way that maximizes the total value while respecting the resource constraints.</li><li><strong>Machine scheduling:</strong> In machine scheduling, there are multiple machines that can process jobs, each with a processing time and a cost. The jobs have release times, due times, and weights representing the importance or priority of the jobs. The goal is to assign the jobs to the machines in a way that maximizes the total weight while respecting the processing and due time constraints.</li></ol><p><strong>References</strong></p><ol><li>Weighted Interval Scheduling Algorithm Explained by Aladdin Persson (<a href="https://www.youtube.com/watch?v=iIX1YvbLbvc">https://www.youtube.com/watch?v=iIX1YvbLbvc</a>)</li><li>GitHub Code (<a href="https://github.com/aladdinpersson/Algorithms-Collection-Python/blob/master/Algorithms/dynamic_programming/weighted_interval_scheduling.py">https://github.com/aladdinpersson/Algorithms-Collection-Python/blob/master/Algorithms/dynamic_programming/weighted_interval_scheduling.py</a>)</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8117eecb521a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>