Skip to content
Project: Predicting Temperature in London
As the climate changes, predicting the weather becomes ever more important for businesses. You have been asked to support on a machine learning project with the aim of building a pipeline to predict the climate in London, England. Specifically, the model should predict mean temperature in degrees Celsius (°C).
Since the weather depends on a lot of different factors, you will want to run a lot of experiments to determine what the best approach is to predict the weather. In this project, you will run experiments for different regression models predicting the mean temperature, using a combination of sklearn
and mlflow
.
You will be working with data stored in london_weather.csv
, which contains the following columns:
- date - recorded date of measurement - (int)
- cloud_cover - cloud cover measurement in oktas - (float)
- sunshine - sunshine measurement in hours (hrs) - (float)
- global_radiation - irradiance measurement in Watt per square meter (W/m2) - (float)
- max_temp - maximum temperature recorded in degrees Celsius (°C) - (float)
- mean_temp - target mean temperature in degrees Celsius (°C) - (float)
- min_temp - minimum temperature recorded in degrees Celsius (°C) - (float)
- precipitation - precipitation measurement in millimeters (mm) - (float)
- pressure - pressure measurement in Pascals (Pa) - (float)
- snow_depth - snow depth measurement in centimeters (cm) - (float)
# Run this cell to install mlflow
!pip install mlflow
Hidden output
# Run this cell to import the modules you require
import pandas as pd
import numpy as np
import mlflow
import mlflow.sklearn
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
# Read in the data
weather = pd.read_csv("london_weather.csv")
# Start coding here
# Use as many cells as you like
# Run this cell to install mlflow
!pip install mlflow
# Import necessary libraries
import pandas as pd
import numpy as np
import mlflow
import mlflow.sklearn
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
# Load the dataset
weather = pd.read_csv("london_weather.csv")
# Display basic information about the dataset
print(weather.info())
# Step 1: Data Preprocessing
# Drop any rows with missing target values
weather = weather.dropna(subset=['mean_temp'])
# Separate features and target variable
X = weather.drop(columns=['date', 'mean_temp'])
y = weather['mean_temp']
# Handle missing values
imputer = SimpleImputer(strategy='mean')
X_imputed = imputer.fit_transform(X)
# Scale the features
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_imputed)
# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
# Step 2: Initialize MLflow
mlflow.set_experiment("London Temperature Prediction")
# Step 3: Define a function to train, evaluate, and log models
def train_and_log_model(model, model_name, params={}):
with mlflow.start_run(run_name=model_name):
# Train the model
model.set_params(**params)
model.fit(X_train, y_train)
# Make predictions and calculate RMSE
y_pred = model.predict(X_test)
rmse = mean_squared_error(y_test, y_pred, squared=False)
# Log model, parameters, and RMSE metric
mlflow.log_params(params)
mlflow.log_metric("rmse", rmse)
mlflow.sklearn.log_model(model, model_name)
print(f"{model_name} RMSE: {rmse}")
return rmse
# Step 4: Experiment with different models and log their RMSE values
# Linear Regression
linear_model = LinearRegression()
train_and_log_model(linear_model, "Linear Regression")
# Decision Tree Regressor
tree_model = DecisionTreeRegressor(random_state=42)
tree_params = {'max_depth': 5}
train_and_log_model(tree_model, "Decision Tree Regressor", tree_params)
# Random Forest Regressor
rf_model = RandomForestRegressor(random_state=42)
rf_params = {'n_estimators': 100, 'max_depth': 10}
train_and_log_model(rf_model, "Random Forest Regressor", rf_params)
# Step 5: Retrieve and store experiment results
experiment_id = mlflow.get_experiment_by_name("London Temperature Prediction").experiment_id
experiment_results = mlflow.search_runs([experiment_id])
# Display experiment results
print(experiment_results[['run_id', 'metrics.rmse', 'params.max_depth', 'params.n_estimators']])