Predicting Worm Population Using Python
Predicting the population of worms in a garden field can be a quirky yet fun way to dive into predictive modeling using Linear Regression. In this article, we'll explore how to build a model in Python that predicts the worm population based on various factors like soil temperature, moisture levels, and the time of year. Let's jump into it!
1. Importing the Necessary Libraries
First, we need to import the required libraries that will help us handle data, create the model, and evaluate its performance.
# For data manipulation
import pandas as pd
# For numerical operations
import numpy as np
# For splitting data
from sklearn.model_selection import train_test_split
# For Linear Regression model
from sklearn.linear_model import LinearRegression
# For evaluating the model
from sklearn.metrics import mean_squared_error
# For plotting (optional)
import matplotlib.pyplot as plt
2. Creating the Dataset
We'll create a simple dataset where we record the soil temperature, moisture level, and days of the year for a few days, and the worm population observed on those days.
data = {
# Soil temperature in °C
'soil_temperature': [18, 20, 22, 21, 23, 19, 25, 22, 21, 20],
# Moisture level in percentage
'moisture_level': [60, 65, 62, 58, 64, 61, 66, 63, 60, 59],
# Days since the start of the year
'days_since_start': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
# Worm population (target variable)
'worm_population': [120, 130, 140, 125, 135, 110, 150, 145, 130, 120]
}
df = pd.DataFrame(data)
print(df.head()) # Display the first few rows of the dataset
3. Preprocessing the Data
We will now split our data into features (soil temperature, moisture level, and days) and the target variable (worm population). Then, we will divide the data into training and testing sets.
# Features
X = df[['soil_temperature', 'moisture_level', 'days_since_start']]
# Target variable
y = df['worm_population']
# Split the data into training and testing sets (80% training, 20% testing)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print("Training data shape:", X_train.shape)
print("Testing data shape:", X_test.shape)
4. Training the Linear Regression Model
With the data prepared, we can now train a linear regression model. The model will learn the relationship between the features and the target variable (worm population).
model = LinearRegression()
model.fit(X_train, y_train)
print("Model Coefficients:", model.coef_)
print("Model Intercept:", model.intercept_)
5. Making Predictions
After training the model, we can use it to predict the worm population based on the test data.
y_pred = model.predict(X_test)
print("Predicted Worm Populations:", y_pred[:5])
6. Evaluating the Model
We’ll assess the model’s performance using two key metrics:
- Mean Squared Error (MSE): The lower the MSE, the better the model's predictions.
- R² score: R² indicates how well the model fits the data. A value closer to 1 means better predictions.
mse = mean_squared_error(y_test, y_pred)
r2_score = model.score(X_test, y_test)
print(f'Mean Squared Error: {mse}')
print(f'R² Score: {r2_score}')
7. Visualizing the Results
Finally, let's visualize how well the model’s predictions align with the actual worm population values.
plt.scatter(y_test, y_pred)
# Line of perfect prediction
plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], color='red', linestyle='--')
plt.xlabel('Actual Worm Populations')
plt.ylabel('Predicted Worm Populations')
plt.title('Actual vs Predicted Worm Populations')
plt.show()
8. Full Code Summary
Here is the complete code to predict the worm population using linear regression:
# Import libraries
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
# Create a simple dataset
data = {
'soil_temperature': [18, 20, 22, 21, 23, 19, 25, 22, 21, 20],
'moisture_level': [60, 65, 62, 58, 64, 61, 66, 63, 60, 59],
'days_since_start': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'worm_population': [120, 130, 140, 125, 135, 110, 150, 145, 130, 120]
}
df = pd.DataFrame(data)
# Define features and target variable
X = df[['soil_temperature', 'moisture_level', 'days_since_start']]
y = df['worm_population']
# 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)
# Initialize and train the model
model = LinearRegression()
model.fit(X_train, y_train)
# Make predictions
y_pred = model.predict(X_test)
# Evaluate the model
mse = mean_squared_error(y_test, y_pred)
r2_score = model.score(X_test, y_test)
# Visualize results
plt.scatter(y_test, y_pred)
plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], color='red', linestyle='--')
plt.xlabel('Actual Worm Populations')
plt.ylabel('Predicted Worm Populations')
plt.title('Actual vs Predicted Worm Populations')
plt.show()
