- 7 weeks ago
Mastering Data Visualization: A Step-by-Step Guide in R
More free coding and data science videos on Rumble: https://rumble.com/c/c-7833526
Stop by whenever you like. Comments, questions, and offers to work together are always welcome.
X Money is the preferred way to pay: https://x.com/SamCast65215624
Cash App $samiamcastillo
PayPal castillo.sam.d@gmail.com
https://www.PredictiveInsightsAI.com
https://linktr.ee/samuel.castillo
More free coding and data science videos on Rumble: https://rumble.com/c/c-7833526
Stop by whenever you like. Comments, questions, and offers to work together are always welcome.
X Money is the preferred way to pay: https://x.com/SamCast65215624
Cash App $samiamcastillo
PayPal castillo.sam.d@gmail.com
https://www.PredictiveInsightsAI.com
https://linktr.ee/samuel.castillo
Category
🤖
TechTranscript
00:00Hello there, actuaries. In this video, you'll learn how to get a perfect score
00:05on the first 15 to 20 percent of exam PA, which is always focused on data
00:11exploration. This will be a fun lesson. You'll learn about pretty data
00:16visualization in R using ggplot2. The syllabus has a number of different
00:23topics all about the same thing. This is analogous to a job description that has
00:29a lot of complex vernacular, but then the day-to-day activities are quite simple
00:35once you start doing it. So here are the objectives from the syllabus. The first is
00:43translate a vague question into one that can be analyzed with statistics and
00:47predictive analytics. Consider factors such as available data and technology,
00:51significance to business impact, blah blah blah blah, and implementation challenges to
00:56define the problem. Understand the key principles of constructing graphs. Create a
01:01variety of graphs using ggplot2. Data types and exploration. Identify structured,
01:07semi-structured, unstructured data. Identify the types of variables and terminology
01:12used in predictive modeling. Understand basic methods of handling missing data.
01:17Implement effective data design with respect to timeframe, sampling, granularity.
01:22Apply univariate and bivariate data exploration techniques. Data issues and resolutions.
01:30Yes, as you can see there's just a lot. This shows you the total relative amount of money in the
01:39world.
01:40As you can see, not much money is in silver or in cryptocurrency despite the huge trends right now.
01:51Even military spending, which we think is relatively large, is right here. This is half of the U.S. deficit.
02:04If you look at the number of coins and banknotes in circulation, see that the U.S. has the largest,
02:11followed by these other powerful countries, Europe, China, Japan. Here's the federal balance sheet.
02:20And look at this entire part was just added since January of 2020.
02:27Is that ridiculous? Here are all of the U.S. billionaires in the world.
02:33There's all the money in the world if you had gold, jewelry, or below ground reserves.
02:40Here are the Fortune 500 companies. Look at that. Just Microsoft and Apple.
02:49So if you were to just take Microsoft, Apple, Amazon, Alphabet, aka Google, and Facebook, and put them together,
02:57they would have enough to pay off the Fed's balance sheet. Or they would have, if you took all the
03:07billionaires in the world, they would be able to buy out Microsoft, Apple, and Amazon. Hmm, that's interesting.
03:13That is why actuaries will always have secure jobs. A picture can sometimes speak a thousand words.
03:21And when you do data visualization, sometimes you need to just look at things from different ways.
03:29And there are two methods to this. There's exploration, which uses your left-hand brain.
03:38And there's communication, which uses your right brain. Exploration is about speed, iteration,
03:47agility, many dimensions, tidy data, which we'll talk about later, and specific tasks that you'll work
03:56on for exam PA. Conversely, the communication role is for simplicity, professionalism, consistency.
04:05You'll do this on your executive summary. There are different phases, and they're all connected to each
04:13other. You begin by taking in the data. This is a CSV file. Then you'll run some queries, transformations.
04:24This is also called tidying. Then you'll create some graphs. Usually these will be predefined for you,
04:32so you will only need to interpret them. Then you'll fit various statistical models. Sometimes you'll notice
04:41things that are not quite as you expect on the model. So you'll go back to the data, make some
04:47changes,
04:49refresh the data. Then when you begin to run out of time, you will transition into writing everything
04:57down into your report.
05:01The transformation phase comprises creating new features, reducing factor levels, applying log transforms,
05:10and creating bins for numeric variables.
05:14Visualization is when you will create graphs in ggplot2, understand key principles of constructing graphs,
05:22create summary tables, and inspect the target variable.
05:27Of course, when you model, you'll be first splitting the data into training and testing sets,
05:32and then fitting and interpreting models. Finally, when you communicate, you will clearly explain
05:38what steps you took and provide professional quality visualizations in tables.
05:44So how do you make graphs in R? Quite simply. First, you have to take some data. Then you will,
05:55well, in this example, there's a small sampling that's applied to it to make the graph easier to read.
06:01But then you will just call the ggplot function.
06:09GG is for a geometric something. And AES is aesthetic.
06:19So in the aesthetic argument, you always put the variable that you want to see in the graph.
06:28So here's, so once you have this geome object, P, you then add to it a graph.
06:36Let's add a geome histogram. And that's what it shows here.
06:42You could also add a geome frequency poly or a geome density.
06:48You can also change the color of your graph using an argument like fill equals dark blue.
06:58If you want to make a graph of more than one variable,
07:01such as a scatter plot with risk score and age, you have to specify multiple variables in the aesthetic.
07:09So here x is risk score. See that this is on the x-axis, y is equal to h.
07:15Then you add a geome point object. The first type of graph that we'll look at is called a histogram.
07:21This shows you the overall distribution of a numeric variable.
07:28On the x-axis, you see the range of values, and on the y-axis, the frequency.
07:34If the graph is symmetric, then the mean will be equal to the median.
07:41That means that if it's a predictor variable, you won't need to apply a log transformation.
07:49If this is a target variable, such as y, the response, you could just use an identity link function in
07:59GLN.
08:03What's more common is that you see a right skew variable. This is where the mean would be higher than
08:11the median.
08:14If this was a predictor variable, you should apply a log transform to make it more symmetric like this.
08:22If this was a target variable, then you should use a log link function in the GLN.
08:29If the mean is less than the median, like this, meaning that the mean would be down here,
08:43and the median would be near the center of mass of the points, then this would be left skewed.
08:51This would not be fixed by a log transform.
08:58Be careful that you specify the right number of bins.
09:03Otherwise, your histogram will have a problem like this, where there are all of these spikes.
09:09You can change this by adjusting the bin width in the histogram argument.
09:18So again, histograms are useful for telling whether or not a categorical predictor is predictive of a target.
09:29So here, the predictor variable is called x.
09:35And this shows you the distribution of the target, y.
09:42So imagine that you're predicting automotive crash claims, the amount of claims from an auto policy.
09:52And you look at three different colors of cars, red cars, green cars, blue cars.
09:57And you notice that the crash scores for the crash claims for red cars are much lower than the claims
10:07for blue cars on average.
10:10That would mean that the variable color is a predictive value in determining the claims.
10:19On the other hand, if you looked at the histograms and notice that these distributions were approximately the same,
10:26that would mean that color is not a significant predictor of claims.
10:33Now, one caveat to this is that you're not looking at other variables at the same time.
10:40That's why just looking at a simple graph isn't enough.
10:43You need to put all the variables together into a model.
10:46The next type of graph is the bar plot.
10:49This shows a category on the x-axis and the number of records on the y-axis.
10:58So when you look at bar plots, you should combine the levels from groups that don't have a lot of
11:05records.
11:06Let's say that I was looking at the month of the year.
11:08This is January, February, March, April, May.
11:14And I noticed that these months here only have a few records.
11:22I might combine these all together to form a new group called other so that when I fit my models,
11:31they will have a significant sample size.
11:35Otherwise, the p-values when I fit a GLM will be really large, meaning that the data just doesn't have
11:43enough credibility.
11:43I also note that if the values of the target are significantly different between those groups, I shouldn't combine them.
11:53In other words, if, you know, in May, the average claim amount was a million dollars.
12:02And in June, the average claim amount was only ten, ten dollars.
12:08I shouldn't combine those two together, even though they both have only a few observations.
12:15The third type of graph is the box plot, also called a box and whisker plot.
12:21It's called this because there is a box that represents the interquartile range.
12:29That's the difference between the 25th percentile and the 75th percentile.
12:34The line in the middle of the box is the median, also known as the 50th percentile.
12:43Then these whiskers here show you the Q1 plus or minus 1.5 times the interquartile range.
12:55And then these points along the outside are outliers or values that are outside of this IQR.
13:05They are very, so a box plot shows you the same information that you see from a histogram,
13:11except it will also give you specific measurements of the median and so forth.
13:18So you should apply a log transform to the variable before creating the plot if you use that log transform
13:25in your model.
13:29One useful case for box plots is detecting interaction variables.
13:35Here's a factor-factor interaction.
13:37There's a difference in the median box centers across the categories.
13:43So this is a graph that's looking at two variables, morning or night, and stop sign or other.
13:54Other could be a yield sign or just a right turn or just a left turn and so forth.
14:01If you look at this group here, notice that this red box is lower than the blue box.
14:09Compare that to this side, where the red center is slightly higher than the green center here.
14:19If there was no interaction variable, then they would look like this, where the left box,
14:27the left box plots are essentially the same as the right box plots.
14:35The second, the next type of graph is the scatter plot.
14:40The advantages of the scatter plot are that it shows correlation
14:45or non-linear relationships between numeric variables, and they are quite easy to read.
14:52Disadvantages are that they get crowded with many observations,
14:56because each point on a box plot represents one record.
15:00They are skewed when outliers are present.
15:06This is what a box plot looks like when you have a lot of records.
15:09You can fix that by making the points transparent and smaller.
15:16In ggplot2, you do that like this.
15:24Scatter plots show you numeric-numeric interactions.
15:28Let's say that your y-axis was your target variable.
15:34Your x-axis was a numeric predictor, and the color was a second predictor.
15:40So a point can either be green or red.
15:43The slope of a line here is the same no matter which color of the point you have.
15:48If you had two different slopes, then that would indicate that there's an interaction between color
15:55and predictor 2.
16:00The next phase of data digitalization that we'll talk about is just the importing.
16:08This is when you take the data in.
16:11For exam PA, there's nothing complicated about reading the physical data, but you do need to
16:18comment on the data source in the time that it was collected.
16:22You also need to consider regulatory or ethical concerns.
16:27If there's anything that should be mentioned, you need to write about it in the report.
16:34So here are some examples of data sources.
16:38You might look at all patients who have been admitted to a hospital, or traffic accidents,
16:46insurance claims, or customer phone calls.
16:50Just some concerns that you would have are hospital patients having private information
16:58about their race or political affiliation.
17:02Traffic accidents that use data from
17:052015 to predict accidents in 2020.
17:10That's too much time between when the data was collected and when it will be used.
17:15Insurance claims that use illegal variables in a pricing model.
17:20Or customer phone calls using data that can't easily be explained.
17:25Here's a real example from a major insurance company in the U.S.
17:29Just a few years ago, one of the largest insurance carriers in the world was accused of racism over
17:36their use of a predictive model.
17:38They used medical claims to predict health recovery in hospitals.
17:42They were predicting health costs, but minorities appeared sicker simply because they had less access to
17:50affordable care and so their claim amounts were higher on average than a white person who had better access to
18:00care.
18:01So they had to spend more on average.
18:04Another example is racism in court sentencing.
18:09A federal court used a predictive model to estimate the probability
18:13that a criminal would recommit a crime if they were released.
18:17They used arrest data and they were predicting drug offenses.
18:24Black people were much more likely to be searched by police than white people, so they had more arrests.
18:32Even though the model did not contain a race variable, the results were racist.
18:41Tidying covers a broad range of topics.
18:44Think about this as your pick and shovel.
18:47You have a huge pile of data and you have to just dig through and find the planted mistakes
18:54mistakes that the SOA puts in these exams.
18:58Clean up the data and then put it into your models.
19:03So you'll first read the data dictionary that they give you on the project statement
19:08and check that it matches the physical data.
19:11Identify the types of variables.
19:13Check missing values.
19:15Decide which time frames and variables you'll use.
19:19And set your base factor levels.
19:24You'll have to fix missing values.
19:26There are three types of missing values.
19:31First is missing at random.
19:34Remember this.
19:36If you spill laptop, if you spill coffee on your laptop and that deletes your hard drive,
19:42that data would be missing at random.
19:45Maybe you were working on an actual project.
19:48Some of the data was on your server.
19:51Some of it was on your laptop.
19:53And all of the files from your hard drive suddenly go missing.
19:58There wouldn't be a pattern between the missing values and the actual data.
20:09Hidden missingness is when there is just an error in the data.
20:14Imagine that someone is typing in a person's name into a database and they misspell that name.
20:23And that results in values not being filled incorrectly.
20:29That would just be an example of hidden missingness.
20:34Or another example is you look at your data dictionary from a product statement.
20:40And notice that one of the values doesn't match what it's supposed to.
20:44The final type is missing not at random.
20:47Imagine that you wanted to know the percentage of people that used illegal drugs.
20:53So you walk out into New York City and you ask a thousand random people.
20:58Do you use illegal drugs?
21:02Some people say, I don't want to answer that question.
21:06That would be a missing value.
21:09Now, would there be a pattern between whether or not people decide to ignore you and whether or not
21:19they're using drugs?
21:21Probably yes.
21:25So how can you fix these values?
21:28Well, the first is that you could just remove the observations altogether.
21:32You should use this only when there are a few missing values or when they're when they are missing at
21:39random.
21:40You can create a new level called missing and use this when there are more values or when they are
21:48MNAR.
21:50Missing not at random.
21:52You can also impute the values with the mean.
21:57You should do this when they are numeric and they're MAR.
22:03You should remove variables altogether if there are more than 50% of the records missing.
22:09And there's no way to repair the data.
22:13Now, that 50% number could be different.
22:17It might be 20% of the records are missing.
22:20Depending on how many variables that you have in the data set and the amount of time that you can
22:25work on it.
22:26The example.
22:28Let's figure out which of these variables are missing at random and which of them are not.
22:34Our goal is to predict whether or not a person will pass exam P.
22:38We're looking at the variables, the hours that they study, whether or not they eat chocolate,
22:45if they work in the life industry or not, if they drive to work, or if they bring their own
22:51lunch.
22:53You look at the percentage of people who pass for non-NA records and compare that to the percentage
22:59of pass which have missing values.
23:02You notice that 51% of the people who accurately record their study hours end up passing,
23:10whereas only 30% of people who don't record their study hours pass.
23:15You could conclude that study hours is not missing at random.
23:22If you look at eats chocolate, it's 49.49.
23:26That's probably random.
23:29Life industry, 53%, 52%.
23:33That also is probably random.
23:36Drives to work, random.
23:38Brings own lunch, 55%, 53%.
23:42There could be something here.
23:44It could be that people who bring their own lunch study while they're on their lunch break
23:49as opposed to going out of the office.
23:52So you could say that that's not missing at random.
23:58So here's a quiz for you.
24:00How should you fix each type of missing value?
24:04On the left, you see the different types, and on the right, you see the solutions.
24:10Connect these dots together for the acceptable ways that you think you should fix them.
24:20You can essentially use any method for any type of missingness, except if the value is not missing
24:29at random.
24:30If it's not missing at random, you should not remove the observations.
24:35That would be this connection right here.
24:40That's because if there's some info in the data, you don't want to take it away.
24:46You want to keep as much info present.
24:51So let's talk about feature engineering.
24:56Feature engineering is when you create new variables from existing variables.
25:02So this table shows you a number of mathematical expressions
25:08and their formulas on the right.
25:10Feature engineering is when you create new variables on the right.
25:11These are all derived on your predictive variables, the x's.
25:18As you can see, there are a lot of different things you could do with your variables to increase
25:22the predictive power.
25:24You could just take the difference, a log, you can make polynomials, powers, ratios, ratios of polynomials,
25:33and so forth.
25:34The only type of model
25:39that will predict that will be able to identify these relationships without you
25:46manually creating the features are tree based models.
25:50Random forests, gradient boosted trees, single decision trees.
25:55If you're using a linear model like a GLM, a lasso, a stepwise regression,
26:03then you need to manually create these features.
26:06The only different, the only exception is the difference here.
26:11That's because a difference is just a linear transformation and linear models can pick those up.
26:20How do you use tables and summary statistics?
26:25You'll have some stats that will be in the template code.
26:32You just need to know how to use them.
26:34A mean is useful for showing the overall behavior of something.
26:38A median tells you what the center behavior is.
26:43The max and the min tell you the higher and the lower outliers.
26:48The variance or the standard deviation will tell you how spread out the values are.
26:55And a percentage is similar to a mean.
26:58It just tells you the overall behavior.
27:01Here's an example.
27:03This is from June 16, 2020.
27:06You are looking at three different variables.
27:09Age, gender, and days.
27:13On the left, you see everything from RStudio.
27:18And on the right, your report in Microsoft Word.
27:23You want to look and see that the values here match the data dictionary.
27:30I see this goes from 1 to 14.
27:32And this says integer 1 to 14.
27:35Check.
27:37This description is the number of days between admission into and discharge from the hospital.
27:42Okay.
27:43For gender, I see that this should be either male or female.
27:47But in the data, I see that there are three values here, which are either unknown or invalid.
27:53So these are really NA values.
27:58For age, I notice that this age is supposed to go from 10 to 100.
28:04If I just look at the summary function in R, it just has this big other category.
28:10So there could be some missing values in there.
28:14So I want to look at the actual counts of these records.
28:18And that's what I can do here.
28:22And then in the Microsoft Word report, I have to write all of this down.
28:28So for gender, I would say there are three missing values.
28:31I just remove these because there are not enough values to make a difference.
28:39And I provide some commentary on the target variable.
28:43I say the target variable, which is days, is the number of days the patient has stayed in
28:48the hospital after being admitted.
28:49This has a mean of 4.4 and a median of 4.
28:53Again, I got that from looking at the mean, the median,
28:58indicating that it's right skewed, which you can also see from the histogram below.
29:04Now let's talk about some more of the right brain behavior.
29:08How can you communicate using graphics?
29:13How can you create useful graphs?
29:16Here is a histogram.
29:19This shows you the distribution of readmissions.
29:24Now, what are the y-axis units?
29:30It just says density.
29:32If you showed this to your manager who wasn't an actuary,
29:36they might not know what density means.
29:40How can you translate this graph into English?
29:43Here's a much better equivalent.
29:46The y-axis shows you the number of hospitals.
29:51In English, you could say there are just over 2,000 hospitals with between 30 and 50 readmissions.
30:01This combines the tabular info that you get from a table with the visual power of a graph.
30:07In ggplot2, there are some parameters that you'd use to create a graph like this.
30:14First, you make the histogram.
30:16Then you change the axis labels and the formatting of the numeric scales.
30:24Then you do the same for the x-axis.
30:29Graphs should be unambiguous.
30:32Here's a mixed bar and line graph.
30:36It's trying to show you the actual versus predicted readmission rates.
30:42I'm looking at this and I see, okay, blue is average of predicted readmission rate.
30:49Orange is average of expected readmission rate.
30:52And I'm looking at these different states, Illinois, Massachusetts, North Carolina, etc.
31:01So when green, when orange is above blue, oh, that's the right axis is predicted.
31:07The left axis is actual.
31:09Wait, so which is right?
31:12Is it the left axis that's orange?
31:15Orange?
31:15Oh, I see.
31:16Orange is expected, so that's actual.
31:21Wait, expected is predicted.
31:23Oh, so expected is orange, which is this right axis.
31:27Do you get the point?
31:28It's really hard to understand this graph.
31:33A better alternative would just be to look at a dot plot.
31:37Here you can see that Massachusetts has higher expected than actual, meaning that it's an overestimate.
31:49North Carolina has lower actual, has lower expected than actual, which is an underestimate.
31:58Pennsylvania has a perfect estimate almost.
32:06You can also show uncertainty in your graphs.
32:08This box plot shows you the spread of values.
32:14Notice that Pennsylvania is right about 1.0, which is perfect.
32:19However, they also have a wide range of values.
32:23Compare that to like North Carolina, which has a narrower band of values,
32:30but they're slightly biased high.
32:34They're overestimated.
32:38Now, you can create this exact graph in ggplot2 with these parameters.
32:44Now, don't worry.
32:45I know this is a lot of code.
32:47You don't have to remember it.
32:48But let me just show you some of the key knobs that you tune if you want to adjust your
32:54own graphs.
32:56So this here, it creates the box plot.
33:00This outlier alpha adjusts the color of these points here.
33:07This coordinate flip is flipping the whole graph 90 degrees.
33:16This ggtitle changes the title here.
33:21Of course, ylabs is actually on the x-axis because I flipped the graph.
33:30And then the subtitle and captions is this commentary here that goes under the title.
33:37You should never have to guess which colors are good.
33:42Some people can have a natural instinct to tell which colors look good together.
33:49I've never been able to do this, so I've always relied on color wheels.
33:53The trick is that you choose colors which are opposite.
33:58If you have a graph with two variables, just choose two colors.
34:03If you have four variables, then choose four colors that are opposite on the color wheels.
34:11This is what happens if you don't.
34:14Your graphs will not have complementary colors.
34:19You can take your colors from your company's website and then create your own themes and color palettes.
34:29You can put them into R and create beautiful visualizations like this.
34:35How do you be persuasive when you're using data visualization?
34:40This comes back to your right brain emotions.
34:45First of all, realize that you can't win an argument.
34:49If you go into a sales presentation and say, I'm going to convince this client that our actuarial services are
35:00the best so that they'll buy.
35:01And I'm going to do that by showing them all of these really convincing graphs.
35:05If you have that mentality, you will not be successful.
35:10Instead, think of yourself as a radiologist.
35:15And you're taking some x-rays of the data and you're presenting them to the doctor.
35:20And you're not trying to make a diagnosis.
35:23You're letting the doctor do that.
35:26Show them the data and let the other person arrive at the conclusion themselves.
35:32Put yourself in the other person's shoes.
35:34Use their language.
35:36Think about what they already know.
35:39And speak from their point of view.
35:42Be friendly, of course.
35:44Try to smile and use good humor.
35:48Get the other person agreeing with you.
35:50Get them saying, yes, yes.
35:53At the beginning of this presentation, I show you something that you already were familiar with.
35:58You know, money, markets, visualizations like that.
36:02Start off with something that they already know and they're excited about.