================================================================= TITLE: Deep learning 3 DATE: 2024-11-27 (November 27, 2024 at 08:48 AM) DURATION: 01:10:21 (4221 seconds) WORDS: 9,015 words SPEECH ID: 26XPVAWX5MAMAH6A ================================================================= --- AI SUMMARY --- vectorization, deep learning, logistic regression, numpy library, explicit for loops, parallelization instructions, GPU, CPU, matrix multiplication, element-wise operations, gradient descent, maximum likelihood, broadcasting, rank one arrays, assertion statements --- FULL TRANSCRIPT --- [148:53:20] 0: Welcome back. Vectorization is basically the art of getting rid of explicit for loops in your page in the deep learning era, certainly in deep learning and practice, you often find yourself training on relatively large data sets, because that's when deep learning algorithms tend to shine, and so it's important that you code run quickly, because otherwise, if you're training on big data sets, your code will take a long time to run and just find yourself waiting a very long time to get a result. So in the deep learning era, I think the ability to perform vectorization has become a key skill. Let's start with an example. So what is vectorization? In logistic regression, you need to compute z equals W, transpose x plus b, where w was this column vector, and x is also this vector. Maybe they're very large vectors with a lot of features. So w and x were both these R, N or R [428:21:20] 0: and X [437:41:20] 0: dimensional vectors. So to compute W transpose X, if you had a non vectorized implementation, you would do something like z equals zero, and then for i in range of NX. So for i equals one to NX, z plus equals wi times xi, and then maybe [556:00:00] 0: do z plus equals vadi. [576:48:00] 0: So that's a non vectorized implementation, and you find that that seems to be really slow. In contrast the vectorized implementation, we just compute W transpose X directly in Python or NumPy, the command you use for that is z equals NP, dot w, comma x, so this computes W transpose X. And you can also just add b to that directly, and you find that this is much faster. Let's actually illustrate this with a little demo, right? So here's my Jupyter notebook in which I'm going to write some Python code. So first, let me import [791:06:40] 0: the numpy library and [805:46:40] 0: so for example, I can create a as in a gray as follows, let's say print a. Now, having written this chunk of code, if I hit Shift Enter, then it executes the code. So I created the array A, and it prints it out. Now let's do the vectorization demo. Going to import the time library, so we use that in order to time. How long different operations take? Going to create an array, a random Rand. Let's create a [972:21:20] 0: million dimensional array with [984:21:20] 0: random variable values, d equals P, dot, random dot, round another new individual array and now tick equals time, dot time. So let's measure the current time. C equals NP, dot, A, B, you have C, talk equals time, dot time, and let's print this is the vectorized version, right? So, vectorized version, [1114:56:00] 0: and so let's print out. [1136:48:00] 0: Let's see the last time. So let's talk minus tick times 1000 so that we can express this in milliseconds. So the mass is milliseconds, okay, so I'm going to hit ship, enter, okay, so that code took about three milliseconds, or this time 1.5 okay, about 1.5 or 2.5 [1239:33:20] 0: so you know, it varies a little bit. Let's keep [1290:18:40] 0: adding to this block of code. Let's now decorate c equals zero time so. [1335:44:00] 0: And now let's implement i in range of 1 million. [1382:56:00] 0: Right c plus equals I times b, pi, [1419:28:00] 0: and then top equals time dot, [1439:17:20] 0: time and finally, create with an explicit for loop, the time it takes. [1475:17:20] 0: This 1000 times, top minus, [1507:01:20] 0: tick, plus oops. And that's just to denote that we're doing this in milliseconds. Okay. Oh, and actually, let's do one more thing. Let's just, you know, print out the value of C the computer to make sure that is the same value in both cases. Okay, so I'm going to hit Shift Enter to run this and check that out. So in both cases, the vectorized version and the non vectorized version computed the same value. This is, you know, 25428, 6.989 so on, the vectorized version took 1.5 milliseconds. The explicit for loop, the non vectorized version took about 400 over almost 500 milliseconds. [1737:09:20] 0: So the non vectorized version took some vectorized version. [1770:45:20] 0: And so with this example, you see that if only you remember to vectorize your code, your code actually runs over 300 times faster. Well, let's just run it again like this and again, yeah, vectorized version 1.5 milliseconds and the full view. So 481 milliseconds. So again, about 300 times slower to do the explicit volume. So 300x slowdown is the difference between your code taking maybe one minute to run versus it taking, say, five hours to run. And when you are implementing deep learning algorithms, you can really get a result back faster and make much faster if you vectorize your code. So some of you might have heard that a lot of scalable deep learning implementations are done on a GPU, on the graphics processing unit, but all the demos I did just now in the Jupyter Notebook were actually on the CPU. And it turns out that both GPU and CPUs have parallelization instructions. They're sometimes called SIMD instructions, this sense of a single instruction, multiple data. But what this basically means is that if you use built in functions such as this np dot function, or other functions that don't require you're explicitly implementing a for loop, it enables it enables Python NumPy to take much better advantage of parallelism to do your computations much faster. And this is true both computations on CPUs and computations on GPUs. It's just that GPUs are remarkably good at the same D calculations, but CPUs actually also not too bad. That just not as good as GPUs. So you see in how vectorization can significantly speed up your code. The rule of thumb to remember is, whenever possible, avoid using explicit for loops. Let's go into the next video to see some more examples of vectorization, and also start to vectorize logistic regression. You [2334:34:40] 0: in a previous video, you saw a few examples of how vectorization, by using built in functions and by avoiding explicit for loops, allows you to speed up your code significantly. Let's take a look a few more examples. The rule of thumb to keep in mind is when you're programming your neural networks or when you're programming logistic regression, whenever possible, avoid explicit for loops. And it's not always possible to never use a for loop, but when you can use a built in function or find some other way to compute whatever you need, it will often go faster than if you have an explicit coordinate. Let's look at another example. If ever you want to compute a vector u as the product of a matrix A and another vector b, then the definition of a matrix multiply is that ui is equal to sum over j, A, ij, DJ. Right? That's how you define UI. And so the non vectorized implementation of this would be, you know, to set u equals NP, dot zeros will be n by one, and then, you know, for I and so on, for j, so on, right? And. Um, U, i plus equals, you know, a, i, j, times E, J. So now this has two for loops looking over i and j. So that's a non vectorized version. The vectorized implementation would be to say u equals NP, dot, a comma, B, and the implementation on the right to vectorize version now eliminates two different for loops, and it's going to be way faster. Let's go through one more example. Let's say you already have a vector v in memory, and you want to apply the exponential operation on every element of say, this vector v so you confuse u equals your vector, that's e to the V 1e, to the v2 and so on, down to E to the VN. So this would be a non vectorized implementation, right? Which is that first you initialize U to a vector of zeros, and then you have a for loop that computes the elements one at a time. But it turns out that Python and NumPy have many built in functions that allow you to compute these vectors with just a single call to a single function. So what I would do to implement this is import NumPy plus NP, and then we just call u equals NP, dot e to the V. And so notice that whereas previously you have an explicit for loop with just one line of code here, this V is an input vector, u is an output vector. You've got to rid of the explicit for loop, and the implementation with writes will be much faster than the one reading the explicit for loop. In fact, the numpy library has many other vector value functions, so NP, dot log of b will compute the element wise log, NP, dot abs, computes the absolute value. NPA dot maximum computes the element wise maximum. So you take the maximum at the element of v with zero v star, star two just takes the element wise square of each element of v1, over V takes the element wise inverse, and so on. So whenever you're tempted to write a for you, take a look and see if there's a way to call a numpy built in function to do it without that formula. So let's take all of these learnings and apply it to our logistic regression gradient descent implementation and see if we can at least get rid of one of the two for loops we had. So here's our code for computing the derivatives for logistic regression. And we had two for loops. One was this one up here, and the second one was this one, right? So in our example, we had n or NX equals two. But if you had more features than just two features, then you'd like to have a four. We will be DW one, DW two, DW three, and so on. So as I said, there's actually a 4j. Equals one to NX, dwj, dwj gets updated. So we like to eliminate this second form. That's what we'll do on the slide. So the way we'll do so is that instead of explicitly initializing DW one, DW two and so on to zeros, we're going to get rid of this and instead make DW a vector. So we're going to set dw equals NP dot zeros, and let's make this a MX by one dimensional vector. Then here, instead of this whole loop over the individual components, we just use this vector value operation, dW plus equals [3768:48:00] 0: xi times dzi. And then finally, [3801:52:00] 0: instead of this, we will just have DW [3826:24:00] 0: device equals m. [3838:45:20] 0: So now we've gone from having two for loops to just one for loop. We still have this one for loop that loops over the individual training examples. So I hope this video gave you a sense of vectorization, and by getting rid of one for loop, your code will already run faster, but it turns out we could do even better. So the next video, we'll talk about how to vectorize logistic regression even further, and you see a pretty surprising result, that without using any for loops, without needing a for loop over the training examples, you could write code to process the entire training set. So pretty. Much all at the same time. So let's see that in the next video, [4065:20:00] 0: we've talked about how vectorization lets you speed up your code significantly. In this video, we'll talk about how you can vectorize your implementation of logistic regression so they can process an entire training set, that is implement a single iteration of gradient descent with respect to the entire training set without using even a single explicit overview. I'm super excited about this technique, and when we talk about neural networks later, without using even a single explicit formula. Let's get started. Let's first examine the forward propagation step of logistic regression. So if you have n training examples, then to make a prediction on the first example, you can compute that compute Z using this formula, then computing activation to compute y hat in the first example, then to make a prediction on the second training example, you need to compute that, then to make a prediction on the third example, you need to compute that, and so on. And you might need to do this m times if you have n training examples. So it turns out that in order to carry out the foreign propagation step that is to compute these predictions on all m training examples. There is a way to do so without needing explicit for you. Let's see how you can do it. First, remember that we defined the matrix capital X to be your training inputs stacked together in different columns like this. So this is a matrix that is a NX by n matrix. So I'm writing this as a Python NumPy shape, but this just means that x is a NX by m dimensional matrix. Now the first thing I want to do is show how you can compute z1, z2 z3, and so on, all in one step, in fact, with one line of code. So I'm going to construct a one by m matrix is really a row vector where I'm going to compute z1 z2 and so on down to Z M, all at the same time. It turns out that this can be expressed as W, transpose the capital matrix x plus an in this vector, B, [4724:10:40] 0: E, so on B, where this, this [4741:30:40] 0: b, b, b, b, b is a one by m [4756:58:40] 0: vector, or one by m matrix, or that is a m dimensional row vector. So about how familiar you are with matrix multiplication, you might see that W transpose x1 [4842:08:00] 0: x2 and so on [4861:20:00] 0: through x m, that W transpose is going to be a row vector. W transpose will be a row vector like that. And so this first term will evaluate to w, transpose x 1w, transpose x2 and so on. Dot, dot, dot, W transpose X m. And then when you add this second term, BBB and so on, you end up adding V to each other. So you end up with another one by n vector, where that's the first element, that's the second element and so on, that's the n element. And if you refer to the definitions above, this first element is exactly the definition of z1 the second element is exactly the definition of z2 and so on. So just as X was what you obtained when you took your training examples and stack them next to each other, stack them horizontally, I'm going to define capital z to be this, where you take the lowercase Z's and stack them horizontally. Okay, so when you stack the lowercase x's, corresponding to different training examples, horizontally, you get this variable, capital X. In the same way, when you take these lowercase z variables and stack them horizontally, you get this variable, which we know by capital Z. And it turns out that in order to implement this, the numpy command is capital Z equals NP, dot w, dot t plus W, transpose x. B and then plus b. Now there is a subtlety in Python, which is that here, B is a row number, or if you want to say, you know, one by one matrix, it's just a normal row number. But when you add this vector to this row number, Python automatically takes this row number b and expands it out to this one bicameral vector. So in case this operation seems a little bit mysterious, this is called broadcasting in Python, and you don't worry about it for now. We'll talk about it some more in the next video. But the takeaway is that with just one line of code. With this line of code, you can calculate capital Z, and capital Z is going to be a one by n matrix that contains all of the lowercase z, lowercase z, 1z lowercase z. So that was Z. How about these values? You know a right. What we like to do next is find a way to compute a one, a, two and so on through a m, all at the same time, and just as stacking low case X's resulted in capital X and stacking, stacking horizontally, low case Z's resulting capital Z stacking lowercase A's is going to result in a new variable, which we define as capital A. And in the program assignment, you see how to implement a vector valued sigmoid function so that the sigmoid function see the details of that in the programming assignment. So just to recap, what we've seen on this line is that instead of loop over examples to compute lower case z and lower case a one at a time, you can implement this one line of code to compute all the Z's at the same time, and then this one line of code with appropriate implementation of lowercase sigma to compute all the lowercase A's all at the same time. So this is how you implement a vectorized implementation with a forward propagation for all entering examples at the same time. So to summarize, you've just seen how you can use vectorization to very efficiently compute all the activations, all the lowercase A's, so that at the same time next it turns out you can also use vectorization to very efficiently compute the backward propagation, to compute the gradients. Let's see how you can do that in the next video. I [6072:58:40] 0: in the previous video, you saw how you can use vectorization to compute the predictions the lower case, A's for an entire training set, all sort of at the same time in this video, you see how you can use vectorization to also perform the gradient computations for all m training examples, again, all sort of at the same time. And then at the end of this video, we'll pull it all together and show how you can derive a very efficient implementation of logistic regression. So you will remember that for the gradient computation, what we did was we computed dz one, for the first example, this will be a one minus y1 and then dz two equals a two minus y2 [6291:01:20] 0: and so on, so [6308:21:20] 0: and So on for all m training examples. So what we're going to do is define a variable d capital Z is going to be dz, one, dz, two, dz, M, again, all the D lower, kz variables stacked horizontally. So this would be one by m matrix, or alternatively a n dimensional row vector. Now recall that from the previous slide, we already figured out how to compute capital increases a one through a m, we had defined capital y as y1, through y, that will also stack horizontally. So based on these definitions, maybe you could see for yourself that can be computed as just a minus y, because this going to be equal to a one minus y1, first element, a two minus y2 second element, and so on, and so and so. This first element a one minus y1 is exactly the definition of dz one. The second element is exactly definition of dz two, and so on. So with just one line of code. You can compute all of this at the same time. Now, in the previous implementation, we've gotten rid of one for loop already, but we still had this second for loop over training samples. So we initialized DW to zero to the vector of zeros. But then we still had to loop over training examples where you have dW plus equals x1, times dz one. For the first training example, dW plus equals x2 dz, two, and so on. So we do the M times and then dw divided equals by M. [6850:29:20] 0: And similarly for BS zero, [6875:22:40] 0: dB plus equals dz, one, dB plus equals dz, two down to dz M, and DB divide equals m. So that's what we had in the previous implementation, we'd already gotten rid of one for loop, so at least now, dw is a vector, and we went separately, updating DW one, DW two and so on. So we got to rid of that already, but we still had a for loop over the m examples in the training set. So let's take these operations and vectorize them. Here's what we can do for the vectorized implementation of dB. What it's doing is basically summing up all of these dz and then dividing by m, so DB is basically one over M sum from i equals one through m of dzi. And where all the D Z's are in that row vector. And so in Python, what you do is implement one over m times n p, dot sum of d z. So just take this variable and call the np dot some function on this and that will give you dB. How about DW? I'll just write out the correct equations. You can verify is the right thing to do. DW tends to be one over m times the matrix, x times dz transpose, and to kind of see why that's the case, this is equal to one over m, then the matrix X is x1 through x m, right stacked up in columns like that, and dz transpose would be dz One down to dz M, like so and so, if you figure out what this matrix times this vector works out to be. This turns out to be one over m times x1 dz, one [7441:30:40] 0: plus dot, dot, dot plus XM, dz, M. [7470:02:40] 0: And so this is a n by one vector. And this is what you actually end up with with dw, because DW was taking these Xi dzi and adding them up. And so that's what exactly this matrix vector multiplication is doing. And so again, with one line of code, you can compute dw, so the vectorized implementation of the derivative calculations is just this. You use this line to implement dB, and use this line to implement dw, and notice that without a for loop over the training set, you can now compute the updates you want to your coherences. So now let's put all together into how you would actually implement HSN progression. So this is our original, highly inefficient, non vectorized implementation where. So the first thing we've done in the previous video was get rid of this body. So instead of looping over DW 1d, w2, and so on. We have replaced this with a vector value, D W. Just say this is d W plus equals x, I, which is now a vector times d z, but now we'll see that we can also get rid of not just the volume below, but also get rid of this body. So here's how you do it. So using what we had from the previous slides, you would say capital Z is equal to W, transpose X plus B, and code you write is capital Z equals NP, dot w, transpose X plus B, and then a equals sigma to capital Z. So you've now computed all of this, and all of this for all the values of i mix on the. Previous slide, you said you would compute dz equals capital A minus capital Y. So now you computed all of this for all the values of i, then finally, dw equals one over m, x, d, z transpose and DB equals one over m, [8115:17:20] 0: NP, dot sum, dz, [8139:17:20] 0: so you've just done forward propagation and back propagation really computing the predictions and computing the derivatives on all m training examples without using a for loop. And so the gradient descent update then would be, you know, W gets updated as w minus the learning rate times dw, which you just computed above, and B gets updated as B minus the learning rate times dB. Sometimes it's being COVID set to denote this is on assignment. But I guess I haven't been totally consistent with that notation, but with this, you have just implemented a single iteration of gradient descent for logistic regression. Now, I know I said that we should get rid of explicit folders whenever you can, but if you want to implement multiple iterations of gradient descent, then you still need a for loop over the number of iterations. So you want to have 1000 iterations of gradient descent, you might still need a for loop. So that's it. You now have a highly vectorized and highly efficient implementation of gradient descent for logistic regression. There's just one more detail that I want to talk about in the next video, which is in our description here. I briefly alluded to this technique called broadcasting. Broadcasting turns out to be a technique that Python and NumPy allows you to use to make certain parts of your code also much more efficient. So let's see some more details of broadcasting in The next Video You [9700:48:00] 1: How do you compute the derivative of B in one line of code in Python, n, u, m, p, y1, [9744:21:20] 2: asterisk, M, parenthesis, N, P, dot, sum, parentheses, d, z, parentheses, parentheses, one minus m, parentheses, NP, dot, sum, parentheses, d, Z, parentheses, parentheses, one slash, m, times, parentheses, NP, dot sum parentheses, d z, parentheses, parentheses, [9909:36:00] 1: or M, [9919:28:00] 2: parentheses, NP, dot sum parentheses, dz, parenthesis, parenthesis and [10134:18:40] 2: I'm going to Learn how to understand what you got to understand something you can explain that to me in the future, I can use this For my best and understanding this [10225:04:00] 1: is pretty tough. [10261:41:20] 0: In the previous video, I mentioned that broadcasting is another technique that you can use to make your Python code run faster. In this video, let's delve into how broadcasting in Python actually works. Let's note today, broadcasting with an example in this matrix, I've shown the number of calories from carbohydrates, proteins and fats in 100 grams of four different foods. So for example, 100 grams of apples, turns out, has 56 calories from carbs and much less from proteins and fats, whereas, in contrast, 100 grams of B has one, four calories from protein, 135 calories from fat. Now let's say the goal is to calculate the percentage of calories from carbs, proteins and fats for each of the four foods. So for example, if you look at this column and add up the numbers in that column, you get that 100 grams of Apple has 56 plus 1.2 plus 1.8 so that's 59 calories. And so as a passage, the percentage of calories from carbohydrates in an apple would be 56 over 59 that's about 94 about 94.9% so most of the calories in an apple come from cows, whereas, in contrast, most of the calories of beef come from protein and fat and so on. So the calculation you want is really to sum up. Each of the four columns of this matrix to get the total number of calories in 100 grams of Apple, beef, eggs and potatoes, and then to divide throughout their matrix so as to get the percentage of calories from carbs, proteins and fats for each of the four foods. So the question is, can you do this without an explicit for loop? Let's take a look at how you could do that. What I'm going to do is show them how you can set, say this matrix equal to a three by four matrix, A and then, with one line of Python code, we're going to sum down the columns. So we're going to get four numbers corresponding to the total number of calories in these four different types of food, 100 grams of these four different types of food. And I'm going to use a second line of Python code to divide each of the four columns by their corresponding sum. If that variable description wasn't very clear, hopefully it'll be clearer in a second when we look at the Python code. So here we are in the Jupiter notebook. I've already written this first piece of code to pre populate the matrix A with the numbers we have just now. So shift, enter and just run that. So there's a matrix A, and now here are the two lines of heightened COVID first. And if you tell equals a dot sum and x is equals zero means the sum vertically, same cow, so, so with some vertically. So, as we say just now, 59 is the total number of calories in the apple, 239 was the total number of calories in beef and eggs and potato and so on. And then we're going to compute percentage equals A over cow, dot B shape, one by four. Actually we want percentages multiplied by 100 here, [11220:48:00] 0: and then let's print percentage. [11241:04:00] 0: Let's run that. And so that command, we've taken the matrix A and divided it by this one by four matrix, and this gives us the matrix of percentages. So as we worked out, kind of by hand, just now, you know, in the Apple there was the first column, 94.9% of the calories, often carbs. Let's go back to the slides. So just to repeat the two lines of code we had, this is what we have written out in the Jupiter notebook. So add a bit of detail. This parameter, axis equals zero means that you want Python to sum vertically. So this is axis zero means to sum vertically, whereas the horizontal axis is axis one, so it's the right axis one or some horizontal instead of sum vertically. And then this command here. This is an example of hyperbolic casting when you take a matrix A so this is a three by four matrix, and you divide it by a one by four matrix. And technically, after this first line of code, Cal, the variable Cal is already a one by four matrix. So technically, you don't need to call V shape here again. So that's actually a little bit redundant. But when I'm writing piping codes, if I'm not entirely sure what matrix, what are the dimensions by matrix, I often would just call a V shape command, just to make sure that is, you know, the right column, back to the row, back to whatever you want it to be. The V shape command is a constant time. So order one operations is very cheap to call, so don't be shy about using the V shape command to make sure that the nucleus is the size you need it to be. Now let's explain in greater detail how this type of operation works. Right? We had a three by four matrix, and we divided it by a one by four matrix. So how can you divide a three by four matrix by that by a one by four matrix and by one by four vector? Let's go through a few more examples of broadcasting. If you take a four by one vector and add it to a number, what Python will do is take this number and auto expand it into a four by one vector as well as follows. And so the vector 1234, plus the number 100 ends up with that vector adding 100 to every element. And in fact, we use this form of broadcasting where that constant was the parameter b. In early video we in early video. And this type of broadcasting works with both column vectors and row vectors. And in fact, we use a similar form of broadcasting earlier with the constant we're adding to a vector in the parameter b in VGC regression. Here's another example. Do. Let's say you have a two by three matrix, and you add it to this one by n matrix. So the general case would be, if you have some m by n matrix here, and you add it to a one by n matrix. What Python will do is copy the matrix M times to turn this into an m by n matrix. So instead of this one by D matrix, or copy it twice in this example to turn it into this also two by B matrix, and they'll add these so you end up with someone right? So you're taking your added 100 to the first column, added 200 column, added 300 to the third column. And this is basically what we did on the previous slide, except that we're using the vision operation instead of an additional operation. One last example, whether you have a n by n matrix, and you add this to an m by one vector, n by one matrix, then just to copy this n times horizontally, so you end up with an n by n matrix. So let's imagine a copy of horizontal few times and add those. So when you add them, we end up with this. So we've added 100 to the first row and added 200 to the second row. Here's the more general principle of broadcasting in Python, if you have an m by n matrix, and you add or subtract or multiply or divide with a one by n matrix, then this will copy it m times into an m by n matrix, and then apply the addition, subtraction, multiplication or division element wise, if, conversely, you were to take the m by n matrix and add, subtract, multiply, divide by m by one matrix, then also this would copy it now n times and turn that into the m by n matrix, and then apply the operation elements y, just one other form of bore constant, which is if you have an n by one matrix, so that's really a column vector, like 123, and you add, subtract, multiply or divide by a row number. So if you have one by one matrix, so such that because 100 then you end up copying this real number n times until you also get another n by one matrix. And then we perform the operation such as addition of this example element twice. And something similar also works for row vectors. The fully general version of broadcasting can do even a little bit more than this. If you're interested, you can read the documentation for NumPy and look at broadcasting that documentation that gives an even slightly more general definition of broadcasting, but the ones on this slide are the main forms of broadcasting that you end up needing to use when you implement it in your network. Before we wrap up just one last comment, which is for those of you that are used to programming either MATLAB or Okta, if you've ever used the MATLAB or octave function BSX fun in neural network programming. BSX fun does something similar, not quite the same, but is often used for a similar purpose as well. We use broadcasting in Python for but this is really only for very advanced MATLAB and optic users. If you've not heard of this, don't worry about it. You don't need to know it when you're coding up neural networks in Python. So that was broadcasting in Python. I hope that when you do the programming homeworks, that broadcasting will allow you to not only make your code run faster, but also help you get what you want done with fewer lines of code. Before you dive into the programming exercise, I want to share with you just one more set of ideas, which is that there's some tips and tricks that I found reduces the number of bugs in my Python code, and then I hope will help you too, so that, let's talk about that in the next week. [13257:09:20] 1: So which of the following, n, u, n, p, y, line of code [13322:34:40] 2: would sum the values. In a matrix, a vertically, a dot sum, parentheses, access, parenthesis, a dot sum, parentheses, access, equals one, parenthesis, a dot sum, parentheses, axis equals Zero. Parenthesis, I [13782:13:20] 1: I Love you, Nancy, I [13881:52:00] 0: the video, [13915:44:00] 0: the ability of Python to allow you to use broadcasting operations and more generally, the great flexibility of the Python young pi program Language is, I think, both a strength as well as a weakness of the current language. I think it's a strength because the great expressivity of the language, the great flexibility of the language, lets you get a lot done, you know, with even just a single line of code. But it's also a weakness, because with broadcasting and this great amount of flexibility, sometimes it's possible you can introduce very subtle bugs or very strange looking bugs. If you aren't familiar with all of the intricacies of how broadcasting and how features like broadcasting work. For example, if you take a column vector and add it to a row vector, you might expect it to throw up a dimension mismatch or type error or something. You might actually get back a matrix as a sum of a row vector and column vector. So there is an internal logic to these strange effects of Python. But if you are familiar with Python now, I've seen some students have very strange, very hard to find bugs. So what I want to do in this video is share with you a couple of tips and tricks that they're very useful for me to eliminate or simplify and eliminate rather strange looking bugs in my own code. And I hope that with these tips and tricks, you'll also be able to much more easily write bug free Python and NumPy code to illustrate one of the less intuitive effects of Python, NumPy, especially how you would construct vectors in Python NumPy. Let me do a quick demo. Let's say I set a equals NP, dot random, dot random, five. So this creates a five random Gaussian variables stored in array, a, and so let's print a. Now, it turns out that the shape of a, when you do this, is this five comma structure. And so this is called a rank one array in Python, and it's neither a row vector nor a column vector. And this leads it to have some slightly non intuitive effect. So for example, if I print a transpose, it ends up looking the same as a So A and A transpose end up looking the same. And if I print a product between A and A transpose, you might think A times A transpose is maybe the outer product should give you a matrix, maybe. But if I do that, use the get the number. So what I would recommend is that when you're coding neural networks, that you just not use data structures where the shape is this. You know, five, comma, N, comma, rank, one array instead, if you set a to be a. On this five by one, then this commits a to be a five by one column vector, and whereas previously, A and A transpose look the same if you now print a transpose, now A transpose is a row vector. Notice one subtle difference in this data structure. There are two square brackets when you print a transpose, whereas previously there was one square bracket. So that's the difference between a this is really a one by five matrix versus a one of these are rank one arrays. And if you print, say, the product between A and A transpose, then this gives you the outer products of a vector, right? So the outer product of a vector gives you a matrix. So let's look in greater detail at what we just saw here. The first command that we rang just now was this, and this created a data structure where a dot shape was this? Funny thing, five comma. And so this is called a rank one array. And this is a very funny data structure. It doesn't behave consistently as either a row vector nor a column vector, which makes some of its effects non intuitive. So what I'm going to recommend is that when you're doing your program exercises, or, in fact, when implementing logistic regression or neural networks, that you just do not use these rank one arrays instead, if every time you create an array, you commit to making it either a column vector, so this creates a fiber one vector, or commit to making it a row vector, then the behavior of your vectors will maybe easier to understand. So in this case, a dot shape is going to be equal to five, comma one, and so this behaves a lot like that. This is a column vector, and that's why you might you can think of this as a five by one matrix or as a column vector, and here a dot shape is going to be one comma five, and this behaves consistently as a row vector. So when you need a vector, I would say, either use this or this, but not a rank one array. One more thing that I do a lot in my code is, if I'm not entirely sure what's the dimension of one of my vectors, I'll often throw in an assertion statement like this to make sure, in this case, that this is a five by one vector. So this is a column vector. These assertions are really inexpensive to execute, and they also help to serve as documentation for your code. So don't hesitate to throw in assertion statements like this when you feel like it. And then finally, if for some reason, you do end up with a rank one array, you can reshape this A equals A dot reshape into, say, a five by one array or one by five array, so that it behaves more consistently as usual column vector or row vector. So I've sometimes seen students end up with very hard to track down both, because they saw the non intuitive effects of rank one arrays by eliminating rank one arrays of my own code, I think my code became simpler and I did not actually find it restrictive in terms of things I could express in code, to just never use a rank one array. And so takeaways are to simplify your code, don't use rank one arrays. Always use either n by one matrices, basically column vectors, or one by N matrices, or basically row vectors. Feel free to toss a lot of assertion statements, so double check the dimensions in matrices and rays. And also, you know, don't be shy about calling the reshape operation to make sure that your matrices or your vectors are the dimension that you need it to be. So that, I hope that this set of suggestions helps you to eliminate across the bugs that from Python code and makes the current exercise easier for you to complete. So wherever. With everything you've learned, you're just not ready to tackle your first program assignment before you do that. Let me just give you a quick tour of IPython notebooks in Coursera. Here's the Jupiter IPython notebook that you can get to on Coursera. Let me just quickly show you a few features of this. The instructions are written right here in the text in the iPython notebook. And these little light gray blocks are blocks of code. So occasionally you see in these blocks something looks like this is the style code here to do their program exercise, please make sure to write your code between the start code here and end code here. So for example, print hello world and then to execute a code block, you can click Shift Enter and then execute this code block, which I guess we just wrote, print hello world and. So that printed hello world to run a cell, you can also to run one of these code blocks in the cell. You can also click cell and run cell. So the excuses, it's possible that on your computer, the keyboard shortcut for cell, run cell might be different than Shift Enter, but it's on both my Mac as well as on my PC, or Shift Enter. So might be the same for you as well. Now when you reading the instructions, if you accidentally double click on it, you will end up with this markdown language. If you end up with this funny looking text, to convert it back to the nice looking test, just run the cell. So either go to cell, run cell, or I'm going to hit Shift Enter, and that basically executes the markdown in terms of backing these nice looking code. Just a couple more tips. When you execute code like this, it actually runs on a kernel, on a piece of code that runs on the server, if you're running an excessively large job, or if you're you leave a computer for a very long time, or something goes wrong, your internet connection, or something, there is a small chance that the kernel on the back end might die, in which case, just click kernel and then restart kernel, and hopefully that will reboot the kernel and make it work again. So that shouldn't happen if you're just run relatively small jobs, and starts it up to IPython notebook, if you see an error message that the kernel has died or something, to try kernel restart. Finally, in an iPad notebook like this that there may be multiple blocks of code, so even if an earlier block of code doesn't doesn't have any created code. Be sure to execute this block of code, because in this example, it imports NumPy as NP and so on and sets up some of the variables you might need in order to execute the lower down blocks of code. So be sure to execute the ones on top, even if you aren't asked to write any code. And finally, when you're done implementing your solutions, is this new Submit Assignment button here on the upper right, and we click that will submit your solutions for green [16583:28:00] 0: I found that the interactive command shell nature of IPython notebooks seem very useful for letting you quickly implement a few lines of code, see an outcome, Learn and it really quickly. And so I hope that the current exercises in the Coursera, Jupiter I pita notebooks will help you quickly learn and experiment and see how to implement these learning algorithms. There's one more video after this, this optional video that talks about the cost function for logistic regression. I can watch that or not. Either is perfectly fine, but either way, best of luck with the week two programming assignments, and I also look forward to seeing you at the start of the week three materials. [16799:38:40] 0: In an earlier video, I've written down a form for the cost function for logistic regression. In this optional video, I want to give you a quick justification for why we'd like to use that cost function for logistic regression. To quickly recap, in logistic regression, we have that the prediction Y hat is sigmoid of W transpose X plus b, where sigmoid is this familiar function. And we said that we want to interpret y hat as the probability that y is equal to one given x. So we want our algorithm to output Y hat as the chance that y is equal to one for a given set of input features x. So another way to say this is that if y is equal to one, then the chance of Y given X is equal to y hat and conversely, if y is equal to zero, then the chance that y was zero was one minus y hat, right? So y hat was a chance that y is equal to one. Then one minus y hat is the chance that y is equal to zero. So let me take these last two equations and just copy them to the next slide. So what I'm going to do is take these two equations, which basically define p of y given x, you know, for the two cases of y equals zero or y equals one, I'm going to take these two equations and summarize them into a single equation. And just to point out y has to be either zero or one, because when binary classification so y equals 01 are the only two possible cases, right? But someone take these two equations and summarize them as follows. Let me just write out what it looks like. Then we'll explain why it looks like that one minus y. So it turns out this one line summarizes the two equations on top. Let me explain why the. So in the first case, suppose y is equal to one, right? So y is equal to one, then this term ends up being y hat, because that's y hat to the power of one, this term ends up being one minus y hat to power of one minus one, so that's the power of zero, but anything to the power of zero is equal to one, so that goes away. And so this equation just says P of Y, given x equals y. Hat, when, when y is equal to one. So you know, that's exactly what we wanted. Now, how about the second case? What if y equals zero? If y is equal to zero, then this equation above is p of y given x equals y, hat to the zero. But anything to the power of zero is equal to one. So that's just equal to one times one minus y, hat to the power of one minus y. So one minus y is one minus zero. So this is just one and so this is equal to one times one minus y hat, which is just equal to one minus y hat. And so here we have the y equals zero. P of y given x is equal to one minus y hat, which is exactly one pointed above. [17693:20:00] 0: So what we've just shown is that this equation [17709:57:20] 0: is a correct definition for p of y given x. Now finally, because the log function is a strictly monotonically increasing function, maximizing log of p of y given x should give you similar result as optimizing p of y given x, and if you compute log of p of y given x, that's equal to log of y, hat to the power of y1, minus y, hat to the power of one minus y. And so that simplifies to y, log y hat plus one minus y times log one minus y hat. And so this is actually negative of the loss function that we had defined previously. And there's a negative sign there, because usually if you're training learning algorithm, you want to make probabilities large, whereas in logistic regression, we're expressing this, we want to minimize the loss function. So minimizing the loss corresponds to maximizing the log of the probability. So this is what the loss function on a single example looks like. How about the cost function, the overall cost function on the entire training set on m examples? Let's figure that out. So the probability of all the labels in the training set, writing this out a little bit informally, is if you assume that the training samples are drawn independently or drawn IID identically, independently distributed, then the probability of the examples is the product of probability. So product from i equals one through M, of p, of y, i given X, I and so if you want to carry out maximum likelihood estimation right then you want to maximize the find the parameters that maximizes the chance of your observations and training set. But maximizing this is the same as maximizing the logs for logs on both sides. So log of the probability of the labels and training set is equal to log of the product is the sum of the log. So that sum from i equals one DM of log p of y i given xi. And we had previously figured out on the previous slide that this is negative L of y times i y height. And so in statistics, there's a principle called the principle of maximum likelihood estimation, which just means to choose the parameters that maximizes this thing, or in other words, that maximizes, you know, this thing right negative sign of mine corresponds to the M, L of y, x, i, y, I just moved the negative sign outside the summation. So this justifies the cost we had for the just regression, which was j of W, B of this. And because we now want to minimize the cost instead maximize the likelihood, we've gotten rid of the minus one. And then finally, for convenience. So to make sure that our quantities are better scale, we just add a one over M extra scaling factor. But So to summarize, by minimizing this cost function, J of WB, we're really carrying out maximum likelihood estimation with the logistic regression model under the assumption that our training examples were IID or identity. Thank you for watching this video, even though this is optional, I hope this. [18673:04:00] 1: Hello, how you doing? I'm [18698:40:00] 1: well. Thank you. How are you I'm doing? Well, good. [18711:44:00] 1: How the little ones, you [18725:20:00] 1: know, they're roaming around now, and I got how's [18751:28:00] 3: the mom today? How's she fit?