# California data Dataset Linear Regression
course: Academy — 65-GENAI-for-Engineers
module: Academy/65-GENAI-for-Engineers
type: notebook
source_url: https://personal-learn.armco.dev/files/Academy/65-GENAI-for-Engineers/folders/Live_Intervention_Linear_Regression_Folder/California_data_Dataset_Linear_Regression.ipynb
---
[cell 1 code]
# Import required libraries
import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
[cell 2 code]
# Load California Housing dataset
california = fetch_california_housing(as_frame=True)
data = california.frame # Convert to pandas DataFrame
data.head()
[cell 3 code]
data.info()
[cell 4 code]
data.describe()
[cell 5 code]
import matplotlib.pyplot as plt
import seaborn as sns
# 1. Histogram of Dependent Variable (DV)
plt.figure(figsize=(6,4))
sns.histplot(data["MedHouseVal"], bins=30, kde=True, color="skyblue")
plt.title("Histogram of Median House Value")
plt.xlabel("Median House Value")
plt.ylabel("Frequency")
plt.show()
[cell 6 code]
# 2. Scatterplot: DV vs Independent Variable
# Example: MedHouseVal ~ MedInc (Income)
plt.figure(figsize=(6,4))
sns.scatterplot(x="MedInc", y="MedHouseVal", data=data, alpha=0.4)
plt.title("Scatterplot: House Value vs Median Income")
plt.xlabel("Median Income")
plt.ylabel("Median House Value")
plt.show()
[cell 7 code]
# Select one predictor (Median Income) and target (House Value)
X_slr = data[["MedInc"]] # Feature: Median Income
y = data["MedHouseVal"] # Target: Median House Value
[cell 8 code]
# Split into train & test sets
X_train, X_test, y_train, y_test = train_test_split(X_slr, y, test_size=0.2, random_state=42)
[cell 9 code]
# Create & train the model
slr_model = LinearRegression()
slr_model.fit(X_train, y_train)
[cell 10 code]
# Print coefficient and intercept
print("SLR Coefficient:", slr_model.coef_) # Effect of income on house value
print("SLR Intercept:", slr_model.intercept_)
[cell 11 code]
# Evaluate model (R² score)
print("SLR Score:", slr_model.score(X_train, y_train))
[cell 12 code]
# Evaluate model (R² score)
print("SLR Score:", slr_model.score(X_test, y_test))