Problem 1

Using R, set a random seed equal to 1234 (i.e., set.seed(1234)). Generate a random variable X that has 10,000 continuous random uniform values between 5 and 15.Then generate a random variable Y that has 10,000 random normal values with a mean of 10 and a standard deviation of 2.89.

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(knitr)
library(kableExtra)
## 
## Attaching package: 'kableExtra'
## 
## The following object is masked from 'package:dplyr':
## 
##     group_rows
library(exact2x2)
## Loading required package: exactci
## Loading required package: ssanv
## Loading required package: testthat
## 
## Attaching package: 'testthat'
## 
## The following object is masked from 'package:dplyr':
## 
##     matches
## 
## The following object is masked from 'package:purrr':
## 
##     is_null
## 
## The following objects are masked from 'package:readr':
## 
##     edition_get, local_edition
## 
## The following object is masked from 'package:tidyr':
## 
##     matches
library(GGally)
## Registered S3 method overwritten by 'GGally':
##   method from   
##   +.gg   ggplot2
library(Matrix)
## 
## Attaching package: 'Matrix'
## 
## The following objects are masked from 'package:tidyr':
## 
##     expand, pack, unpack
library(matrixcalc)
library(car)
## Loading required package: carData
## 
## Attaching package: 'car'
## 
## The following object is masked from 'package:dplyr':
## 
##     recode
## 
## The following object is masked from 'package:purrr':
## 
##     some
set.seed(1234)
X = runif(n = 10000, min = 5, max = 15)
Y = rnorm(10000, mean = 10, sd = 2.89)

hist(X)

hist(Y)

Probability. Calculate as a minimum the below probabilities a through c. Assume the small letter “x” is estimated as the median of the X variable, and the small letter “y” is estimated as the median of the Y variable. Interpret the meaning of all probabilities.

x = median(X)
y = median(Y)

a: P(X>x | X>y)

Generically: \[ P(A | B) = \frac{P(A \cap B)}{P(B)} \]

And in our case: \[ P(X>x | X>y) = \frac{P(X>x \cap X>y)}{P(X>y)} \]

And: \[ P(X>x | X>y) = \frac{P(X>x)P(X>y | X>x)}{P(X>y)} \]

Xgx = mean(X>x) #P(X>x)
subset_X = X[X > x]
Xgy_given_Xgx = length(subset_X[X > y]) / length(subset_X) #Given X>x, probability that X>y
num = Xgx * Xgy_given_Xgx # final numerator
denom = mean(X>y) #P(X>y)
num / denom
## [1] 1

The probability is 1. In other words, given that X is greater than y, X is certain to be greater than x. This is intuitive; our value for y is 10.03. If X is greater than 10.03, it will certainly be greater than x which is 10.01.

P(X>x | X>y) = 1

b: P(X>x & Y>y)

This question is simpler; they are independent events, and so we multiply the two probabilities to find the joint one.

mean(X>x) * mean(Y>y)
## [1] 0.25

So the probability that X is greater than x as well as that Y is greater than y is 0.25 or 25%. Again, this is quite intuitive. By definition, half of the numbers in a set are greater than its median. This is true for both X and Y, and so the joint probability is 0.25.

P(X>x & Y>y) = 0.25

c: P(X<x | X>y)

In retrospect, the path to the answer for part a was correct but unnecessarily complicated. This time, I’ll calculate the conditional probability as:

\[ P(X<x | X>y) = \frac{P(X<x \cap X>y)}{P(X>y)} \]

(I confirmed the answer to part a using this method as well.)

So the numerator is the joint probability, and we can find all the instances in which X is both less than x as well as greater than y, and then express that as a proportion.

numerator = sum(X < x & X > y) / length(X)
numerator
## [1] 0

In fact, there are no such instances. The numerator will equal 0 and we can stop our calculations already.

P(X<x | X>y) = 0

Investigate whether P(X>x & Y>y)=P(X>x)P(Y>y) by building a table and evaluating the marginal and joint probabilities.

result_table = data.frame(
  "n_10000" = c("Y > y", "Y <=y ", "Total"),
  "X_greater_than_x" = c(sum(X>x & Y>y) / 10000, sum(X>x & Y<=y) / 10000, sum(X>x & Y>y) / 10000 + sum(X>x & Y<=y) / 10000 ),
  "X_LEQ_x" = c(sum(X<=x & Y>y) / 10000, sum(X<=x & Y<=y) / 10000, sum(X<=x & Y>y) / 10000 + sum(X<=x & Y<=y) / 10000),
  "Total" = c(sum(X>x & Y>y) / 10000 + sum(X<=x & Y>y) / 10000, sum(X>x & Y<=y) / 10000 + sum(X<=x & Y<=y) / 10000 , 1)
)

kable(result_table, "html")
n_10000 X_greater_than_x X_LEQ_x Total
Y > y 0.2507 0.2493 0.5
Y <=y 0.2493 0.2507 0.5
Total 0.5000 0.5000 1.0

The column names should be: X>x, X<=x, and total. The goal, again, is to investigate whether P(X>x & Y>y) equals P(X>x)P(Y>y).

For P(X>x & Y>y), we can simply look at that cell in the table–the probability is 0.2507. Now, we want to evaluate if that’s equal to the joint probability of both events occurring. Looking at the total for P(X>x), the probability is 0.5. The total probability for P(Y>y) is likewise 0.5. So P(X>x)P(Y>y) is 0.25. That’s indeed quite close to 0.2507 (albeit not exactly equal). Still, it’s close enough and this is the result I expected; generally when random variables are independent, then p(x, y) = p(x)p(y).

Check to see if independence holds by using Fisher’s Exact Test and the Chi Square Test. What is the difference between the two? Which is most appropriate? Are you surprised at the results? Why or why not?

First, I’m going to quickly set up a matrix that has the counts (versus the probabilities). Then I’ll conduct the two tests.

matrix_for_tests = matrix(c(sum(X>x & Y>y), sum(X<=x & Y>y), sum(X>x & Y<=y), sum(X<=x & Y<=y)), nrow = 2)
head(matrix_for_tests)
##      [,1] [,2]
## [1,] 2507 2493
## [2,] 2493 2507
fisher.exact(matrix_for_tests)
## 
##  Two-sided Fisher's Exact Test (usual method using minimum likelihood)
## 
## data:  matrix_for_tests
## p-value = 0.7949
## alternative hypothesis: true odds ratio is not equal to 1
## 95 percent confidence interval:
##  0.9350 1.0938
## sample estimates:
## odds ratio 
##   1.011264
chisq.test(matrix_for_tests)
## 
##  Pearson's Chi-squared test with Yates' continuity correction
## 
## data:  matrix_for_tests
## X-squared = 0.0676, df = 1, p-value = 0.7949

With both tests, we are testing the independence of the variables. The null hypothesis is that they are in fact independent. So if the p-value is low enough, we can reject the null hypothesis. The p-value for Fisher’s test is 0.7949, and for the Chi-squared test is also 0.7949. So in both cases, we fail to reject the null hypothesis. Generally, it is more appropriate to use Fisher’s test when there’s a small sample size. That’s not really the case here and so it’s more appropriate to use the chi-squared test. As it turned out, it really didn’t end up mattering since both tests resulted in the same p-value. I’m not surprised at the results of the tests. I would have been shocked if there were a low p-value since the two variables are intuitively independent of one another.

Problem 2

Compete in the Regression with a Crab Age Dataset competition. And:

Part a

Descriptive and Inferential Statistics. Provide univariate descriptive statistics and appropriate plots for the training data set. Provide a scatterplot matrix for at least two of the independent variables and the dependent variable. Derive a correlation matrix for any three quantitative variables in the dataset. Test the hypotheses that the correlations between each pairwise set of variables is 0 and provide an 80% confidence interval. Discuss the meaning of your analysis. Would you be worried about familywise error? Why or why not?

I’ll first load the data and provide summary statistics

data = read_csv("/Users/gavrielsteinmetz-silber/Desktop/DATA605/605 Final/train.csv")
## Rows: 74051 Columns: 10
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): Sex
## dbl (9): id, Length, Diameter, Height, Weight, Shucked Weight, Viscera Weigh...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
print(colSums(is.na(data)))
##             id            Sex         Length       Diameter         Height 
##              0              0              0              0              0 
##         Weight Shucked Weight Viscera Weight   Shell Weight            Age 
##              0              0              0              0              0
print(summary(data))
##        id            Sex                Length          Diameter     
##  Min.   :    0   Length:74051       Min.   :0.1875   Min.   :0.1375  
##  1st Qu.:18512   Class :character   1st Qu.:1.1500   1st Qu.:0.8875  
##  Median :37025   Mode  :character   Median :1.3750   Median :1.0750  
##  Mean   :37025                      Mean   :1.3175   Mean   :1.0245  
##  3rd Qu.:55538                      3rd Qu.:1.5375   3rd Qu.:1.2000  
##  Max.   :74050                      Max.   :2.0128   Max.   :1.6125  
##      Height           Weight        Shucked Weight     Viscera Weight    
##  Min.   :0.0000   Min.   : 0.0567   Min.   : 0.02835   Min.   : 0.04252  
##  1st Qu.:0.3000   1st Qu.:13.4377   1st Qu.: 5.71242   1st Qu.: 2.86330  
##  Median :0.3625   Median :23.7994   Median : 9.90815   Median : 4.98951  
##  Mean   :0.3481   Mean   :23.3852   Mean   :10.10427   Mean   : 5.05839  
##  3rd Qu.:0.4125   3rd Qu.:32.1625   3rd Qu.:14.03300   3rd Qu.: 6.98815  
##  Max.   :2.8250   Max.   :80.1015   Max.   :42.18406   Max.   :21.54562  
##   Shell Weight           Age        
##  Min.   : 0.04252   Min.   : 1.000  
##  1st Qu.: 3.96893   1st Qu.: 8.000  
##  Median : 6.93145   Median :10.000  
##  Mean   : 6.72387   Mean   : 9.968  
##  3rd Qu.: 9.07184   3rd Qu.:11.000  
##  Max.   :28.49125   Max.   :29.000

The options for independent variables include: Sex, Length, Diameter, Height, Weight, Shucked Weight, Viscera Weight, and Shell Weight. The dependent variable is Age. We can see that the ages go from 1 to 29 with a median age of 10. The summary statistics are interesting. For example, the average crab weight is around 23 ounces, but there’s a crab that weighs over 80 ounces. Similarly, the average crab height is 0.35 feet but there’s a crab that’s over 2.8 feet tall. At first, I thought these had to be mistakes; some Google searches suggest that the weight is possible, but the heights must be errors. I will eliminate those rows later, when I do the regression. I also see there are crabs with a listed height of 0…this is impossible and I’ll eliminate those rows later as well.

I’ll now create some plots. First, I noticed in the head that there are three values for Sex (one for indeterminate). Let’s see how common each value is (this may inform the variable’s potential in a model).

data %>% ggplot(aes(x = Sex, fill = Sex)) + 
  geom_bar()

Later, I’ll need to use a variable that’s right-skewed, so I may as well plot some variables now:

cont_vars = colnames(data)[3:9]
for (var in cont_vars) {
  plot = ggplot(data, aes(x = !!sym(var))) +
    geom_histogram() +
    labs(title = paste("Histogram of", var), x = var, y = "Frequency") +
    theme_minimal()
  print(plot)
}
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Quite a few of the variables are right-skewed which makes sense since there’s a lower bound but no upper one. Let’s also see a couple of scatterplots:

cont_vars = colnames(data)[3:9]
for (var in cont_vars) {
  plot = ggplot(data, aes(x = !!sym(var), y = Age)) +
    geom_point() +
    geom_jitter() +
    labs(title = paste("Scatterplot of", var, "vs. Age"), x = var, y = "Age") 
  print(plot)
}

All of these continuous variables have a positive correlation with Age. However, most do not look strictly linear, and transformations will likely be in order. Now, I shift to look at a scatterplot matrix:

ggpairs(data = data, columns = c("Length", "Weight", "Shell Weight", "Age"))

There appear to be some strong correlations here. The correlation between Weight and Shell Weight is sort of obvious. But the correlations between length and the two weight variables are nearly as strong. The weakest correlations (although still quite strong) are between the independent variables and Age.

I will now create a correlation matrix for the three independent variables already discussed.

cor_ind_data = data %>% 
  dplyr::select(c("Length", "Weight", "Shell Weight"))

cor_matrix = cor(cor_ind_data)
cor_matrix
##                 Length    Weight Shell Weight
## Length       1.0000000 0.9363738    0.9169573
## Weight       0.9363738 1.0000000    0.9655246
## Shell Weight 0.9169573 0.9655246    1.0000000

I turn now to test the hypotheses that the correlations between each pairwise set of variables is 0 and provide 80% confidence intervals.

cor.test(data$Length, data$Weight, conf.level = 0.8)
## 
##  Pearson's product-moment correlation
## 
## data:  data$Length and data$Weight
## t = 725.93, df = 74049, p-value < 2.2e-16
## alternative hypothesis: true correlation is not equal to 0
## 80 percent confidence interval:
##  0.9357910 0.9369515
## sample estimates:
##       cor 
## 0.9363738
cor.test(data$Length, data$`Shell Weight`, conf.level = 0.8)
## 
##  Pearson's product-moment correlation
## 
## data:  data$Length and data$`Shell Weight`
## t = 625.39, df = 74049, p-value < 2.2e-16
## alternative hypothesis: true correlation is not equal to 0
## 80 percent confidence interval:
##  0.9162044 0.9177038
## sample estimates:
##       cor 
## 0.9169573
cor.test(data$Weight, data$`Shell Weight`, conf.level = 0.8)
## 
##  Pearson's product-moment correlation
## 
## data:  data$Weight and data$`Shell Weight`
## t = 1009.3, df = 74049, p-value < 2.2e-16
## alternative hypothesis: true correlation is not equal to 0
## 80 percent confidence interval:
##  0.9652040 0.9658423
## sample estimates:
##       cor 
## 0.9655246

The 80 percent confidence interval for the correlation coefficient between Length and Weight is 0.9357910 to 0.9369515. The 80 percent confidence interval for the correlation coefficient between Length and Shell Weight is 0.9162044 to 0.9177038. The 80 percent confidence interval for the correlation coefficient between Weight and Shell Weight is 0.9652040 to 0.9658423.

In all these instances, it means we repeatedly estimated the correlation between samples, in 80% of the samples the correlation would fall between the two numbers. A few observations. First, these intervals are quite narrow. Granted it’s an 80 percent confidence interval and not a 95 percent one, but the fact that it’s so narrow indicates that the estimate is pretty accurate. Also, the correlation scores between the independent variables is quite high. I mentioned this fact earlier, but the small 80 percent confidence interval highlights the concern.

Yes, given the correlations I just described, I’m worried about familywise error. Familywise error is when type I errors occur during multiple hypotheses tests. Now, suppose we create a model with all these independent variables (predicting Age). These variables highly correlate with one another. As such, there may incorrectly be very high standard errors. This will hinder the ability to identify significant coefficients (and there lies the potential for familywise errors).

Part b

Linear Algebra and Correlation. Invert your correlation matrix from above. (This is known as the precision matrix and contains variance inflation factors on the diagonal.) Multiply the correlation matrix by the precision matrix, and then multiply the precision matrix by the correlation matrix. Conduct LDU decomposition on the matrix.

First, here is the precision matrix:

prec_matrix = solve(cor_matrix)
prec_matrix
##                 Length     Weight Shell Weight
## Length        8.280786  -6.235915    -1.572198
## Weight       -6.235915  19.453492   -13.064757
## Shell Weight -1.572198 -13.064757    15.055982

I now multiply the correlation matrix by the precision matrix, and then vice versa:

cor_prec = cor_matrix %*% prec_matrix
prec_cor = prec_matrix %*% cor_matrix

cor_prec
##                     Length       Weight Shell Weight
## Length        1.000000e+00 0.000000e+00            0
## Weight        0.000000e+00 1.000000e+00            0
## Shell Weight -2.220446e-16 3.552714e-15            1
prec_cor
##                     Length        Weight  Shell Weight
## Length        1.000000e+00 -4.440892e-16 -8.881784e-16
## Weight       -1.776357e-15  1.000000e+00  1.776357e-15
## Shell Weight  1.776357e-15  1.776357e-15  1.000000e+00

Now I’ll conduct LDU decomposition on the correlation matrix.

lu_cor = lu.decomposition(cor_matrix)
#expand(lu_cor)
L = lu_cor$L
U_a = lu_cor$U

D = diag(diag(U_a)) 
U = solve(D) %*% U_a

L
##           [,1]      [,2] [,3]
## [1,] 1.0000000 0.0000000    0
## [2,] 0.9363738 1.0000000    0
## [3,] 0.9169573 0.8677452    1
D
##      [,1]      [,2]       [,3]
## [1,]    1 0.0000000 0.00000000
## [2,]    0 0.1232041 0.00000000
## [3,]    0 0.0000000 0.06641878
U
##      [,1]      [,2]      [,3]
## [1,]    1 0.9363738 0.9169573
## [2,]    0 1.0000000 0.8677452
## [3,]    0 0.0000000 1.0000000
L %*% D %*% U #should be the same as cor_matrix
##           [,1]      [,2]      [,3]
## [1,] 1.0000000 0.9363738 0.9169573
## [2,] 0.9363738 1.0000000 0.9655246
## [3,] 0.9169573 0.9655246 1.0000000
cor_matrix
##                 Length    Weight Shell Weight
## Length       1.0000000 0.9363738    0.9169573
## Weight       0.9363738 1.0000000    0.9655246
## Shell Weight 0.9169573 0.9655246    1.0000000

Part c

Calculus-Based Probability & Statistics. Many times, it makes sense to fit a closed form distribution to data. Select a variable in the Kaggle.com training dataset that is skewed to the right, shift it so that the minimum value is absolutely above zero if necessary. Then load the MASS package and run fitdistr to fit an exponential probability density function. (See https://stat.ethz.ch/R-manual/R-devel/library/MASS/html/fitdistr.html ). Find the optimal value of \(\lambda\) for this distribution, and then take 1000 samples from this exponential distribution using this value (e.g., rexp(1000,\(\lambda\))). Plot a histogram and compare it with a histogram of your original variable. Using the exponential pdf, find the 5th and 95th percentiles using the cumulative distribution function (CDF). Also generate a 95% confidence interval from the empirical data, assuming normality. Finally, provide the empirical 5th percentile and 95th percentile of the data. Discuss.

We saw this histograms earlier, and Shucked Weight is one variable that’s skewed to the right. Here it is again:

data %>% ggplot(aes(x = `Shucked Weight`)) +
  geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Let’s see if shifting is necessary (I’d be shocked):

min(data$`Shucked Weight`)
## [1] 0.0283495

And indeed the minimum value is above 0. I’ll now use fitdistr to fit an exponential probability density function.

library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
## 
##     select
epdf = fitdistr(data$`Shucked Weight`, densfun = "exponential")

I use this to find the optimal value of \(\lambda\) for this distribution:

lambda = as.numeric(epdf$estimate)
lambda
## [1] 0.09896806

Now I’ll take 1000 samples from this exponential distribution using this value:

samples = rexp(1000, lambda)

And I’ll plot the samples as well as the original variable:

ggplot(data.frame(samples), aes(x = samples)) +
  geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

data %>% ggplot(aes(x = `Shucked Weight`)) +
  geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

The histograms look quite different. The plot of the exponential distribution samples makes our variable look normal in comparison. The exponential distribution is concentrated on the left and is very right-skewed. The count decreases quickly at first and then the rate slows down. Our original variable, again, looks much more normal. It just has that tail on the right but it’s not nearly as skewed as the exponential distribution samples.

I’ll now use the exponential pdf to find the 5th and 95th percentiles.

qexp(0.05, rate = lambda) 
## [1] 0.5182813
qexp(0.95, rate = lambda)
## [1] 30.26969

The 5th percentile is 0.5182813; the 95th percentile is 30.26969.

By the way, if this is right, the numbers should be close to those percentiles in our sample from the PDF.

fifth = quantile(samples, probs = 0.05)
ninetyfifth = quantile(samples, probs = 0.95)

fifth
##        5% 
## 0.5244731
ninetyfifth
##      95% 
## 29.17819

And indeed, those numbers are pretty close.

I’ll now generate a 95% confidence interval from the empirical data, assuming normality.

moe = 1.96 * (sd(data$`Shucked Weight`) / sqrt(length(data$`Shucked Weight`)))
confidence_int = c(mean(data$`Shucked Weight`) - moe, mean(data$`Shucked Weight`) + moe)
confidence_int
## [1] 10.06381 10.14473

I’ll also use t.test to confirm:

t.test(data$`Shucked Weight`)
## 
##  One Sample t-test
## 
## data:  data$`Shucked Weight`
## t = 489.43, df = 74050, p-value < 2.2e-16
## alternative hypothesis: true mean is not equal to 0
## 95 percent confidence interval:
##  10.06381 10.14473
## sample estimates:
## mean of x 
##  10.10427

And that looks good. So the 95% confidence interval from the empirical data is 10.06381 to 10.14473.

Finally, I’ll provide the empirical 5th percentile and 95th percentile of the data:

quantile(data$`Shucked Weight`, c(.05,.95))
##        5%       95% 
##  1.502523 19.376883

So with the exponential PDF, the 5th percentile was 0.5182813 and the 95th percentile 30.26969. With the empirical data, the 5th percentile was 1.502523 and the 95th percentile 19.376883. Obviously, the data doesn’t follow this distribution, despite both histograms revealing a right tail. At the end of the day, our empirical data is much more normal and so the results from the calculations on the empirical data versus the exponential distribution differ from one another. While in general it might be useful to take random samples from the exponential rather than sampling from the original data (which has noise), I do not think it’s necessarily advisable in this case since the distributions look a bit different.

Part d

Modeling. Build some type of multiple regression model and submit your model to the competition board. Provide your complete model summary and results with analysis. Report your Kaggle.com user name and score.

As discussed earlier, I need to eliminate any rows where there’s a value of 0 since that’s impossible. I’ll also eliminate rows where there’s a height of 2.825 feet since those are surely mistakes.

filtered_data = data %>% 
  filter(Height != 2.825, Height > 0)

nrow(data) - nrow(filtered_data)
## [1] 26

So we’ve eliminated 26 rows. Now, I’d like to build a model, but we already saw earlier that there are some highly correlated features. This will make any model (particularly some of the coefficients) impossible to interpret. Let’s take a closer look at the correlated features:

numeric_data = filtered_data %>% 
  dplyr::select(Length, Diameter, Height, Weight, `Shucked Weight`, `Viscera Weight`, `Shell Weight`, Age)

cor(numeric_data)
##                   Length  Diameter    Height    Weight Shucked Weight
## Length         1.0000000 0.9894180 0.9278977 0.9364075      0.9155308
## Diameter       0.9894180 1.0000000 0.9309363 0.9382733      0.9142005
## Height         0.9278977 0.9309363 1.0000000 0.9116137      0.8731699
## Weight         0.9364075 0.9382733 0.9116137 1.0000000      0.9712438
## Shucked Weight 0.9155308 0.9142005 0.8731699 0.9712438      1.0000000
## Viscera Weight 0.9178730 0.9183580 0.8927362 0.9710367      0.9425782
## Shell Weight   0.9169557 0.9226845 0.9134735 0.9654940      0.9103232
## Age            0.6123714 0.6207971 0.6445802 0.6008359      0.5028780
##                Viscera Weight Shell Weight       Age
## Length              0.9178730    0.9169557 0.6123714
## Diameter            0.9183580    0.9226845 0.6207971
## Height              0.8927362    0.9134735 0.6445802
## Weight              0.9710367    0.9654940 0.6008359
## Shucked Weight      0.9425782    0.9103232 0.5028780
## Viscera Weight      1.0000000    0.9338612 0.5764331
## Shell Weight        0.9338612    1.0000000 0.6631687
## Age                 0.5764331    0.6631687 1.0000000

All the weight variables are highly correlated with one another. This is intuitive; it looks like there tends to be a fairly consistent ratio between shucked weight, viscera weight, shell weight, and total weight. I’ll keep only shell weight since that has the highest correlation with the dependent variable. Length and diameter are also very highly correlated (almost a coefficient of 1!), and so I’ll drop length.

filtered_data2 = filtered_data %>% 
  dplyr::select(Sex, Diameter, Height, `Shell Weight`, Age)

Now, let’s build an initial model:

model1 = lm(Age ~ ., data = filtered_data2)
plot(model1)

summary(model1)
## 
## Call:
## lm(formula = Age ~ ., data = filtered_data2)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -10.2817  -1.4026  -0.4102   0.7630  18.3715 
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)     6.597270   0.073112  90.236   <2e-16 ***
## SexI           -1.115302   0.027461 -40.614   <2e-16 ***
## SexM           -0.183192   0.020916  -8.759   <2e-16 ***
## Diameter       -2.251115   0.114291 -19.696   <2e-16 ***
## Height          9.406608   0.280082  33.585   <2e-16 ***
## `Shell Weight`  0.421042   0.006732  62.546   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2.326 on 74019 degrees of freedom
## Multiple R-squared:  0.4631, Adjusted R-squared:  0.463 
## F-statistic: 1.277e+04 on 5 and 74019 DF,  p-value: < 2.2e-16

This is really just to get a sense of the data. I don’t love the residuals vs. fitted…it looks like far more residuals are above the horizontal line. The QQ plot is also a little disturbing and suggests that we need transformations.

First, I’ll transform just the dependent variable:

bc = boxcox(model1, lambda = seq(-3, 3))

best.lam = bc$x[which(bc$y==max(bc$y))]

model2 = lm(Age^best.lam ~ ., data = filtered_data2)
plot(model2)

summary(model2)
## 
## Call:
## lm(formula = Age^best.lam ~ ., data = filtered_data2)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.15157 -0.01413  0.00275  0.01741  0.32191 
## 
## Coefficients:
##                  Estimate Std. Error t value Pr(>|t|)    
## (Intercept)     7.156e-01  8.566e-04 835.367  < 2e-16 ***
## SexI            1.506e-02  3.217e-04  46.791  < 2e-16 ***
## SexM            1.866e-03  2.451e-04   7.614 2.69e-14 ***
## Diameter       -3.916e-02  1.339e-03 -29.243  < 2e-16 ***
## Height         -1.412e-01  3.282e-03 -43.033  < 2e-16 ***
## `Shell Weight` -1.510e-03  7.887e-05 -19.140  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.02725 on 74019 degrees of freedom
## Multiple R-squared:  0.5744, Adjusted R-squared:  0.5743 
## F-statistic: 1.998e+04 on 5 and 74019 DF,  p-value: < 2.2e-16

It’s actually a bit better, but the residuals still are far from normal. So now I’ll transform the predictor variables. In particular, I want to evaluate all the variables simultaneously to see the necessary power transform. And I’m power transforming the numeric variables as a function of the identity matrix.

quant_var = as.matrix(filtered_data2[2:4])
myt = powerTransform(quant_var~1)
myt
## Estimated transformation parameters 
##     Diameter       Height Shell Weight 
##    0.9689496    0.6552235    0.3040808

And now I’ll create a new dataframe with the transformed values:

transformed_filtered = filtered_data2[, c(2, 3, 4, 1, 5)]
for (i in 1:3){transformed_filtered[,i] = transformed_filtered[i]^myt$lambda[i]}

Now I’ll build a new model with the transformed variables. I’ll also add an interaction term (Sex * Diameter)

model3 = lm(formula = Age^best.lam ~ Diameter + Height + `Shell Weight` + 
    Sex + Sex * Diameter, data = transformed_filtered)

summary(model3)
## 
## Call:
## lm(formula = Age^best.lam ~ Diameter + Height + `Shell Weight` + 
##     Sex + Sex * Diameter, data = transformed_filtered)
## 
## Residuals:
##       Min        1Q    Median        3Q       Max 
## -0.151476 -0.013171  0.002876  0.016074  0.314387 
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)     0.724730   0.001442  502.47   <2e-16 ***
## Diameter        0.125716   0.002039   61.66   <2e-16 ***
## Height         -0.061617   0.003327  -18.52   <2e-16 ***
## `Shell Weight` -0.122834   0.001341  -91.61   <2e-16 ***
## SexI            0.083303   0.001501   55.49   <2e-16 ***
## SexM            0.025292   0.001704   14.84   <2e-16 ***
## Diameter:SexI  -0.071205   0.001408  -50.57   <2e-16 ***
## Diameter:SexM  -0.020207   0.001492  -13.54   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.02504 on 74017 degrees of freedom
## Multiple R-squared:  0.6406, Adjusted R-squared:  0.6406 
## F-statistic: 1.885e+04 on 7 and 74017 DF,  p-value: < 2.2e-16
plot(model3)

One thing right away is that the R-squared value is better than it was for model2 (a valid comparison since the dependent value was transformed in both cases). There’s probably still a little bit of a pattern in the residuals vs. fitted, but it’s much better. There are a few outliers which are messing with the QQ plot but it’s not egregious and I think it’s a major improvement on model1. Overall, it’s a quite simple model (R-squared = Adjusted R-squared) and pretty powerful given its simplicity.

I’ll now read in the test data. Importantly, I’ll apply the same transformations as earlier:

test_data = read_csv("/Users/gavrielsteinmetz-silber/Desktop/DATA605/605 Final/test.csv")
## Rows: 49368 Columns: 9
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): Sex
## dbl (8): id, Length, Diameter, Height, Weight, Shucked Weight, Viscera Weigh...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
filtered_test = test_data %>% 
  dplyr::select(Diameter, Height, `Shell Weight`, Sex, id)

for (i in 1:3){filtered_test[,i] = filtered_test[i]^myt$lambda[i]}

summary(filtered_test) 
##     Diameter          Height        Shell Weight        Sex           
##  Min.   :0.1462   Min.   :0.0000   Min.   :0.3828   Length:49368      
##  1st Qu.:0.8908   1st Qu.:0.4544   1st Qu.:1.5207   Class :character  
##  Median :1.0726   Median :0.5143   Median :1.8028   Mode  :character  
##  Mean   :1.0246   Mean   :0.4970   Mean   :1.7157                     
##  3rd Qu.:1.1932   3rd Qu.:0.5598   3rd Qu.:1.9618                     
##  Max.   :1.6007   Max.   :1.9748   Max.   :2.7692                     
##        id        
##  Min.   : 74051  
##  1st Qu.: 86393  
##  Median : 98734  
##  Mean   : 98734  
##  3rd Qu.:111076  
##  Max.   :123418
summary(transformed_filtered)
##     Diameter          Height         Shell Weight        Sex           
##  Min.   :0.1462   Min.   :0.05663   Min.   :0.3828   Length:74025      
##  1st Qu.:0.8908   1st Qu.:0.45436   1st Qu.:1.5207   Class :character  
##  Median :1.0726   Median :0.51434   Median :1.8028   Mode  :character  
##  Mean   :1.0230   Mean   :0.49653   Mean   :1.7135                     
##  3rd Qu.:1.1932   3rd Qu.:0.55978   3rd Qu.:1.9553                     
##  Max.   :1.5888   Max.   :1.18007   Max.   :2.7692                     
##       Age       
##  Min.   : 1.00  
##  1st Qu.: 8.00  
##  Median :10.00  
##  Mean   : 9.97  
##  3rd Qu.:11.00  
##  Max.   :29.00

I summarized this transformed data as well as the transformed training data just to make sure the transformations were done on the same columns. Indeed, the data look similar so that’s a sanity check. Finally, I’ll make predictions and then inverse transform the predictions using the (inverse of the) value I used to transform Age in the training data.

predictions_transformed = predict(model3, newdata = filtered_test)
predictions_original = predictions_transformed ^ (1 / best.lam)

summary(predictions_original)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   3.569   8.382  10.144   9.742  11.170  22.273
summary(transformed_filtered$Age)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##    1.00    8.00   10.00    9.97   11.00   29.00

I summarized the predictions to compare them with the summary of the Age in the training data. Clearly it doesn’t do a great job with the outliers but otherwise it’s not bad! Now, I could round the ages but I’ll actually keep them as they are (as the example data on the Kaggle page has them).

I’ll write a csv to upload:

submission_df = data.frame(id = filtered_test$id, Age = predictions_original)
submission_df$id = as.integer(submission_df$id) 
write.csv(submission_df, file = "submission_file.csv", row.names = FALSE)

And I uploaded the csv.

My Kaggle username is gste My private score is 1.51769 My public score is 1.52121