Here's a comprehensive data science code example that demonstrates a complete machine learning pipeline for a regression task using Python. This example predicts housing prices based on various features:
python
# Import necessary libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
import warnings
warnings.filterwarnings('ignore')
# 1. Data Loading and Exploration
print("1. Loading and exploring dataset...")
housing = fetch_california_housing()
df = pd.DataFrame(housing.data, columns=housing.feature_names)
df['target'] = housing.target
# Basic data exploration
print("\nDataset Shape:", df.shape)
print("\nFeature Names:", housing.feature_names)
print("\nFirst 5 rows:")
print(df.head())
print("\nStatistical Summary:")
print(df.describe())
# 2. Data Visualization
print("\n2. Creating visualizations...")
plt.figure(figsize=(12, 6))
sns.heatmap(df.corr(), annot=True, cmap='coolwarm')
plt.title("Feature Correlation Matrix")
plt.show()
# 3. Data Preprocessing
print("\n3. Preprocessing data...")
X = df.drop('target', axis=1)
y = df['target']
# Split data into train and test sets
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# Feature scaling
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# 4. Model Building
print("\n4. Training models...")
# Linear Regression Baseline
lr = LinearRegression()
lr.fit(X_train_scaled, y_train)
lr_pred = lr.predict(X_test_scaled)
# Random Forest with Hyperparameter Tuning
rf = RandomForestRegressor(random_state=42)
param_grid = {
'n_estimators': [100, 200],
'max_depth': [10, 20, None],
'min_samples_split': [2, 5]
}
grid_search = GridSearchCV(rf, param_grid, cv=5, scoring='neg_mean_squared_error')
grid_search.fit(X_train_scaled, y_train)
best_rf = grid_search.best_estimator_
rf_pred = best_rf.predict(X_test_scaled)
# 5. Model Evaluation
print("\n5. Model Performance:")
print("\nLinear Regression:")
print(f"RMSE: {np.sqrt(mean_squared_error(y_test, lr_pred)):.4f}")
print(f"R² Score: {r2_score(y_test, lr_pred):.4f}")
print("\nRandom Forest (Tuned):")
print(f"RMSE: {np.sqrt(mean_squared_error(y_test, rf_pred)):.4f}")
print(f"R² Score: {r2_score(y_test, rf_pred):.4f}")
# 6. Feature Importance Visualization
print("\n6. Feature Importance Analysis...")
importances = best_rf.feature_importances_
indices = np.argsort(importances)
plt.figure(figsize=(10, 6))
plt.barh(range(X.shape[1]), importances[indices])
plt.yticks(range(X.shape[1]), [housing.feature_names[i] for i in indices])
plt.title("Feature Importance in Random Forest")
plt.tight_layout()
plt.show()
# 7. Residual Analysis
print("\n7. Generating residual plot...")
plt.figure(figsize=(10, 6))
plt.scatter(lr_pred, lr_pred - y_test, c='blue', label='Linear Regression')
plt.scatter(rf_pred, rf_pred - y_test, c='red', label='Random Forest')
plt.hlines(y=0, xmin=0, xmax=5, colors='black', linestyles='--')
plt.xlabel("Predicted Values")
plt.ylabel("Residuals")
plt.title("Residual Plot")
plt.legend()
plt.show()
print("\nAnalysis Complete!")
This code demonstrates:
Complete Data Science Pipeline:
Data loading from scikit-learn's built-in dataset
Exploratory Data Analysis (EDA) with statistical summaries
Data visualization (correlation matrix)
Feature scaling and preprocessing
Model training with hyperparameter tuning
Model evaluation using RMSE and R² metrics
Feature importance analysis
Residual plot visualization
Key Features:
Multiple algorithm comparison (Linear Regression vs Random Forest)
Hyperparameter tuning using GridSearchCV
Comprehensive visualizations using Matplotlib and Seaborn
Error analysis and diagnostics
Feature importance interpretation
Output:
Prints evaluation metrics
Generates three visualization plots:
Correlation matrix
Feature importance bar chart
Residual plot
To use this code:
Ensure you have the required libraries installed (numpy, pandas, scikit-learn, matplotlib, seaborn)
Run in a Jupyter notebook or Python environment with GUI support for visualizations
The code will automatically download the California Housing dataset
You can modify this template for different datasets by changing the data loading section and adjusting the feature engineering/modeling steps accordingly. For classification tasks, you'd need to modify the problem type and use appropriate evaluation metrics.