0% found this document useful (0 votes)
10 views6 pages

Linear & Logistic Regression Analysis

The document provides a comprehensive overview of various regression analyses, including linear and logistic regression, using both random data points and real datasets such as California housing and diabetes data. It also covers hypothesis testing through chi-square tests, examining relationships between categorical variables like smoking and exercise. Additionally, it includes code snippets in R for implementing these analyses, ensuring reproducibility with set seed values.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views6 pages

Linear & Logistic Regression Analysis

The document provides a comprehensive overview of various regression analyses, including linear and logistic regression, using both random data points and real datasets such as California housing and diabetes data. It also covers hypothesis testing through chi-square tests, examining relationships between categorical variables like smoking and exercise. Additionally, it includes code snippets in R for implementing these analyses, ensuring reproducibility with set seed values.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Linear & Logistic Regression with Random Data Points

CopyEdit

[Link](123) # Ensuring reproducibility

# Generating random data

x <- rnorm(100) # 100 random values from a normal distribution

y <- 3*x + rnorm(100) # Linear relation with some noise

# Linear Regression

linear_model <- lm(y ~ x)

summary(linear_model)

# Logistic Regression (Generating binary outcome)

y_binary <- ifelse(y > mean(y), 1, 0)

logistic_model <- glm(y_binary ~ x, family = binomial)

summary(logistic_model)

2. Linear & Logistic Regression for California Housing Dataset using API

CopyEdit

library(AppliedPredictiveModeling)

library(caret)

# Load dataset from API

data_url <- "[Link]


ml/master/datasets/housing/[Link]"

housing_data <- [Link](data_url)

# Preprocessing

housing_data <- [Link](housing_data) # Removing missing values

housing_data$median_house_value <- housing_data$median_house_value / 100000 # Scaling

# Linear Regression

linear_model <- lm(median_house_value ~ median_income, data = housing_data)


summary(linear_model)

# Logistic Regression (Converting target to binary)

housing_data$high_value <- ifelse(housing_data$median_house_value >


median(housing_data$median_house_value), 1, 0)

logistic_model <- glm(high_value ~ median_income, data = housing_data, family = binomial)

summary(logistic_model)

3. Linear & Logistic Regression with Random Data Points (No API)

CopyEdit

[Link](42)

# Generating Random Data

x <- rnorm(100)

y <- 5*x + rnorm(100)

# Linear Regression

linear_model <- lm(y ~ x)

summary(linear_model)

# Logistic Regression

y_binary <- ifelse(y > mean(y), 1, 0)

logistic_model <- glm(y_binary ~ x, family = binomial)

summary(logistic_model)

4. Logistic Regression: Predicting Magazine Subscription

CopyEdit

[Link](100)

# Generating Sample Data

customers <- [Link](

age = sample(18:70, 1000, replace = TRUE),

income = sample(20000:100000, 1000, replace = TRUE),


buy_magazine = sample(0:1, 1000, replace = TRUE)

# Logistic Regression

logistic_model <- glm(buy_magazine ~ age + income, data = customers, family = binomial)

summary(logistic_model)

5. Predict Diabetes Using Pima Indian Diabetes Dataset

CopyEdit

library(MASS)

# Load dataset

data_url <- "[Link]


[Link]"

col_names <- c("Pregnancies", "Glucose", "BloodPressure", "SkinThickness", "Insulin", "BMI",


"DiabetesPedigree", "Age", "Outcome")

diabetes_data <- [Link](data_url, header = FALSE, [Link] = col_names)

# Logistic Regression

logistic_model <- glm(Outcome ~ ., data = diabetes_data, family = binomial)

summary(logistic_model)

6. Predict Bank Term Deposit Subscription (UCI Data)

CopyEdit

data_url <- "[Link]

bank_data <- [Link](data_url, sep = ";")

# Converting categorical to numeric

bank_data$y <- ifelse(bank_data$y == "yes", 1, 0)

# Logistic Regression

logistic_model <- glm(y ~ age + job + marital + education, data = bank_data, family = binomial)

summary(logistic_model)
7. Checking ‘cyl’ and ‘carb’ Dependency in mtcars Dataset

CopyEdit

data(mtcars)

str(mtcars)

# Checking if 'cyl' and 'carb' exist

if ("cyl" %in% colnames(mtcars) & "carb" %in% colnames(mtcars)) {

print("Both variables are in the dataset.")

} else {

print("One or both variables are missing.")

8. Chi-Square Test for ‘cyl’ and ‘carb’

CopyEdit

# Creating contingency table

contingency_table <- table(mtcars$cyl, mtcars$carb)

# Chi-square test

chi_test <- [Link](contingency_table)

chi_test

9. Hypothesis Test for Smoking vs. Exercise (Survey Data)

CopyEdit

# Generating Random Survey Data

[Link](50)

survey_data <- [Link](

smoking = sample(c("Yes", "No"), 200, replace = TRUE),

exercise = sample(c("Regular", "Occasional", "None"), 200, replace = TRUE)

)
# Contingency table

survey_table <- table(survey_data$smoking, survey_data$exercise)

# Chi-square test

chi_test <- [Link](survey_table)

chi_test

10. Chi-Square Independence Test (Textbook Formula)

CopyEdit

# Observed Data

observed <- matrix(c(50, 30, 20, 40, 60, 30), nrow = 2, byrow = TRUE)

rownames(observed) <- c("Smokers", "Non-Smokers")

colnames(observed) <- c("Regular", "Occasional", "None")

# Computing expected frequencies

row_totals <- rowSums(observed)

col_totals <- colSums(observed)

total <- sum(observed)

expected <- outer(row_totals, col_totals) / total

# Computing Chi-square statistic

chi_square_stat <- sum((observed - expected)^2 / expected)

df <- (nrow(observed) - 1) * (ncol(observed) - 1)

# Compute p-value

p_value <- 1 - pchisq(chi_square_stat, df)

# Output results

cat("Chi-square statistic:", chi_square_stat, "\n")

cat("Degrees of freedom:", df, "\n")

cat("P-value:", p_value, "\n")

Explanation:
• Observed Frequencies: Given survey data of smoking vs. exercise.

• Expected Frequencies: Computed using row and column totals.

• Chi-square Statistic: Measures difference between observed & expected values.

• P-value: If p < 0.05, we reject the null hypothesis (smoking is dependent on exercise).

Common questions

Powered by AI

Random data generation serves as a powerful tool to simulate real-world uncertainty and variability, allowing students to engage interactively with concepts of statistical modeling and hypothesis testing without real-world data restrictions. It facilitates step-by-step illustration of model fitting, assumptions validation, and hypothesis test execution, enhancing comprehension through experimentation and active learning. This deepens understanding by linking theory with practical application, making abstract concepts more accessible .

Performing linear regression on random data points helps in understanding whether a linear relationship exists between the generated variables even when some level of noise is introduced. This can illustrate the behavior of linear models under conditions of uncertainty and randomness, allowing practitioners to analyze how well the model can capture the underlying relationship and predict outcomes in real-world data scenarios .

The logistic regression model quantifies how variables like age and income influence magazine purchasing behavior by estimating the likelihood (odds) of subscription. The coefficients from the logistic regression output provide insight into the sign and magnitude of change in log-odds of subscription with respect to a unit change in predictors. A positive coefficient indicates an increased likelihood, while negative suggests a decrease, contingent upon statistical significance as determined by p-values .

Using logistic regression on the Pima Indian Diabetes dataset allows researchers to quantify the influence of various risk factors, like Glucose, BMI, etc., on the likelihood of diabetes occurrence. The model's coefficients elucidate how each factor increases or decreases the risk, thereby providing predictive insights into health outcomes. This aids in early identification of high-risk individuals and enables tailored preventive strategies or interventions .

The chi-square test for 'cyl' and 'carb' reveals whether there is a statistically significant association between these categorical variables in the mtcars dataset. A significant chi-square statistic, with a p-value less than 0.05, would indicate a dependency or association, implying that the distribution of 'carb' is related to different levels of 'cyl'. Conversely, non-significance suggests independence, thus implying no association between these features .

Converting categorical outcome variables to numerical is essential for logistic regression because the algorithm requires numerical input to calculate the probability of class membership. This conversion, typically using binary encoding, allows the model to quantify relational patterns and predict outcomes based on feature influences. It simplifies the response to a binary classification, facilitating optimization and probability estimation of term deposit subscriptions .

Preprocessing, such as removing missing values, ensures the integrity and completeness of inputs into the regression model, preventing inaccuracies due to null data. Scaling, particularly normalization, ensures equal treatment across various numerical features, preventing features with larger values from disproportionately influencing the model. Together, these steps improve the model's accuracy and consistency, leading to more reliable and interpretable regression coefficients and outcomes .

Logistic regression predicts binary outcomes by modeling the log-odds of class membership as a linear combination of predictor variables. Summary statistics, including coefficients, p-values, and metrics like AIC, provide insights into predictor significance, model fit, and how well the model captures data variability. This evaluation is crucial for interpreting the model's effectiveness, reliability, and for identifying key predictors that significantly influence the prediction outcome .

Converting the response variable, median house value, to binary is crucial in using logistic regression as it facilitates the prediction of dichotomous outcomes, specifically allowing the model to compute probabilities for houses being categorized as high-value or not. This impacts model performance by simplifying continuous data into categorical predictions, thus better focusing the logistic regression on capturing trends in house valuation that define high-value status .

The chi-square independence test involves constructing a contingency table of observed frequencies, computing expected frequencies using the formula (row total * column total) / overall total for each cell, calculating the chi-square statistic as the sum of (observed - expected)^2 / expected across all cells, and determining the p-value using the chi-square distribution. A p-value below 0.05 indicates rejecting the null hypothesis of independence, suggesting a dependency between the categorical variables .

You might also like