We Can Become Weather Forecasters With ML

Rifah Maulidya
Adventures in Consumer Technology
6 min readJul 3, 2024

Becoming the forecaster seems interesting, here is how you can do that assisted by ML aka machine learning!šŸ”®

Photo by Johannes Plenio on Pexels

When I wake up, I brush my teeth and face to start my morning. Being fresh, now I want to open the windows and doors to see my cats (wild cats, two orange and one grey) that always come to my house asking for food. Today is sunny and bright, so this is a wonderful day to start working. After 4 hours, the weather outside suddenly changes into windy and soon will rain, of course itā€™s cold. It always repeats and happens every year. This is what climate change is, one of the global challenges that we should be aware of.

Through this article, we make this awareness into reality and contribute to tackling the challenge. Here I want to talk about the challenge of climate change and I want to show you how to build a machine learning model to predict temperature anomalies.

The beginning

Today our planet has to address one of the most urgent problems ā€” climate change. There is a need for an immediate response because rapid increases in world temperature, melting poles, and more frequent disasters are some of the depressing signals. Machine learning (ML) is a subfield within AI domain that deals with enabling computers to learn from data without being explicitly programmed, which provides innovative solutions for addressing these challenges. Here, machine learning can assist in forecasting climate patterns, optimizing resource utilization, and protecting our environment by incorporating a lot of information and advanced algorithms.

Will the predictive climate model work?

The prediction of extreme weather and climate change is now possible because of the new era that is being impacted by some machine learning technologies. By analyzing past weather records, these predictive tools can help with future weather predictions for any area of interest which will make decision-making processes affecting development initiatives or disaster preparedness mechanisms amidst other considerations. One such way involves using heatwave detection algorithms that inform response decisions by localities regarding their vulnerability coverage through rainfall detection systems at those moments when such events become close. These are the various situations where machine learning can be used:

1. Environmental monitoring

Itā€™s more important than ever to keep an eye on ecosystems and environmental health if weā€™re going to do something about climate change, and thatā€™s where artificial intelligence comes into play! If we look at some specific cases ā€” such as using Googleā€™s artificial intelligence in satellite imagery processing applications within ā€œAI for Social Goodā€ ā€” then one may find modern approaches like those described above which have already been applied. AI also can predict pollution levels based on real data that have been recorded from highways or main roads through sensors, with this action we can reduce harmful emissions and protect public health.

2. Renewable energy optimization

Wind and solar power play a key role in reducing emissions of greenhouse gases. By predicting energy output based on weather conditions and optimizing control mechanisms of renewable energy plants, machine learning helps increase the efficiency of these energy sources. For instance, ML algorithms are used to analyze the weather data to forecast solar power generation thus assisting grid operators in balancing supply and demand more effectively. Smart grids make use of artificial intelligence to handle electricity distribution; thus enhancing energy efficiency.

3. Disaster prediction and management

Global warming triggers natural calamities like hurricanes, floods, and wildfires experts say. We have computer systems known as Machine learning models which can foretell these happenings beforehand hence giving people in various localities time to prepare for them. For instance, there have been developed some artificial intelligence (AI) based systems that can predict the course or intensity levels of a hurricane such that those responsible for making decisions related to evacuation routes will make sound judgments on it. Artificial intelligence (AI) improves emergency response strategies. In natural disasters, machine learning can use current information to ensure the distribution of resources is done in a well-coordinated manner to save lives efficiently.

How you can leverage machine learning for climate action?

After we take a look at how climate change can affect each other, itā€™s time for us to take action to utilize machine learning facing climate change! How? here is the practical guide for making simple predictions of whatā€™s the next weather or the temperature.

Import the library

import pandas as pd 
import matplotlib.pyplot as plt
import seaborn as sns

Load the dataset

Here we will use the dataset from NASA which is global temperature anomaly data from 1880 to 2024. Inside of this, it includes the land ocean: global means and we need to read it. The link is included in the ā€˜data_urlā€™ if you want to check!

# Load global temperature anomaly data
data_url = "https://data.giss.nasa.gov/gistemp/tabledata_v4/GLB.Ts+dSST.csv"
df = pd.read_csv(data_url, skiprows=1)Clean the data

Clean the dataset

Make sure the data has no null value and drop unnecessary columns like temperature anomaly and year.

# Clean the data
df is df.rename(columns={'Year': 'year', 'J-D': 'temperature_anomaly'})

# Remove non-numeric values and convert to float
df = df[df['temperature_anomaly'] != '***']
df['temperature_anomaly'] = pd.to_numeric(df['temperature_anomaly'])

# Select relevant columns and drop NaNs
df = df[['year', 'temperature_anomaly']].dropna()

Visualize the data

After cleaning the data, we can visualize the line graph.

plt.figure(figsize=(10, 6))
sns.lineplot(x='year', y='temperature_anomaly', data=df, marker='o', color='b')
plt.title('Global Temperature Anomalies Over Time')
plt.xlabel('Year')
plt.ylabel('Temperature Anomaly (Ā°C)')
plt.grid(True)
plt.show()

Then here is what we get. I wish it become ā€œa lineā€ but it shows a Fluctuating Graph due to fluctuations of temperature.

Image from author

As we can see here, from 1880, the temperature was still cooler than the reference value and it showed a minus on temperature anomaly. Afterward, the temperature rose regularly and sometimes had fluctuations until it reached the highest temperature in 2024 (which is a positive sign that the temperature is hot) approximately 1.23 Celsius.

Machine learning for predicting

After visualizing, we can start building machine learning to predict future temperatures based on historical data. This is how we can apply ML to climate data prediction.

# Import the libraries
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
import numpy as np

# Prepare the data for modeling
X = df[['year']]
y = df['temperature_anomaly']

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Train the model
model = LinearRegression()
model.fit(X_train, y_train)

# Make predictions
y_pred = model.predict(X_test)

Plot and ready for the result!

Here we will plot the linear regression and from here we know the temperature on our earth in the future!

# Plot the results
plt.figure(figsize=(10, 6))
plt.scatter(X_test, y_test, color='blue', label='Actual')
plt.plot(X_test, y_pred, color='red', linewidth=2, label='Predicted')
plt.title('Actual vs Predicted Temperature Anomalies')
plt.xlabel('Year')
plt.ylabel('Temperature Anomaly (Ā°C)')
plt.legend()
plt.grid(True)
plt.show()

Then it shows like.. this!

Image by author

As you can see here, the model shows that temperature anomalies have continually been increasing, this indicates a continued process of global warming. Machine learning capabilities for predicting climate change are seen in the linear regression forecast closely approximating the actual data.

The final words

Machine learning tools provide ways that help cope with and even change in climate. Ranging from environmental monitoring devices, forecasting tools for future weather conditions up to optimization of renewable energy sources or efficient farming methods using only AI-driven software programs are needed protective measures for our planet. As we move forward with the use of these technologies it becomes absolutely necessary that we invest into extensive studies and systems in place for general use of such AI-based technologies.

--

--

Rifah Maulidya
Adventures in Consumer Technology

A person who is interested in AI, robotics, and CS. Learning 1% lessons everyday for 99% good results in the next days.