0% found this document useful (0 votes)
16 views4 pages

Regression Analysis with UCI Datasets

The document outlines a program that demonstrates Linear Regression using the California Housing Dataset and Polynomial Regression using the Auto MPG Dataset. It includes functions to train models, visualize results, and evaluate performance metrics such as Mean Squared Error and R^2 Score. The program is executed in the main block to showcase both regression techniques.

Uploaded by

sadiqhamuskan4
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)
16 views4 pages

Regression Analysis with UCI Datasets

The document outlines a program that demonstrates Linear Regression using the California Housing Dataset and Polynomial Regression using the Auto MPG Dataset. It includes functions to train models, visualize results, and evaluate performance metrics such as Mean Squared Error and R^2 Score. The program is executed in the main block to showcase both regression techniques.

Uploaded by

sadiqhamuskan4
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

Program 7

7. Develop a program to demonstrate the working of Linear Regression and Polynomial Regression. Use
Boston Housing Dataset for Linear Regression and Auto MPG Dataset (for vehicle fuel efficiency
prediction) for Polynomial Regression.

import numpy as np
import pandas as pd
import [Link] as plt
from [Link] import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from [Link] import PolynomialFeatures, StandardScaler
from [Link] import make_pipeline
from [Link] import mean_squared_error, r2_score

def linear_regression_california():
housing = fetch_california_housing(as_frame=True)
X = [Link][["AveRooms"]]
y = [Link]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

model = LinearRegression()
[Link](X_train, y_train)

y_pred = [Link](X_test)

[Link](X_test, y_test, color="blue", label="Actual")


[Link](X_test, y_pred, color="red", label="Predicted")
[Link]("Average number of rooms (AveRooms)")
[Link]("Median value of homes ($100,000)")
[Link]("Linear Regression - California Housing Dataset")
[Link]()
[Link]()

print("Linear Regression - California Housing Dataset")


print("Mean Squared Error:", mean_squared_error(y_test, y_pred))
print("R^2 Score:", r2_score(y_test, y_pred))

def polynomial_regression_auto_mpg():
url = "[Link]
column_names = ["mpg", "cylinders", "displacement", "horsepower", "weight", "acceleration",
"model_year", "origin"]
data = pd.read_csv(url, sep='\s+', names=column_names, na_values="?")
data = [Link]()

X = data["displacement"].[Link](-1, 1)
y = data["mpg"].values

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

poly_model = make_pipeline(PolynomialFeatures(degree=2), StandardScaler(), LinearRegression())


poly_model.fit(X_train, y_train)

y_pred = poly_model.predict(X_test)

[Link](X_test, y_test, color="blue", label="Actual")


[Link](X_test, y_pred, color="red", label="Predicted")
[Link]("Displacement")
[Link]("Miles per gallon (mpg)")
[Link]("Polynomial Regression - Auto MPG Dataset")
[Link]()
[Link]()

print("Polynomial Regression - Auto MPG Dataset")


print("Mean Squared Error:", mean_squared_error(y_test, y_pred))
print("R^2 Score:", r2_score(y_test, y_pred))

if __name__ == "__main__":
print("Demonstrating Linear Regression and Polynomial Regression\n")
linear_regression_california()
polynomial_regression_auto_mpg()

output:

Common questions

Powered by AI

Overfitting occurs in Polynomial Regression when the model becomes excessively complex by fitting to noise and minor fluctuations in the training data rather than the underlying pattern, often due to a high degree polynomial. This can result in poor generalization to new data. To mitigate overfitting, strategies such as using cross-validation to select an appropriate polynomial degree, regularization techniques like Ridge or Lasso regression to penalize excessive model complexity, and ensuring that there is enough data for training by reducing model complexity or increasing dataset size, can be employed. Additionally, visual diagnostics such as plotting learning curves may reveal signs of overfitting .

Visual plots are crucial for evaluating regression model performance as they provide a graphical representation of how well the model fits the observed data. In the case of Linear Regression with the California Housing dataset, plots showing actual versus predicted values allow for a straightforward assessment of the model's predictive accuracy. Similarly, for the Auto MPG dataset, scatter plots in Polynomial Regression help visualize the relationship between displacement and mpg, indicating whether the polynomial model captures non-linear patterns that a linear model might miss. These visualizations support error diagnostics and model validation, offering a quick assessment of model fit and overfitting or underfitting issues .

The Auto MPG dataset includes features like "horsepower" that may contain missing values represented as '?', requiring cleaning steps such as imputation or removal before analysis. Furthermore, since this dataset contains a mix of numerical and categorical data (e.g., origin as a categorical variable), categorical encoding might be necessary for regression models to interpret these variables correctly. In contrast, the California Housing dataset used features already numerical and standardized, minimizing initial preprocessing needs. Thus, the varied types and quality of data within the Auto MPG dataset necessitate additional preprocessing for accurate model application and performance optimization .

Mean Squared Error (MSE) and R^2 score are standard metrics for quantifying model performance in regression. MSE measures the average squared difference between actual and predicted values, providing a sense of prediction accuracy. It is sensitive to outliers, thereby indicating how well the model captures extreme variations in data. The R^2 score, or coefficient of determination, indicates the proportion of variance in the dependent variable predictable from the independent variable, thus reflecting the model's explanatory power. Together, they offer comprehensive insight into both the accuracy and effectiveness of a regression model .

Polynomial Regression improves prediction by introducing a polynomial relationship between input features and the target variable. For the Auto MPG Dataset, using Polynomial Regression allows the model to capture non-linear relationships between displacement and miles per gallon (mpg), which Linear Regression might not fully capture as it assumes a straight-line relationship. The inclusion of higher degree terms in Polynomial Regression enables more flexibility in fitting the data, potentially resulting in better predictive performance, as reflected in lower mean squared error and possibly higher R^2 score compared to Linear Regression .

The choice of target and predictor variables is pivotal as it directly impacts the model's ability to uncover meaningful relationships and make accurate predictions. In Linear Regression applied to the California Housing dataset, the predictor "AveRooms" provides a simple yet effective metric likely correlated with housing prices, suitable for linear analysis. Conversely, the Auto MPG dataset employs "displacement" as a predictor for "mpg" under Polynomial Regression, capturing its non-linear effect on fuel efficiency. The alignment between variable type, predictor-target relationship and regression model complexity ensures robust analysis and accurate model conclusions .

Using Linear Regression on the California Housing Dataset helps in understanding how well the predictor variable, the average number of rooms (AveRooms), explains the variability in the target variable, the median value of homes. The mean squared error (MSE) provides information about the average squared difference between the observed and predicted values, indicating the model's predictive accuracy. A lower MSE signifies better model performance. The R^2 score reflects the proportion of variance in the target variable that is predictable from the predictor variables. A higher R^2 means a better fit of the model. Therefore, these metrics provide insights into the adequacy of Linear Regression in explaining the relationship between these variables .

Using a smaller test dataset, like the 80/20 split used in the regression analysis, poses implications such as increased variance of evaluation metrics and reduced generalization capability assessments. Smaller test sets may not fully represent the diversity of the entire dataset, leading to overly optimistic or pessimistic assessments of model performance. This can impede the model's usefulness for new or unseen data. A careful balance in test size selection is critical; a larger test set might offer more reliable evaluations at the expense of reduced training data, potentially impairing the model's learning ability .

StandardScaler is used to normalize features by removing the mean and scaling to unit variance. In Polynomial Regression, especially when higher degree terms are included, the range of feature values can vary greatly, causing instability in model convergence and sensitivity to input scales. By standardizing the features, StandardScaler ensures that each feature contributes equally to the result, improving numerical stability and model convergence, thereby enhancing the overall model performance. Its role in the pipeline is crucial for preventing biasing the model towards features with larger numerical ranges .

Naive Linear Regression assumes a straight-line relationship between independent and dependent variables, which can be limiting for datasets with inherent non-linear relationships. This assumption may result in high bias, where the model fails to capture the true underlying patterns, leading to inaccurate predictions and poor generalization. For instance, important complexities in pattern behavior, like quadratic or exponential growths, would be missed, skewing model outputs. Such challenges necessitate exploring models capable of accommodating non-linearity, such as Polynomial Regression, which can better capture the intricacies of the data .

You might also like