During week 10, our focus was on examining Transformations and Link functions. We delved into these topics using the apartments dataset, which comprises information about apartments in both San Francisco and New York City. Now, let’s analyze and provide feedback on our exploration of these concepts.
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.2 ✔ readr 2.1.4
## ✔ forcats 1.0.0 ✔ stringr 1.5.0
## ✔ ggplot2 3.4.3 ✔ tibble 3.2.1
## ✔ lubridate 1.9.2 ✔ 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(ggthemes)
library(ggrepel)
library(broom)
library(lindia)
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
Below, we upload the dataset and build a linear regression model.
url <- "https://raw.githubusercontent.com/leontoddjohnson/i590/main/data/apartments/apartments.csv"
apts <- read_delim(url, delim = ',')
## Rows: 492 Columns: 8
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl (8): in_sf, beds, bath, price, year_built, sqft, price_per_sqft, elevation
##
## ℹ 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.
model <- lm(price ~ price_per_sqft,
filter(apts, in_sf == 0))
rsquared <- summary(model)$r.squared
apts |>
filter(in_sf == 0) |>
ggplot(mapping = aes(x = price_per_sqft,
y = price)) +
geom_point() +
geom_smooth(method = 'lm', color = 'gray', linetype = 'dashed',
se = FALSE) +
geom_smooth(se = FALSE) +
labs(title = "Price vs. Price Per Sq. Ft.",
subtitle = paste("Linear Fit R-Squared =", round(rsquared, 3))) +
theme_classic()
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'
There are some notable concerns about the model that need addressing. Firstly, the choice of predictors, specifically using price per square foot as a predictor for price, poses a problem. This decision creates a built-in dependency, which goes against the assumption of independence in the model. Moreover, the model appears to overlook potentially influential predictors like neighborhood, number of bedrooms/bathrooms, and building amenities, raising the possibility of introducing bias into the results. The absence of randomization in the data also leaves room for underlying confounding factors that could impact the observed relationship between price and price per square foot.
Additionally, the exclusive reliance on R-squared as the sole metric for evaluating the model is a limitation. This approach provides a narrow perspective on model performance. Considering alternative metrics such as Mean Squared Error or Root Mean Squared Error could offer a more comprehensive assessment of predictive performance. Below is the modified code, now incorporating Mean Squared Error.
# Fit linear regression model
model <- lm(price ~ price_per_sqft, data = filter(apts, in_sf == 0))
# Make predictions
predictions <- predict(model, newdata = filter(apts, in_sf == 0))
# Calculate Mean Squared Error
mse <- mean((apts %>% filter(in_sf == 0) %>% pull(price) - predictions)^2)
# Visualize the data and linear fit
apts %>%
filter(in_sf == 0) %>%
ggplot(mapping = aes(x = price_per_sqft, y = price)) +
geom_point() +
geom_smooth(method = 'lm', color = 'gray', linetype = 'dashed', se = FALSE) +
geom_smooth(se = FALSE) +
labs(
title = "Price vs. Price Per Sq. Ft.",
subtitle = paste("Linear Fit MSE =", round(mse, 3))
) +
theme_classic()
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'
R-squared primarily emphasizes capturing the variability in the dependent variable, while Mean Squared Error (MSE) directly evaluates prediction accuracy by measuring the average squared differences, offering a more detailed understanding of the model’s effectiveness.
In power transformations, although new linear models were applied following the transformation, a direct comparison with the original model was not conducted. It would have been beneficial to incorporate a few lines of code to formally evaluate and compare the models, determining whether the power-transformed model yields a superior fit.
# Original Model
original_model <- lm(price ~ price_per_sqft, data = filter(apts, in_sf == 0))
# Transformed Model
apts <- apts %>%
mutate(log_price = log(price))
transformed_model <- lm(log_price ~ price_per_sqft, data = filter(apts, in_sf == 0))
# Model Comparison
summary(original_model)
##
## Call:
## lm(formula = price ~ price_per_sqft, data = filter(apts, in_sf ==
## 0))
##
## Residuals:
## Min 1Q Median 3Q Max
## -4289426 -1480152 19921 894222 17184132
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -3213431.7 322193.0 -9.974 <2e-16 ***
## price_per_sqft 3689.5 175.8 20.984 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2221000 on 222 degrees of freedom
## Multiple R-squared: 0.6648, Adjusted R-squared: 0.6633
## F-statistic: 440.3 on 1 and 222 DF, p-value: < 2.2e-16
summary(transformed_model)
##
## Call:
## lm(formula = log_price ~ price_per_sqft, data = filter(apts,
## in_sf == 0))
##
## Residuals:
## Min 1Q Median 3Q Max
## -1.1514 -0.3639 -0.0443 0.3023 1.9612
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 1.271e+01 7.256e-02 175.14 <2e-16 ***
## price_per_sqft 9.815e-04 3.960e-05 24.79 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.5001 on 222 degrees of freedom
## Multiple R-squared: 0.7346, Adjusted R-squared: 0.7334
## F-statistic: 614.5 on 1 and 222 DF, p-value: < 2.2e-16
# AIC Comparison
AIC(original_model)
## [1] 7186.49
AIC(transformed_model)
## [1] 329.266
The updated code incorporates explicit model comparison by computing and displaying AIC values for both the original and transformed models. AIC serves as a quantitative measure, offering a more informed evaluation of model performance and complexity. Optimal models exhibit lower AIC values, indicating a favorable balance between fit quality and simplicity. The transformed model demonstrates a significantly reduced AIC compared to the original, implying superior data fit. Unlike the previous reliance on visual assessments and R-squared values, this enhancement introduces AIC—a widely acknowledged metric—improving the precision of model evaluations by considering both fit accuracy and model intricacy.
The code section provides a thorough introduction to logistic regression, elucidating the model and its coefficients in predicting whether an apartment is located in San Francisco based on elevation. The incorporation of a visual representation of the sigmoid function aids comprehension by depicting how elevation impacts the probability of an apartment being in SF. However, the model evaluation aspect is deficient, lacking formal metrics like accuracy or ROC curves.
Furthermore, assumptions regarding the monotonic relationship between elevation and the likelihood of an apartment being in SF are made without conducting rigorous checks for linearity and multicollinearity. The model’s restricted use of a single predictor variable, focusing solely on elevation, neglects other potentially influential factors. Including additional predictors could bolster accuracy. The critique emphasizes the significance of scrutinizing dataset characteristics, highlighting the imperative to address issues like data quality, representativeness, and biases to ensure the model’s conclusions are reliable. Incorporating these considerations and refining model evaluation would enhance the robustness and applicability of the logistic regression analysis.
The code explains Poisson Regression for modeling count data, highlighting the importance of transforming the response variable by taking its logarithm. Visualizations like histograms and scatter plots help understand apartment prices in San Francisco and New York City. However, the square footage variable is transformed using both square root and logarithm, which might be too complex without a clear reason. The code applies Poisson Regression to predict apartment prices based on the square root of square footage, but the interpretation of coefficients is unclear, especially when introducing the concept of percent change.
It’s assumed that all other variables are constant, which might not be explicitly stated. The visualization of the Poisson model is helpful, but the explanation of coefficients could be simpler. Overall, the code is informative but could benefit from clearer explanations, especially regarding variable transformations and model interpretation, for a broader audience. Simplifying these aspects would enhance the code’s clarity and make it more accessible.