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

7th ExP

The document outlines a program demonstrating Linear Regression using the Boston Housing Dataset and Polynomial Regression using the Auto MPG Dataset. It includes data loading, model training, predictions, and evaluation metrics such as R² Score and Mean Squared Error. Visualizations of the regression results are also provided for both datasets.

Uploaded by

rocknyc26
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 views4 pages

7th ExP

The document outlines a program demonstrating Linear Regression using the Boston Housing Dataset and Polynomial Regression using the Auto MPG Dataset. It includes data loading, model training, predictions, and evaluation metrics such as R² Score and Mean Squared Error. Visualizations of the regression results are also provided for both datasets.

Uploaded by

rocknyc26
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
You are on page 1/ 4

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 matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_boston # For Linear Regression
import warnings
warnings.filterwarnings('ignore') # Ignore deprecation and other warnings
%matplotlib inline
# -----------------------------------------
# PART 1: LINEAR REGRESSION – Boston Housing Dataset
# -----------------------------------------
print("\n--- Linear Regression on Boston Housing Dataset ---")
# Load the dataset
boston = load_boston()
df_boston = pd.DataFrame(boston.data, columns=boston.feature_names)
df_boston['PRICE'] = boston.target
# Use 'RM' (average number of rooms per dwelling) to predict 'PRICE'
X = df_boston[['RM']]
y = df_boston['PRICE']
# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)
# Linear Regression model
lr_model = LinearRegression()
lr_model.fit(X_train, y_train)
# Predictions
y_pred = lr_model.predict(X_test)
# Evaluation
print("R² Score:", r2_score(y_test, y_pred))
print("Mean Squared Error:", mean_squared_error(y_test, y_pred))
# Plot
plt.figure(figsize=(8, 5))
plt.scatter(X_test, y_test, color='blue', label='Actual')
plt.plot(X_test, y_pred, color='red', linewidth=2, label='Predicted')
plt.xlabel("Average number of rooms per dwelling (RM)")
plt.ylabel("House Price")
plt.title("Linear Regression: Boston Housing")
plt.legend()
plt.show()
# -----------------------------------------
# PART 2: POLYNOMIAL REGRESSION – Auto MPG Dataset
# -----------------------------------------
print("\n--- Polynomial Regression on Auto MPG Dataset ---")

# Load Auto MPG dataset from seaborn


auto_data = sns.load_dataset("mpg")

# Drop missing values


auto_data.dropna(inplace=True)

# Use 'horsepower' to predict 'mpg' (fuel efficiency)


X = auto_data[['horsepower']].values
y = auto_data['mpg'].values

# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)

# Polynomial Features (degree 2)


poly = PolynomialFeatures(degree=2)
X_train_poly = poly.fit_transform(X_train)
X_test_poly = poly.transform(X_test)

# Polynomial Regression model


poly_model = LinearRegression()
poly_model.fit(X_train_poly, y_train)

# Predictions
y_pred_poly = poly_model.predict(X_test_poly)
# Evaluation
print("R² Score:", r2_score(y_test, y_pred_poly))
print("Mean Squared Error:", mean_squared_error(y_test, y_pred_poly))

# Visualization
plt.figure(figsize=(8, 5))
# Sort values for smooth curve
sort_idx = X_test[:, 0].argsort()
plt.scatter(X_test, y_test, color='blue', label='Actual')
plt.plot(X_test[sort_idx], y_pred_poly[sort_idx], color='green', linewidth=2,
label='Predicted Curve')
plt.xlabel("Horsepower")
plt.ylabel("Miles per Gallon (mpg)")
plt.title("Polynomial Regression: Auto MPG")
plt.legend()
plt.show()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy