Linear Regression with Scikit-Learn
Transcript
This course is a practical and hands-on introduction to machine learning with Python and Scikit-Learn for beginners. It is designed and taught by Aakash N.S., who is the CEO and co-founder of Jovian. You'll learn about a bunch of common machine learning models and different types of machine learning. By the end of this course, you'll be able to confidently build, train, and deploy machine learning models in the real world. The topic for today is linear regression with Scikit-Learn. This is the first topic we are covering in machine learning with Python. And in fact, one of the things we'll try and do today is to apply linear regression to a real world problem. And we'll try to predict medical expenses using this technique. So here's an overview of what we are going to cover today. Just a quick outline. So first we start by stating a typical problem statement for machine learning. Then we will download and explore a dataset.
Then we will perform linear regression with one variable using Scikit-Learn. Then we'll perform linear regression with multiple variables. And don't worry if these terms don't make sense right now. They will by the end of this session. Then we'll use categorical features for machine learning. Learn how to apply that in general, not just for linear regression. We will also talk about regression coefficients and feature importance. How do you interpret the outputs of a model that you create?
And then we will apply linear regression to some other datasets. This tutorial is an executable Jupyter notebook hosted on Jovian. And you can run this online on binder or you can run this on your computer as well. You can also run this on Google collab and that's perfectly fine too. So here's the problem that we will solve today. And using this problem, we will define the terms machine learning and linear regression in the context of this problem.
And then later we'll generalize their definitions. Let's read the problem carefully. And then we'll think about how we can approach this problem. Acme insurance incorporated offers affordable health insurance to thousands of customers all over the United States. And as the lead data scientist at Acme, you are tasked with creating an automated system to estimate the annual medical expenditure for new customers using information such as their age, sex, BMI, children, smoking habits,
region of residents, et cetera. Why are you asked to do that? Because estimates from your system will be used to determine the annual insurance premium, which is the amount paid every month or every year. That is offered to the customer. So your job is to figure out when a new customer applies for medical insurance based on information like their age, sex, BMI, et cetera, how much they might incur in medical bills in an average year.
If you can find that information along with some other information can be used to determine what you should charge the customer for insurance. And this is a typical problem that you will face and it's a typical example of a machine learning problem where you want to replace some manual decision making or one, one piece of a manual decision making process with some automation. So in this case, for example, you may need an expert who has seen customers for several decades to figure out based on this information, what their medical information might look like, or if you're a data scientist, you can figure that out using data and that's what we're going to create today. You need some data to actually figure this information out, but fortunately because Acme insurance already has thousands of customers, they have given you a CSV file. So here's a CSV file that your manager or whoever is working on this
project has given you, and this CSV file contains historical data. Let's say from the past year for over 1300 customers, you can see here we have information like age, sex, BMI, the body mass index, number of children, whether this person is a smoker or not, which region of the country they belong to and the actual medical charges they incurred in the previous year. All right. So we have some historical data and we would want recent historical data not going too far behind because medical charges can change due to inflation and due to other reasons as well.
So that's the data you have. And your job is to create some kind of a system which can take this information age, sex, BMI, children, smoker region for a new customer and estimate what their charges are going to be over the coming year. Okay. And here's a source for this data set. This is a popular data set that is used in machine learning. Now, before we proceed further, just take a moment to think about how you can approach this problem.
Let's begin by downloading the data. So we will download the data using the URL retrieve function from URL lib.request. This is a simple function that's already present in the Python standard library URL lib. So let's get the URL into a variable called medical charges URL and let's import from URL lib.request from URL lib.request the URL retrieve function. Let's call URL retrieve with the medical charges URL and let's download the data to this file, medical.csv.
Okay. So now we have a file medical.csv, which should have the required data. Next is to create a pandas data frame using the downloaded file to view and analyze the data. So let's install the pandas library using pip and then we import pandas using the alias PD, and then we call PD dot read CSV and give it the name of the CSV file.
And here we have the data frame. So the first step is to get the data into your Jupiter notebook, no matter what kind of problem you're working on, whether it is data analysis or machine learning. And one way to get the data is by downloading it using URL lib. The other way to do it is you can go file open and then you can click the upload button here. You can click the upload button here and upload the file from your computer. We've also looked at other ways to download datasets, for example, from Kaggle and we will apply all of these different techniques at different points in this course. So here's the data and this data contains 1,338 rows and seven columns.
Each row of the dataset contains information about exactly one customer. Our objective is to find a way to estimate the value in the charges column using the values in the other columns. Now, if we can do so for historical data, then we should be able to estimate the charges for new customers too, simply by asking for their information like age, sex, BMI, et cetera, maybe in an application form. Okay. So let's first check the data type for each column. We go medical DF dot info and we have seven columns age and age
age seems to be an integer sex seems to be a string, as you can see here, male and female. So actually it's more of a categorical column, but let's just call it a string for now BMI seems to be a floating point number, and you can see here in BMI, we can have these decimals each can also have decimals, but it looks like we've only collected the integer portion of the age. So that's what we're working with. Then we have children. This is the number of children, the customer has, and this is again an integer and typically this would be a number like zero, one, two, three, then we have smoker, whether the person smokes or not, and this has a yes, no answer. So this was probably a tick box somewhere in a form.
So this is also a categorical column, which we have in the form of a string right now, then we have a region. So it seems like there are different regions, customers, customers, can belong to like Southwest, Southeast, Northwest, Northeast. Seems like there are four of them, but we'll have to check. And finally, we have the actual annual medical charges incurred by the customer, so there are numeric columns, and then there are categorical or string columns, and among the numeric, there are integers and floating point numbers as well. Now, one good thing here is that there are no null entries. If you see here, no, no count that is one three, three, eight, which is also the total number of entries. So that means that there are no empty values in any columns.
So none of the columns contain any missing values and that already seems as a fair bit of work, but don't worry, we will deal with missing values in future lessons. Next, let us look at some statistics or the numerical columns. So if we call medical DF dot describe that is going to give us information like the count means standard deviation, minimum, and all the percentiles like 25 percentile, 50 percentile, which is the median 75 percentile and the maximum, and this is always a good thing to do at the very beginning just to see if the data, the range of data makes sense. And I would say that the data makes sense. It seems like the average age is around 40 seems like the standard deviation is 15. Minimum is 18 maximum is 64. Okay. We already know that 18 is the minimum age, 64 is the maximum age. They both seem reasonable, but this also tells us that perhaps the insurance company does not take applications below the age of 18 or above the age of 64.
Then we have the BMI. So with the BMI, it seems like the minimum is 15. So the BMI just to give you a sense of what the average age is. The BMI just to give you a sense is the mass of a person in kilograms divided by the square of their height. So it's a ratio of mass or weight to the square of a person's height in meters. So BMI, this is in the units kilograms per meter square. So it seems like the BMI is the minimum is around 15.96 or 16 and the maximum is around 53. Okay.
Then we have the number of children that goes from a minimum of one to a maximum of five. Then we have the actual medical charges which go from a minimum of one, one, two, one. So just a thousand dollars, this person basically did not go to the hospital at all during the year to a maximum of $64,000. So you can see that there is a huge variation in the charges from thousand to 64,000, not only that you can also see that if you check the 50% mark, 50% of people have their medical charges under $10,000 or even 75% have it under $16,000. So that means there is a huge skew or there are several outliers in the charges column. And we'll see that in more detail once we study the visualizations, but even just by looking at these numbers, you can tell some of these things. The mean is 13,000, but the 50% mark is 9,000. So there's a bit of a skew in the data.
So this is what you should do whenever you load up a data frame, just look at the data, just look at all these statistics and try and draw whatever inferences you can in this case. Once again, there don't seem to be any incorrect values like negative ages or ages greater than 200, let's say, or any negative values. Everything seems nice and clean. So somebody has put together this dataset for us, made sure that it is pristine. All the data is valid and there is no missing data that makes our job a lot easier.
So that was downloading the data. So let me just save my project at this point. I'm just going to import the Jovian library and click Jovian.com it. Make sure you're saving your notebook from time to time. So now we've downloaded the data. So let's start by doing what we know. Let's start by just doing some exploratory analysis and visualization. And let's see where that can take us. We will visualize the distributions of values in some of the columns. And we will also find the relationships between the charges columns and the other columns, because we have to use the other columns to predict charges. And we will use the libraries, matplotlib, seaborn, and plotly for visualization plotly specifically, because it will give us some interactive charts and save us some coding, but a lot of all of these plots can be done using just matplotlib and seaborn
as well, and I've linked to some tutorials here that you can check out in case you want to refresh or learn one of these libraries. So I'm going to install these libraries first using pip. All right. And then I'm going to import these libraries. So I'm going to import plotly dot express, which is a high level API that makes it really easy to create plotly interactive charts. Then I'm going to import matplotlib and I'm going to import matplotlib dot pipe lot as PLT, this is how typically matplotlib is done. So I'm going to import that. I'm going to import matplotlib. And finally, I'm going to import seaborn as SNS.
So these are all the conventional ways in which these libraries are imported. One last thing we have is matplotlib inline. The purpose of this line is to ensure that any charts that you create, they show up as outputs within your Jupiter notebook and not as popups, because when you close a pop-up, the chart goes away. Okay. All right. So now we have imported the libraries. One other thing I'm going to do is just change some settings, which will improve the default style and the font sizes for our charts, which is going to make the font sizes a bit larger and use the dark grid style for seaborn. This will only apply to matplotlib and seaborn, not to plotly.
Okay. Let's begin with the first column age and age is a numeric column. The minimum age in the dataset is 18 and the maximum age in the dataset is 64. So we can visualize the distribution of each using a histogram, essentially trying to find out how many people, how many customers we have for every age. From 18 to 64. So that means we need 64 minus 18 plus one or 47 bins, one for each year.
And that way we'll be able to visualize it using a histogram. Another useful plot is a box plot. A box plot is also quite useful because it tells you the minimum, the maximum, the median, and all the columns. So that can give you a sense of the distribution of, of where the 50% point lies. And using plotly, we can actually create both of these charts with just one line of code. We say PX dot histogram pass in the medical DF data frame.
And then we specify that we just want to use the age on the X axis. And we want to use the age on the X axis. And we want to use 47 bins and we want to give the charter title distribution of age. Now, by adding this marginal equals box parameter, plotly will also plot a box plot right above the histogram for us. So here's what the distribution of age looks like. You can see here at the age of 18, we have 69 customers at the age of 19. We have 68, then we have anywhere from 20 to 30 customers at every age. It seems like a lot of people here in the range of 40 to 50. And then here we have the highest age, which is 64 and nobody beyond the age of 64.
It's a nice uniform distribution. If you just ignore these two values, you can see that the midpoint is around 39. Almost. And the quartiles are also equally balanced on each side. So the distribution of ages in the dataset is almost uniform with 20 to 30 customers for every age, except for the ages of 18 and 19, which seem to have over twice as many customers compared to other ages now to explain this piece, the uniform distribution might simply arise from the fact that there is not a big variation in the number of people at any given age between 18 and 64 in the United States. For example, if we open up this other chart that's available online, this tells you the
population and different age ranges. So you can see here 15 to 19, 20 to 24, 25 to 29. So it seems like the, and it's split across male and female, but the overall population you can clearly see across different age groups is fairly similar. And you can assume that there is a certain percentage of people, certain percentage of population that takes their insurance from ACMA insurance incorporated. So that's why you see this kind of a distribution, which reflects the overall population. This is always something that you should check whenever you have a dataset. Does that make sense? This is always something that you should check whenever you have a dataset does the data
you have reflect the distribution of the overall population or not. But in this case, in one case it does not. And I will let you figure out why this might be the case. Can you explain why there are over twice as many customers with the ages 18 and 19 compared to other ages? If I had to guess, I would probably guess that maybe ACMA insurance is offering a lower insurance premium. If you sign up before the age of 20, that could be one reason.
And also because maybe 18 is the legal age for you to be able to get insurance, at least from this company. So a lot of people, as soon as they turn 18, get the insurance that could be one of the other reasons, but neither of these, we can assume we would have to then go and verify if this is indeed the case, maybe even look at some industry averages. If we can find some reports online. Okay. So that was the distribution of each. It was mostly uniform with a couple of years where we had twice as many people. Next, let's look at the distribution of body mass index. Once again, we are going to create a histogram of the body mass index. And this time we're going to use the red color and we're going to have a box part once again.
So here is a distribution of the body mass index. And this looks very different. It seems like it is distributed according to a Gaussian distribution or what is also called a normal distribution. Here's what a normal distribution looks like. So if you have a certain population of data. Yeah, this is the one. So if you have a certain population of data where most of the values are centered around a single value, the, what is called the mean, and then you have a decreasing probability as you go away from that mean that's called a normal or Gaussian distribution. And this is exactly what is visible here.
Why is this Gaussian and why is the previous one normal? I let you think about that. But what we can notice here with BMI is that most people have a BMI or a body mass index around 30, maybe in the range of 25 to 35. And then as you get further away, fewer people seem to have that BMI. So 25 to 35, roughly speaking might represent the average human in terms of the ratio of weight to height. And here's how you can interpret body mass index values. Or this is how that typically interpreted less than 18.5 is considered underweight.
And then 18.5 to 24.9 is considered normal to overweight is well. 25 to 29.9 is considered overweight slightly more than 30, 30 to 39 is considered obese and greater than 40 is considered morbid obesity. Now, this is an important factor from the health perspective. Typically people are expected to be in the normal to overweight range. If they're underweight, then they are more susceptible to certain diseases.
And if they are obese or even morbidly obese, then they are more susceptible to certain illnesses as well. And this is why this is one important piece of information that is requested in your insurance form. So as we perform this analysis, as you see with age, you can see with age that there may be a certain relationship between age and medical charges, and you can try and guess what that relationship might be. And then there may be a certain relationship between BMI and medical charges as well.
With BMI, I'm guessing somewhere in between might be lower medical charges. If you're to either extreme, maybe you will have a higher medical charges. Now let's look at the most important column, the distribution of charges. And before I look at the distribution, do you want to take a guess on what the distribution of charges is going to look like? Just think about it. We've already seen the description. We've already seen the statistics for it. So here we are creating a histogram once again, BX dot histogram. And we have a medical data frame, the DA, the data frame on the X axis.
We want to show charges and we also want to show a box plot above the histogram. And then we want to set the title to annual medical charges, but we have another. Important section here. This is called smoker. So what we're doing is we want to split the histogram of charges for smoker versus not non-smoker. So we have a column smoker and we are going to use that to split the data. And here's what that gives us green represents people who have responded. Yes to smoker.
And no gray represents people who have not responded. Yes to smoker. So you can see here that people who are not smokers seem to have lower medical and lower annual medical charges. In fact, most people in general overall seem to fall in the maybe like 5,000. What is this? A 2000 to $15,000 expense category. So most people are spending between 2000 to $15,000, not more than that, which is not a very high expense. And then there are some people who need to spend a lot every year.
And there is a stark difference between people who smoke and people who do not. It seems like 50% the median for non-smokers is 7,300. And the medium for smokers seems to be 34,000. Now it's not entirely clear if this is because they are smokers. If it is just generally true that you will have a higher medical if you smoke regularly, or is it that more people who smoke are taking life insurance? And maybe fewer people who smoke or do not smoke are taking life insurance.
So we don't know what this means. All we know is that people have responded. Yes to smoker seem to have a higher median medical expense. But in general, you can see that this follows the exponential distribution or a more appropriately. This is called the power law. So in the power law, what happens is you have a lot of people along the smaller numbers. You have a lot of people who have a very low expense, and then you can see this exponential decrease. In the medical charges.
And if you were to separate out smokers and non-smokers and plot them separately. So you would see that for non-smokers, you have this exponential decay. And maybe for smokers, you have that as well, but it seems like there are two sections. Maybe this is just general smokers, and this is maybe smokers with some ailments, right? So there is something to discover here, why we're seeing this kind of a pattern. Maybe do we need another category of like light smokers and heavy smokers? We might need to look into this, but at the very least, we're already starting to observe some trends that the charges have that for most customers, the annual medical charges are under $10,000, $14,000. And only a small fraction of customers have higher medical expenses, possibly due to accidents, major illnesses or genetic diseases. And this is what happens. Most of the population is healthy.
Most of the population probably does not need to go to a hospital every year, maybe except for a few checkups, regular checkups, but some people unfortunately either have accidents or major illnesses or genetic diseases, right? So that's why they may incur a higher medical expense. And the second is that there is a significant difference in medical expenses between smokers and non-smokers. While the median for smoke non-smokers is 7,300. The median for smokers is close to 35,000. Okay.
So next up, here's an exercise for you visualize the distribution of medical charges in connection with some other factors like sex and region. So maybe replace this by sex and replace this by region and see if you see a similar disparity across males and females or across different regions. Okay. So while we're talking about the smoker column, let's try and visualize the distribution there. So let's just see how many examples we have for each.
So it seems like out of the 1300 or so people we have thousand or so have responded. No for smoker and around 274 have responded. Yes. So about 20% of the customers are smokers and we can visualize this using a histogram as well. So we say PX dot histogram. We pass in the data frame for X on the X column, we have smoker and let's break down the visualization by sex. This time. So here you can see that yes, represents people who've responded. Yes to smoker.
And that number seems to be in total about two 68 or so, and no represents people have responded. No, but this is also broken down by sex. So you can see that about 115 females said yes. And 159 males on the other hand, 517 males said no. And 547 females. So it seems that some people have responded. 547 females, so it seems that smoking is more common among males. And this is something that you should try and verify. This is something that you should try and verify.
And similarly, it also seems like 20% of the customers have reported that they smoke. So this is also again, something that you should try and verify, see if this matches with the national average. And you can assume that the data was collected in 2010. The data set has been around for about 10 years. Now, the reason you should verify these things as you're performing this analysis. And the reason you should perform this analysis in the first place is to understand if the distribution of the data that you have. Matches the distribution of the population itself, right? If your data contains 90% smokers, but in the general population, there are only about 10% smokers. Then any analysis that you do, or any model that you build will be wrong because it will be built under the assumption that 90% of the inputs that are coming to the model are going to have yes in smokers.
So that's why wherever you're building a model, make sure that the distributions of each column match the distributions of the populations where the model will be applied. So with that, we've looked at the individual columns. You can also try and visualize the distribution of sex region and children and report your observations. Okay. So now having looked at some individual columns, we can now visualize the relationship between charges, which is the value that we wish to predict and the other columns. I would guess that age would be one of the most important factors in determining your medical expenses. So let's visualize the relationship between age and charges using a scatter plot. So we use PX dot scatter. We pass in the data frame medical DF. We pass in the data frame medical DF.
And on the X axis, we want to show the age on the Y axis. We want to show the charges and we will show a single point on the chart for each customer. Now, whenever you have a Scott scatter plot, you should also use the opportunity to maybe add some color. So maybe let's color the points based on whether the person is smoker or not. And let us just set the opacity of points to 0.8 because we have over a thousand customers, so we may have some overlapping points.
So just so that we are able to better see the data, let's just reduce the opacity a little bit of the points. And finally, we're just setting a title as well. Okay. So now we have this chart and this looks very interesting. I can see three clear clusters here. Here's what I can see. I can see three clear clusters of points and each of which seems to form a line with an increasing slope. You can see that this seems to roughly lie in a line.
Of course it goes up and down, but roughly you can see a linear trend here. And then you have the second cluster, which also seems to have a somewhat linear trend as increasing with age. But if you look carefully, you have a mix of smokers and non-smokers in this cluster. It's possible that this is actually two different clusters, which just happened to fall in a similar place. For example, if I turn off smoker, this is what we get. So it seems like among non-smokers, most people incur a fairly low medical expense that goes from 0 to 5,000 at age 18 and goes up to 13 to 15,000 at age 64. But then there are some, as we said, there are maybe five, 10% of people who unfortunately due to accidents, genetic ailments or major illnesses have to spend a lot more. And then there's probably a similar trend here for smokers. You can see here, this is seems to be the baseline.
So probably if you're just smoking, don't have any other ailments, this is where you are. And then here you have another group of people. So it's possible that these are people who are smokers and have ailments, or as there was one suggestion, maybe it is a combination of being a smoker and also being obese. So it's possible that is, that could be the reason for this. So it's worth investigating, but you can see here, there are two clear sections. Maybe you need a smoker and a heavy smoker section. Maybe that makes a big difference. Maybe a two cigarettes a day doesn't make a difference, but 20 does. So all of these interesting things here, and that's what we've summarized here. And this is a general thing that you should do in your exploratory analysis. Whenever you observe a trend, summarize it and try to offer some explanation.
And you can mention clearly that there are certain hypotheses, like we're using the terms like it's possible, which means that this is something to be verified. And then presumably, which means that, okay, you have one cluster for smokers and one clusters for smokers with medical issues, or it could be smokers who are also obese. So we don't know, we'll have to study this. We'll have to dig deeper and try and figure it out. So I'll leave that as an exercise for you. And there are definitely more inferences that you can draw from the above chart. So I'll let you draw that as well. For example, what percentage of people lie outside the norm? So this, how many people lie in this region and how many people lie outside? And what are the number of outliers? Let's look at BMI. This seems again to be an important factor. So let's visualize the relationship between body mass index and charges using another scatter plot.
Once again, we will use PX dot scatter on the X axis. This time we will use BMI on the Y axis, we will use charges and we will color the points once again, using the smoker column. And we will set the opacity to 0.8 and we will set on hover. We'll also show the sex so that when you hover over a point, you have some more information and we set a title for the chart. So here's what the chart looks like. And now you can see that the picture is starting to get a little clearer.
So if you see here, if I turn off, yes, you can see that there seems to be no real relationship between BMI and medical charges. Maybe BMI is a flawed metric. Maybe it doesn't really make sense. You can see here that you have numbers all over the place. And if anything, you have some outliers here somewhere in between in the 20 to 40 range, not beyond 50 or not below 20. But that could also be because there are very few people below 20 or beyond 40.
But once you add in the smokers, or if you just look at the smokers, you can start to see a trend here. So it seems like there are two major clusters below the BMI of 30. Your medical charges stay low in about the 30 K range below the 30 K range and above 30, then they seem to increase. So smoking combined with obesity, it may appear it might seem that this might be a bad condition to be in. So this requires more investigation, but we're already starting to uncover more information.
At this point, if you have doubts, you should probably reach out to somebody in the company, somebody who actually has some expertise in the field and ask them if this is indeed the case. And all of these things are going to be important because the model that you build, you will have to explain why it gives the predictions that it does a lot of times because there are regulatory requirements. There are regulatory requirements in healthcare. There are regulatory requirements in finance and a bunch of other domains as well. So that's why understanding these relationships is important. What other insights can you gather? Just try and see if you can gather some other insights from this graph and try and create some more graphs to visualize how the charges column is related to other columns. For example, charges against children. Do you see that there is a general increase in charges when you have more children or charges with sex?
Do you see that there is a difference between males and females maybe compared with region and maybe directly compared with smoker? Maybe just look at the average charges for smokers and the average charges for non-smokers. Here's a hint for you. You might want to use the violin plot for some of these. For example, if you do PX dot scatter medical DF and on the X axis, you put children and on the Y axis, you put charges. There's a problem here.
You can't really tell much because the value of children is not continuous. It goes from zero to one to three to four to five. So we don't know if there are five points here or 50 points or 500. It's very hard to tell because they're all on top of each other. So if you just change scatter to violin, and if you've ever wondered why a violin chart is useful, now you will see just change it to violin. Now you can see that you also have this way for this chart. The width tells you how many values lie here relatively. So it seems like you have a bunch of values here, a bunch of values here, and then you have all these outliers. And now you can observe a general trend. You can see that the bulk of values shift up as we go with the number of children increasing such as the number of children increases.
The potential medical costs seem to slightly increase, not by a lot because there are many people who have a very low medical cost despite having four children. There are many people who have a very high medical costs without despite having high children, despite having zero children. Okay. But there is some sort of a trend here, a very weak trend, but a trend nevertheless. So as you can tell from the analysis, the values in some columns are more closely related to the values and charges compared to other columns. For example, age and charges seem to grow together and BMI and charges don't. So the relationship between two columns on whether they grow together or not is often expressed numerically using a measure called a correlation coefficient. And there's a certain formula for it and there's a certain meaning it has.
But first, let's just see how to compute the correlation coefficient. The correlation coefficient can be computed using the.corr or.corr method of a pandas series. So if we say medical DF dot charges dot core medical DF dot age. So we want to compute the correlation between charges and age, and it seems like the correlation is 0.29. Okay. And we'll see what that means in just a second. And then if you want to compute the correlation between the medical charges and the BMI, it seems like the correlation here is 0.19. So there's definitely a higher correlation between age and charges than there is between BMI and charges. And maybe let's also compare children. So with children, there seems to be an even lower correlation than the BMI. Okay. So that's how you compute correlation between columns. And you can also compute correlation for categorical columns. It won't work directly.
At least I believe it won't. Medical DF dot smoker, it won't work directly because you need numeric data to compute the correlation. So what do you need to first do is convert your categorical data into numeric data. So here's what I'm going to do. I am going to create a new series called smoker numeric. And how are we going to do that? We're going to take medical DF dot smoker and we can call dot map on it. So dot map takes either a function or a dictionary and it applies it to every value.
So here we've supplied a dictionary, no dictionary, which converts no into zero and yes into one. So when you call medical DF dot smoker dot map smoker values, then wherever you have a no, that's going to convert to zero. Wherever you have a yes, that's going to convert to one. So this is a very useful technique. Whenever you want to quickly convert some categories into numbers, let's, and let's compare that. Let's see medical DF not smoker. So you have, yes, no, no, no.
And you have one zero zero zero. Now, once it is converted into a number, you can then compute the correlation. So you see medical DF dot charges, not correlation smoker numeric. And that has a coalition of 0.787. So now you can start to see the train 0.787 for smoker. Probably the highest correlation. Then you have with age 0.299. Then you have with charges 0.19. And then you have with children 0.06. And then there are some other categorical columns as well. So we're not just, we're not done yet. So here's how the correlation coefficient is interpreted. It indicates two things. It indicates strength and it indicates the direction. So the greater the absolute value of the correlation coefficient, the stronger is the relationship. Which means that if you have an extreme value like minus one or one and one is pretty much the highest value that you can get, you cannot get something higher than one or lower than minus one.
That indicates a perfectly linear relationship where a change in one variable is accompanied by a perfect consistent change in the other variable. Which means essentially that these points lie on a line and there's a geometric interpretation here. So if you have X and Y, let's say age and charges, and you saw this kind of a graph, that would mean perfect correlation, correlation of one. This would be positive correlation. And if you had a chart like this, where it was a line, but one increase in one led to decrease in the other, that would be a perfect negative correlation close to minus one. But you generally have something in between. You have strong positive correlation where these points are distributed around the line or a weak positive correlation where there is a weak trend of some kind or no correlation at all where points are all over the place.
Or you can have a weak negative or strong negative correlation, right? So that's the direction, the sign of the correlation coefficients represents the direction of the relationship. If it's positive, then you have an increasing relationship. If it's negative, then you have a decreasing relationship. If the correlation coefficient is very close to zero, then you have practically no correlation. Okay. And the correlation coefficient has a formula and you can check out this formula. This is simply the sum of XI minus the mean of X, YI minus the mean of Y added up divided by a square root of some other quantity. I'll let you figure out what this formula means because it's not very important. It's simply a question of carefully looking at each of the terms and listing out what it means, but this is the more important interpretation that you should have. When you see correlations, you see plus one. This is what you see.
You see something, let's say greater than 0.5, greater than 0.7. This is what you should imagine less than 0.5. This is what you should imagine close to zero is this and less than zero. These are the pictures you should have in mind. Okay. And if you really want to learn the mathematical definition and the geometric interpretation, I have linked to a video here. But this picture pretty much summarizes everything we need to know. Okay. Now, the pandas data frames also provide a CORR method to compute the correlation coefficients between all pairs of numeric columns. So if I just call medical DF. CORR that's going to compute the correlation between age BMI children charges, which are the numeric columns with the other numeric columns. You can see age and age. So age has a perfect correlation with itself. If you plot age with age and you can do that, you can do something like this.
PX dot scatter you have medical DF X equals age and Y equals age. You see that there's obviously a perfect correlation. It's a straight line. So age has a perfect correlation, but what we're interested in is the correlation of charges with the other columns. You can see that age has a correlation of 0.299 with charges. BMI has a weaker correlation of 0.198 and children has an even weaker correlation of 0.067. Okay. And finally charges with charges obviously has a correlation of one.

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