1. Home
  2. Explore
  3. Computer Science
  4. Building Keras Models

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Building Keras Models

Transcript

[SQUEAKING] [RUSTLING] [CLICKING] RAMA RAMAKRISHNAN: OK. All right. Let's get going. Today is going to be packed. I'm going to spend the first roughly half of the lecture on actually building a model-- a Keras model in Colab-- to solve the heart disease problem we saw earlier, and then switch gears halfway, and then talk about how to solve image classification. So we're going to do two Colabs today. I've been talking about Colab. Colab, I've been teasing you.

We'll actually do Colabs today. All right. So summary of where we were. By the way, I've shut off the lights in the top because, when I switch to Colab, it's going to be much better for you folks, particularly the folks in the back, to be able to see it. But I hope you can see the slide right now. Yes? OK. Great. So this is just a quick recap of what we did last class. Broadly speaking, training a neural network essentially is no different than training other kinds of models. We have a bunch of parameters, i.e., weights and biases, and we need to use the data to find good values of those weights. And what does good mean? Typically, it means that we define some measure of discrepancy between what the model predicts for a given set of weights and what the right answer is, what the ground truth answer is. And then we try to find weights that minimize this discrepancy. That's it. And this notion of discrepancy is called a loss function.

So broadly speaking, the overall training flow is that you define some network. It has an input. It goes through a bunch of layers. You come up with some predictions. You take the predictions. You take the true values. And then those two go into the loss function, i.e., the discrepancy function. And then you come up with a loss score. And then you send it to the optimizer, which then proceeds to calculate the gradient of this loss function with respect to all the parameters. And then it updates all the weights using that gradient, and then the process repeats. That's it. So that is the training flow. Quick recap. Now, we also talked about the optimization algorithm we're going to use, which is called gradient descent. And gradient descent, as you noticed, in each iteration, every data point is being used to make predictions and therefore to calculate the loss, and then to calculate the gradient. And then we pointed out that gradient descent is actually not

as good as something called stochastic gradient descent-- stochastic gradient descent-- where, instead of taking all the points, we just randomly choose a small number of points, pretend for a moment as if those are the only points we have, make predictions, calculate loss, calculate gradient, and go on. So that was the basic idea behind stochastic gradient descent. Two different kinds of things. Now, what it means is that when we actually start training the model, as we will in a few minutes, because we only take a few points at a time, we have to be a bit careful in what's going on. And I want to make sure you clearly understand what the differences are before we actually get to the Colab. OK? All right. So there is the notion of an epoch. An epoch essentially just means that we make one pass through the training data. All the training data. We make one pass through it. And so what is one pass is that if you have something

like gradient descent, one pass means every data point is sent through the network. We calculate its predictions, calculate the loss, calculate the gradient. We run every training sample through it. We calculate the gradient, which is just this thing here. I mean, I will sometimes say d of loss, dW. Derivative of loss with respect to W. Sometimes I might use this nabla symbol. These are all interchangeable. So we'll calculate the gradient, and then we update using some version of this.

But we just do it once at the end of the epoch. Because if you have 10 billion data points, every one of them flows through, you get 10 billion outputs. And then we calculate the epoch just once. At the end of this thing, we calculate the gradient and update once. One update per epoch. Yes? Now, in stochastic gradient descent, what we do is that we process the data in batches. Small numbers of points at a time. And these are called-- technically speaking, they're called minibatches. I don't know about you. I just get tired of saying minibatches, so I'm just going to say batches from this point on. OK? And in fact, that is widely done in the literature. So we'll have to process it in batches. So we take the training data. And then we divide it up into batches-- batch 1, batch 2, all the way till the final batch. And so what we do is, for each batch, we basically do gradient descent. For each batch, we take batch 1, and then we

run just the training samples in that batch through the network to get predictions. We calculate the gradient, we update the parameters, and then we go to batch 2. Then we go to batch 3 and so on and so forth. So pictorially, this is how it's going to look like. Let's say the first batch is, say, 32 points. We take those 32 points. We run it through the network, get all the stuff out. We calculate the gradient, update the weights. So when we now get to batch 2, the weights have changed. They have been updated. And then we do the same thing with batch 2, batch 3, and all the way till we get to the end of the thing. And when we are done with this thing, this whole thing is called a what? An epoch. This whole thing is an epoch. OK? All right. So the question, of course, is that if you have a bunch of data points, and you're going to run stochastic gradient descent on it,

in a particular epoch, how many batches are going to be there? How many batches are going to be there? Now, Keras is going to calculate all this stuff. You don't have to worry about it. But you just need to understand exactly what happens. So my philosophy, by the way, is that you have to know the details of what's going on. If you don't know the details, and if you haven't figured out at least once, you will not actually be able to think new and creative thoughts for a new problem. It's because the concepts are not manipulable in your head yet. OK.

Please use the microphone. AUDIENCE: So when we talk about SDG and we are talking about-- we are only taking some part of it, is it what we are saying is that we only take some variables, or we're only taking some part of the data? RAMA RAMAKRISHNAN: We are taking some rows. AUDIENCE: We're taking only-- oh, right. So that-- RAMA RAMAKRISHNAN: Data points. AUDIENCE: That means the batch itself. RAMA RAMAKRISHNAN: Exactly. So for example, let's say you have 1,000 data points, 1,000 rows of observations, 1,000 patients in the heart disease example, or 1,000 images that you're trying to classify. You take, let's say, 32 of those images, 32 of those patients, and that's a batch. Then you go to the next 32, then the next 32, and so on and so forth, until you run out of patients or run out of images. AUDIENCE: And each iterative time you are updating with the weights, the weights that you've got? RAMA RAMAKRISHNAN: Correct.

AUDIENCE: And it means you keep correcting it or keep moving towards-- RAMA RAMAKRISHNAN: You're basically updating the weights as you go along. AUDIENCE: Updating the weights. AUDIENCE: And what we are calling the epoch is ultimately the equation of loss function that we are trying to get. RAMA RAMAKRISHNAN: No, an epoch-- see, the thing to remember is that here, this whole thing is called an epoch, because we have to do one full pass through the training data. But within that epoch, we update the weights many times. Basically, we update the weights as many times as we have batches.

All right. So to go here-- let's say, for example-- basically, the idea is that you take the training set, you divide it by the batch size, and you choose the batch size. You choose the batch size. And we'll talk about, well, How do you choose that? later on. You choose the batch size. And once you choose the size, just divide it and round it up. So for example, as you will see in the Colab, a training set is going to be 194 patients. And then we're going to choose a batch size of 32. And we typically tend to choose batch sizes of 32, 64, and things like that because it actually aligns very well with the nature of the parallel hardware we're going to use. And so here, 32 and so on. So divide 194 by 32. You get 6-point-something. You round it up to 7. And so what that means is that the first six batches will have 32 samples each. And then the final batch has only two samples left. And that's OK.

It can be a nice, little, small batch at the end. There's nothing that says that every batch has to be the same size. That's it. Epochs. Batches. [AUDIO OUT] AUDIENCE: And are you-- for each batch, you run through the whole network, all the layers? Or each layer is one batch? RAMA RAMAKRISHNAN: No. For a batch, you run it through the entire network. So the way to think about it is that you take a batch. Just momentarily, you assume that's all the data you have. Just run it through the network, because unless you run it through every layer of the network,

you can't get a prediction. Unless you get a prediction, you can't calculate the loss. And unless you calculate the loss, you can't calculate the gradient. Unless you calculate gradient, you can't update the weights. AUDIENCE: The last thing. But if you're using all the data, just doing the gradient descent, then you just go through the network once, right? RAMA RAMAKRISHNAN: Exactly. So in gradient descent, one epoch is one pass and one weight update. And in stochastic gradient descent, the number of updates you make is equal to the number of batches you have, which ends up being the training set divided by the batch size rounded up. AUDIENCE: Sorry, just to confirm. So initially, when you introduced the concept of batches, the whole purpose was not to run through all the data and be able to do some prediction from a subset. So now, the advantage is that after batch 1, we are using more accurate coefficient to run through batch 2 and so on?

That's really the advantage of it? RAMA RAMAKRISHNAN: Exactly. AUDIENCE: Or is there something else here? RAMA RAMAKRISHNAN: Perfectly said. That's exactly the advantage. So we take a small amount of data, and we say, hey, we know this is not all the data, it's just a small subset of the data. So therefore, it's not going to be super accurate. It's going to be approximate. But it's OK. So we still tend to move in the right direction. So instead of waiting for the whole thing to get done and then updating it, we're just going to update it as we go along. All right. Yes. AUDIENCE: Another question. Is it that doing this process, SGD, will render us a more better solution, or it requires less compute power? RAMA RAMAKRISHNAN: Both. AUDIENCE: Both. RAMA RAMAKRISHNAN: Both. And the reasons for both are in the previous lecture. Yeah. And I'm saying that instead of repeating it, just because I'm very pressed for time today.

That's why. All right. Cool. So that's what we have. Are we good? OK. So now we come to the last step before we actually fire up the Colab, which is overfitting and regularization. So if you remember from your machine-learning background, when your model gets more and more complex-- use a simple model, then use a more complex model, and so on and so forth-- what happens to the error on the training data, typically? What happens to the error on the training data? So let's say you have a simple regression model. You get some error. And then you have a regression model in which you use all kinds of interaction terms, you use logarithms, and this and that, and make it super complicated. What do you think is going to happen to the error on the training data? AUDIENCE: Reduce. RAMA RAMAKRISHNAN: Reduce. Basically, it's going to go down as the model gets more complex. Correct? Now, of course, comes the punchline, which is, what do you think is going to happen to the training data? I showed you the answer.

Basically, what's going to happen, typically, at least conceptually, is that it's going to get better and better. At some point, it's going to bottom-out, and it's going to start climbing again. And so we typically refer to this phenomenon here, when it starts to climb again, as overfitting because the model is essentially fitting to the idiosyncrasies of the training data as opposed to generalizing patterns. And then, in this thing, we call it underfitting because still there's a lot of potential to improve. And we really are hoping to find the sweet spot in the middle. That's the basic idea of overfitting, underfitting. And the way we-- and to relate this to neural networks, as you see, as you've learned so far, you have to learn smart representations of the input data. And to do that, I have argued that you need to have lots of layers in your network. The more layers you have, the better things get. GPT-3, for example, has 96 layers, if I recall.

More layers the better. But more layers means more parameters. More parameters means more complexity to the model, and therefore more chance of overfitting. So it's really important in neural networks that we think about regularization. And regularization, you will recall from your machine-learning background, is the way we handle the risk of overfitting and try to find models that fit just right. And so several regularization methods have been developed over the years. And we are going to use only two of them. The first one is called early stopping. And this has been famously referred to by Geoff Hinton, who is one of the pioneers, or as he's more colorfully known, one of the godfathers of deep learning-- he also won the Turing a few years ago-- as a "beautiful free lunch." That's what he calls it. So the idea is very simple. We take a validation set. We take the training data, we split it

into a training and a validation set, and then we just keep doing gradient descent. Bup bup bup bup bup bup. The training will hopefully keep on getting better and better. Lower and lower error. And then we just keep track of what's going on in the validation set. And then, at some point, if it starts to flatten out and start to climb, we just say, OK, that's when we stop training. And what we're going to do in the Colab is actually run it through the whole thing, see where it flattens out, and then we say, OK, that's where we should stop. But of course, you don't want to go all the way to the end and then go back and say, well, I want to stop at the 10th epoch. And there are ways you can use Keras to be very efficient about this. But the fundamental idea is you take the training data, split it into training and validation, and just track what's going on in the validation set to see whether this kind of bottoming out happens. So this is called early stopping.

And the other way we're going to do-- this is called early stopping. We're looking for this part. The other thing is called dropout. And I'm going to come back to dropout on Wednesday's lecture because that's the first time we're going to use it. And so I'll come back to dropout and tell you exactly how it works. It's a very, very clever strategy, but we will not use it today. We'll use it on Wednesday. So in summary, what do we do? We get the data ready. We design the network-- number of hidden layers, number of neurons, and so on and so forth. We pick the right output layer. We pick the right loss function. We choose an optimizer. As I mentioned earlier, SGD comes in lots of flavors, lots of variations on the theme. And empirically, much like for hidden-layer neurons we tend to use ReLU as the activation function, for optimization, we tend to use a flavor of SGD called Adam as the default

because it's really good. So we'll use Adam, as you will see. We typically use either early stopping or dropout. And then we just fire it up and start training Keras in TensorFlow. All right. So that is the training loop. Now I'm going to switch gears and give you a quick intro to Teras and Kensor-- Teras and KensorFlow. Keras and Tensor-- no, TensorFlow and Keras. Thank you. And then we'll actually fire up the Colab. So first of all, what's a tensor? AUDIENCE: Yeah. Just a quick question on the previous thing. If you're looking at the validation sets to avoid overfitting, but aren't you actually overfitting because you're kind of using the validation set as a training set? Or not. RAMA RAMAKRISHNAN: No, no, no. The validation set is never used to calculate any gradients. It's only used to calculate accuracy and loss. Yeah. It's kept aside and only used for evaluation, not for training. That's what keeps you honest.

All right. And this will become clear when we actually go into the Colab. So what's a tensor? All right. OK. AUDIENCE: Tensor is the input data, which you're giving to the system. It could be in various formats like, for instance, an image. It could be-- like we call it a 4D tensor. If it's time series data, it's 3D. And typically, if we just send numbers in, it becomes a vector, which would coincide. It gives the value of the variable as well as-- the values of the variables associated to it, as well as the information you want [INAUDIBLE].

RAMA RAMAKRISHNAN: You're kind of on the right track, but not entirely. It's actually a simpler concept than that. So-- AUDIENCE: A matrix, but generalizable with higher dimensions. RAMA RAMAKRISHNAN: Correct. That's also actually correct, but incomplete. The reason is because it can be simpler than a matrix. It's not matrix or higher. It actually could be simpler. In fact, you take a number, it's actually a tensor. All right. The simplest case of a tensor is a number. The next simpler case is a vector, which is a list. The next higher case is a table. So these are all tensors. So tensors, basically, are a generalization of the notion of both a number, a vector, and a table to higher dimensions. So you can think of a tensor as having what are called-- every tensor has something called a rank. So a number is just a number. It doesn't have a dimensionality to it. So it has got rank 0. OK?

While a vector, it's a list of numbers. You can write it down, top to bottom, and it's one dimension. So that dimension, that one dimension, is called a rank. So it's called rank 1. A table is 2D, two dimensional, so it's called rank 2. And you can have a rank 3, which is just a bunch of tables. A bunch of tables is a rank 3 tensor. We also think of it as a cube. So these things are very useful because, obviously, we are all familiar with vectors. As you will see very shortly later in this class, black and white, grayscale images, are usually represented using tables of numbers, like this. Color images are represented using three tables.

Can you think of what might be representable as a tensor of rank 4, meaning, every element of a tensor of rank 4 is actually a color picture? Shout it out. AUDIENCE: Video. RAMA RAMAKRISHNAN: Video. Exactly. What is the video? A video is basically a stream of color images. A color video. So each element of that stream, the first dimension of the tensor is which frame it is, and then everything else is the actual frame. So the way I think about these tensors always is-- if you take a tensor, you can just think of it as a-- you can think of a tensor as being this array, which has all these axes or dimensions.

This is the first one, this is the second one, this is the third one, and so on. This is a tensor of rank 4. 1 2 3 4. And so if you have a vector-- so you can imagine, if it's just a vector, you can imagine the vector actually living like this. Just a list of numbers. But if it's just-- if it is just a 2D, a rank 2 tensor, which is just like that-- which is just like that. So this thing becomes like that, and that thing becomes like that. So for example, if this is a 7 comma 3, that means that there are 7 rows and 3 columns. So you get the idea. So the way you think about tensors is always as if there's open square bracket, a bunch of things, a closed square bracket. And that's really what a tensor object is.

So what that means is that anytime you have a tensor-- anytime you have a tensor, however complicated it is, you can always create a more complicated tensor by-- if you want to take a list of those tensors-- let's say that you have a list of videos. Each video is a rank 4 tensor, which means a list of videos is what rank? AUDIENCE: 5. RAMA RAMAKRISHNAN: Exactly. So a tensor of rank, say, 10, is just a list of rank 9 tensors.

So that is the most important thing you need to understand about tensors. So at any point in time, if I give you a tensor, you can just iterate through the first dimension of it, the first aspect of it. And as you go through each one of these values-- so for example, here, yeah, that can do it. So if you have this tensor here, and if you want to create a more complicated tensor, no problem. So you add another dimension here.

And now it just becomes-- this dimension, let's say, has 9 values. 0, 1, all the way to 9. So you put 0 here. And then what do you get? This whole tensor is a rank 4 tensor. And you put a 1 here. It's another rank 4 tensor. You put a 2 here. Another rank 4 tensor. So every tensor, you take the first element. It's just a list, but it's a list of the next down-rank tensor. Now, this tensor concept is actually something Einstein came up with. And so it's simultaneously kind of easy to understand and also slippery. So I would actually encourage you

to read the book, which has a really good discussion of tensors. And the more you practice with it, the easier it'll get. So if you feel you kind of understood but not quite, you're not alone. It happens to all of us. You have to pay the price and go through the crucible. OK? All right. So to come back to this, that's what we have. And we already talked about a rank 4 tensor. It's a video. So 2.2, the text has a lot more detail. You should definitely read it. So here, TensorFlow is a library. And as you can imagine, neural networks, tensors come in and go through the network and go out the other end. And since tensors capture everything-- numbers, lists, tables, and so on and so forth-- it's just tensors flowing from input to output. Hence, it's called TensorFlow. And it gives you a couple of things

which are really, really important, which is why we use it. The first one is that it will automatically calculate gradients for you of arbitrarily complicated loss functions. You don't have to calculate the gradient because calculating the gradient is very painful. It will automatically calculate the gradients for you. That's the best part. You don't have to use the chain rule. You don't have to do anything. The second thing it will do, it gives you all these optimizers, including SGD and all its variations, so you don't have to worry about the optimization itself. You can just pick and choose what you want. Third, if you have a lot of servers, it will actually take the computational load and distribute it across all those servers. People here with a CS background know that parallelizing computation is actually a very difficult problem. There are things which are called embarrassingly parallel.

Many things are not. And it's actually quite tricky to figure it out. You don't have to figure it out. TensorFlow will figure it out. And then finally, I talked about the fact that there are these things called GPUs, Graphics Processing Units, which are parallel hardware. And so, even if you have just one computer but it has GPUs, there's a particular way in which you have to take your computation and organize it to really exploit the fact that you have a GPU. And so TensorFlow will actually do it for you, out of the box, automatically. You don't have to worry about any of that stuff. So those are all the advantages of this thing. By the way TPU is called a Tensor Processing Unit. It's something that-- you can think of it as Google's GPU. They came up with their own variation on the theme. Now, Keras sits on top of TensorFlow. This is the hardware you have. TensorFlow sits on top of the hardware.

Keras sits on top of TensorFlow, and it basically gives you a whole bunch of convenience features. So for example, it gives you the notion of a layer. We already saw, keras.dense is a dense layer. It gives you the notion of a layer, it gives you the notion of activation functions, and so on and so forth. It gives you easy ways to preprocess the data, easy ways to train the model, report on metrics, calculate validation loss, validation accuracy, training loss, all the metrics we care about. And then it also gives you a whole library of pre-trained models that you can just use and adapt for your particular problem. So it gives you a whole bunch of conveniences. And that's why it's very popular. And by the way, many of you might also be familiar with PyTorch, which is a fantastic framework as well for deep learning. And the reason we chose to go with TensorFlow for this course,

rather than PyTorch, is because we wanted to make the course accessible to folks who don't have a ton of programming background before coming to the class, and PyTorch is a bit more demanding from a CS perspective. It requires more knowledge of object-oriented programming, which is why we decided to go with TensorFlow and Keras, because I think it's actually as powerful, in many ways, and it's a little easier to get going. So that's what we have here. And one other thing I will mention is that there are three ways in which you can use Keras. There are three kinds of APIs-- sequential functional, subclassing. And we'll almost exclusively use the functional API. And in fact, the model we built for heart disease prediction uses the functional API. And so just read 7.2.2 of the textbook to understand in detail how the API works. I find in my own work, the functional API is basically all I need. I don't need to do anything more complicated than that.

And as you will see as you work on the homeworks and on your project, it's sort of a beautifully designed LEGO-block environment for doing these things. And you can create very complicated models very easily. There is a whole bunch of stuff here on these websites, so check them out. Lots of Colabs are available. So now, if you go back to the neural model for heart disease prediction, this is what we came up with in the last class. We had an input layer, one dense layer with 16 neurons, ReLU neurons, an output layer with a sigmoid, and then, boom, that was a model. So let's train this model. And so the training checklist is that we have already done this. Hidden layer of 16 neurons. Sigmoid. We need to use an appropriate loss function based on the type of the output. What loss function should we use? What is the output here? It's a binary classification problem. So what should the loss function be?

I kind of heard it somewhere. You can shout it out. AUDIENCE: [INAUDIBLE] RAMA RAMAKRISHNAN: The output is a sigmoid. The loss function. AUDIENCE: Binary cross-entropy. RAMA RAMAKRISHNAN: Binary cross-entropy. Remember, if you're predicting a number, an arbitrary number, you can use something like mean squared error. If you're predicting a probability, which has to be compared to a 0, 1 output, which is what binary classification is all about, we use binary cross-entropy. So that's what we do here. So we do binary cross-entropy. And then we will go with Adam. And then we will use early stopping to make sure we don't overfit. I know this-- OK, I promise, this is literally the last slide before I go to the Colab. I feel like one of those used car salesmen. Wait, there is more! So anyway. So don't worry if you don't understand every detail of what I'm going to go through. I'm going to link to the Colab as soon as the class is over.

But once you get your hands on the Colab, make sure you actually go through every line in Colab. What I typically do when I'm trying to learn something new is I'll actually cut and paste. I won't do that. I won't actually cut and paste the code and run it myself. I will retype the code. If you retype the code as opposed to cutting and pasting, trust me, you will learn a lot more. So I strongly encourage you to do it that way. And so all the Colabs you're going to publish in the class, the first thing you should do is you should just make your own copy of the notebook. Copy to Drive. And then, if you're using anything other than today's Colab, anything involving natural language processing or vision, you probably should use a GPU. So just go into-- you go in here, choose the runtime to be GPU, and then you start your notebook, and you're done. And the second time onwards, you can just go directly to this step. You don't have to do all this stuff for that particular notebook.

There are numerous tutorials, like five-minute videos and so on, on how to use Colab. Just do that. I'm not going to spend time on it here. All right. OK. So I just ran it a few hours ago. I'm not going to run every cell now because this is going to take some time. It's going to get in the way of the class time. But I'm going to just go through it slowly and explain what's going on. So here, this is just an introduction to the data set. We already saw this introduction last week. We have whatever-- 303 patients. Heart patients. We have a whole bunch of variables here-- age, demographics, and a whole bunch of biomarker information. And this is our target variable. 0 or 1. Heart disease, yes or no. And so, by the way, just some technical preliminaries here, basically every time we load these things, we're actually going to load these packages. So you can see here, these are the two key things we need to do. We import TensorFlow first.

And then, from within TensorFlow, we import Keras. That's what these two lines do here. And folks who have done data science and machine learning a bit before, you'll know this. We will actually load the three packages that were just most commonly used right, which is NumPy, Pandas, and Matplotlib. NumPy, because it's very easy for manipulating matrices and arrays and tensors. Pandas because, oftentimes, you get some data from somewhere, you need to massage it and wrangle it to a point where you can actually feed it into Keras. So you need pandas for that. And Matplotlib because you just want to plot these loss curves and accuracy curves to see whether early stopping is needed. So that's why we use it. So we import all these things. And then, I guess the other thing you have to remember is that when we are training these deep-learning models, there is randomness in the process, which enters in a few different places.

So clearly, the starting values for these weights are going to be-- the weights are going to be randomly initialized. And therefore, that's obviously a source of randomness. Now, we talked about how you take-- when you're doing stochastic gradient descent, you take all the data, and then you randomly choose batches right from this data till we finish a whole pass through it. Well, that immediately raised the question, well, what do you mean by randomly choose? So typically, what we do in practice is that-- and Keras will take care of all this for you-- you basically take the data and just shuffle it once, randomly. And then you just go first 32, next 32, next 32, next 32, like that. But it is a source of randomness. And then when we split the data into train, validation, testing, and so on, particularly if you want to look for early stopping and overfitting, we need to again split the data randomly. And that's another source of randomness.

And then when we do dropout, which we will talk about on Wednesday-- again, dropout has a little bit of a random element to it, and so that's another source of randomness. So all this means is that if you're working with these models and if you want to build a model and you want to hand it off to someone so that they can reproduce your results, well, you better make sure that you make it easy for them to replicate what you have. And the way you do it is by sending a random seed for all these things. And the way you do it is by having this little handy function here, set_random_seed. And of course, I use 42, just like everybody should. So that's that. By the way, that's just a pop culture reference to this book called The Hitchhiker's Guide to the Galaxy. So when I say something about the number 42, and you'll know what I mean. So by the way, the question inevitably comes at this point,

OK, if we do exactly this, will we actually get the exact same numbers that you have in your version of the notebook? And the answer is, hopefully, most of the time, but it's not guaranteed. So this is called bitwise reproducibility. It's not guaranteed due to certain hardware things and device drivers and stuff like that, so we won't get into all that stuff, which is why, as you see here, I have a bit of a fingers-crossed thing. All right. Cool. So that's what we have. So as it turns out, Francois Chollet, who wrote the book, the textbook, he actually made this data available in a Pandas dataframe. So we read the CSV file into this dataframe right there. And then it's 303 rows, 14 columns. And you can see here, we'll take a look at the first few rows. And these are all the rows-- age, gender, cholesterol, blah, blah blah blah blah. And then this is the target variable right there. And one of the first things I always

do when I'm working with a binary classification problem is to quickly check whether the positive and negative classes are balanced or not. And so what you can do is you can just quickly check to see what percent of the data points is 0 versus 1. And you can see here, 72.6% of the patients don't have heart disease. That's a good thing, of course. And then 27.4 have heart disease. So it's not 50/50 or roughly 50/50. It's a little thin. So by the way, quick question. What is a good baseline model for this problem? Suppose you couldn't use anything, any complicated thing. What's a good baseline model? Let's go to this other side. AUDIENCE: Yes. Just predict zero every time. RAMA RAMAKRISHNAN: Why would you do that? AUDIENCE: It would give you a 72.6% accuracy. RAMA RAMAKRISHNAN: Exactly. Because 72.6% is the higher class, higher class of the higher percentage, you just predict it. You'll be right on those 72.6% of the cases, you'll be wrong on the rest, which

means that your accuracy of this model is going to be 72.6%. And so any fancy model we build, it's got to do better than this. Otherwise, it's not worth its weight in layers. All right. So we'll come back to this later. So the first thing we want to do is we want to preprocess it, because this data set has both categorical variables and numeric variables. And so it's usually convenient just to group them into two different groups. So I have listed all the categorical variables here and the numerics here. And then we have the preprocessing here. We have to take the categorical variables, and we have to one-hot encode them. And the reason is that unlike, say, a decision tree model, a neural network cannot handle categorical inputs directly. It can only handle numeric inputs, which means that we have to numericalize every categorical thing that comes in.

And there are many ways to do it, but the standard way to do it is one-hot encoding. And for the numeric variables, we need to normalize them. And I'll come to that in a second. So Pandas has this get_dummies function here. And you can just run this thing, and it will just one-hot encode the whole thing. So once you do that, this is what you have. So you can see here, previously, let's say, thal had three values-- fixed, normal, reversible, or something. And then you go to the one-hot encoded version. And now we can see here, thal_fixed, thal_normal, thal_reversible. That's three columns. That's the one-hot encoding in action. Now, the other thing to remember is that neural networks work best when the numeric inputs you send them are all in a relatively small range. They shouldn't have a wide range of variation. And so the standard practice is to standardize

the numerical variables. By standardize, I mean typically subtract the mean, divide by the standard deviation. We should do that. But before we do so, we should split the data into a training set and a test set. And why do we want to split into a test set? Because at the very end, once we have built the model and done all the things we want to do with it, we finally want to take out the test set and evaluate it once so that we get this true measure of how it's going to perform in the wild after you deploy it. So you want to divide it, let's say, 80% training and 20% test set. So the question is, why should we do the splitting now before we do the normalization? Why can't we just do the normalization and then do splitting?

All right. AUDIENCE: Because then your validation set is also somewhat dependent on your test set results, as well as the mean of the test set. RAMA RAMAKRISHNAN: Correct. Because the test set has now essentially been influenced by the training set. The modeling process-- part of the modeling process is the splitting. And the splitting also-- the standardization-- if the standardization, which is part of the process, uses information about the test set, well, the test set is not really kept away from anything, is it? That's why we want to split it, lock away the test set somewhere, and then proceed with the modeling. Again, this is like machine learning 101, which is why I'm going through it pretty fast. So we do this sampling function, take 20% of the data, and make it the test set. And the remaining is going to be the training set. And when we do that, you can see the training set is now 242 rows, while the test is 61 rows.

And any of these data frames, you'll know the shape attribute gives you the dimensions of the number of rows and the columns. That's what we're doing here. And now that we have done that, we have done the split, we can calculate the mean and the standard deviation. So I calculate the mean here. I calculate the standard deviation. These are all the means. And once I do that, I just do each column minus the mean, divide the standard deviation. And then once I do that, I save them in the train and the test dataframes. And you can see here now all the numbers are all very smallish-- 0, 1, minus 1, around that range. And that's kind of ideal for neural network training. OK? All right. So at this point, the data is entirely numeric. And then we are almost ready to feed it into Keras. And the way you do it is you take a NumPy array-- you take a Pandas dataframe, and then you

convert it into a NumPy array. And then Keras is happy to take it, happy to receive it. So we use this thing called to_numpy, which I think is as descriptive as it gets in programming. And then you save it as train and test. Now, train and test are two NumPy arrays with exactly the same information, and now we can feed it into Keras. All right. Now I guess there's one other thing we need to do, which is that in this dataframe, train and test are independent variables. All the features, as well as the target, the 0, 1 target, they're all in this. And we need to now take it and just take the dependent variable, the 0, 1 column, and split it out, and keep the x and the y separately. That's the whole point of it. Because you need to feed the x, do the prediction, and then compare it to the actual y, and calculate the loss, and so on and so forth. So the target column is our y variable. And it's column number 6 from the left. If you count it, you can see it.

So we delete it from the train and test. And now we have 242 rows and 29 columns, 29 features. You will recall from the network that we made way back, it had 29 inputs, 29 nodes in the input layer. And that's where the 29 is coming from. And so now we just select the sixth column, which is the target, and make it the y variable, train_y and test_y. And that is, of course, a vector, which is 242 long in the training set and 61 long in the thing. So at this point, all we have done

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent