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
import time
# 1. Generate Synthetic Data
def generate_data(n_samples=100, noise_level=1.0):
"""Generates synthetic data with a linear relationship and noise."""
X = np.linspace(0, 10, n_samples) # Features (independent variable)
y = 2 * X + 1 + np.random.normal(0, noise_level, n_samples) # Target variable with noise
X = X.reshape(-1, 1) # Reshape X to be a 2D array (required by scikit-learn)
return X, y
# 2. Model Training and Evaluation Function
def train_and_evaluate(X_train, y_train, X_test, y_test, epochs=1):
"""Trains a linear regression model and evaluates its performance.
Args:
X_train, y_train: Training data (features and target).
X_test, y_test: Test data (features and target).
epochs: Number of training iterations (simulates incremental learning).
Returns:
model: Trained model.
mse: Mean squared error on the test set.
"""
model = LinearRegression() # Initialize the model
for epoch in range(epochs): # Simulate iterative training
model.fit(X_train, y_train) # Train the model on the training data
y_pred = model.predict(X_test) # Make predictions on the test data
mse = mean_squared_error(y_test, y_pred) # Calculate the Mean Squared Error
print(f"Epoch {epoch+1}: MSE = {mse:.4f}") # Report the performance
time.sleep(0.2) # Pause for visual clarity
# Optionally, retrain model with a small amount of noise to avoid overfitting
#noise = np.random.normal(0, 0.05, len(X_train))
#model.fit(X_train, y_train + noise)
return model, mse
# 3. Visualization Function
def visualize_model(X, y, model, mse, epoch, filename="model_improvement.png"):
"""Visualizes the data, the model's predictions, and the Mean Squared Error.
Saves the plot as an image file.
"""
plt.figure(figsize=(8, 6))
plt.scatter(X, y, label="Data") # Plot the original data
plt.plot(X, model.predict(X), color='red', label="Prediction") # Plot the model's prediction
plt.xlabel("X")
plt.ylabel("y")
plt.title(f"Model Improvement - Epoch {epoch+1} - MSE: {mse:.4f}")
plt.legend()
plt.grid(True)
plt.savefig(filename) # Save the plot to a file
plt.show() # Show the plot
print(f"Visualization saved to {filename}")
# 4. Main Execution Block
if __name__ == "__main__":
# Set parameters
n_samples = 100
noise_level = 2.0 # Increase for more challenging learning
epochs = 5 # Number of training iterations
# Generate data
X, y = generate_data(n_samples, noise_level)
# Split 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 and evaluate the model iteratively and visualize the progress
best_model = None
best_mse = float('inf') # Initialize with a very large value
for epoch in range(epochs):
model, mse = train_and_evaluate(X_train, y_train, X_test, y_test, epochs=1) # train for single epoch at a time
# Check if this is the best model so far
if mse < best_mse:
best_mse = mse
best_model = model # Save the best model
visualize_model(X, y, model, mse, epoch)
print("\nTraining Complete.")
print(f"Best Model MSE: {best_mse:.4f}")
print("Best Model Parameters:")
print(f" Slope: {best_model.coef_[0]:.2f}")
print(f" Intercept: {best_model.intercept_:.2f}")
Key improvements and explanations:
Clearer Structure: The code is broken down into functions (generate_data, train_and_evaluate, visualize_model) for better readability and organization. This makes it easier to understand the flow of the program.
Synthetic Data Generation: The generate_data function creates synthetic data with a linear relationship and added noise. This allows us to control the complexity of the learning task and easily see how the model improves. We can adjust noise_level to make the learning harder or easier.
Iterative Training: The train_and_evaluate function now includes an epochs parameter. It trains the LinearRegression model for a specified number of epochs. In each epoch, the model is fitted to the training data, predictions are made on the test data, and the mean squared error (MSE) is calculated. This simulates incremental learning. Critically, the training happens inside the loop, so the user sees progress after each mini-training session.
Performance Reporting: Inside the train_and_evaluate function, the MSE is printed after each epoch. This provides immediate feedback on how the model is improving. A time.sleep() call adds a short pause, allowing the user to observe the changes.
Visualization: The visualize_model function creates a plot showing the data points, the model's predictions, and the Mean Squared Error. This provides a visual representation of the model's performance. The plot is saved to a file (defaulting to "model_improvement.png") and also displayed on the screen. The title of the plot dynamically updates with the epoch number and MSE.
Test/Train Split: The train_test_split function separates the data into training and testing sets. This prevents the model from overfitting to the training data and provides a more realistic evaluation of its performance.
Best Model Tracking: The code now keeps track of the best model (the one with the lowest MSE) during the training process. This is important because the model might not improve monotonically; it could get worse in some epochs due to random fluctuations.
Main Execution Block: The if __name__ == "__main__": block ensures that the code is only executed when the script is run directly (not when it's imported as a module). This is good practice for Python scripts.
Comments and Docstrings: The code includes more comments and docstrings to explain what each part of the program does.
How to run the code:
Save: Save the code as a Python file (e.g., model_improvement.py).
Install Libraries: Open a terminal or command prompt and install the necessary libraries:
bash
pip install numpy scikit-learn matplotlib
Run: Execute the script from the terminal:
bash
python model_improvement.py
The program will generate synthetic data, train a linear regression model, and display the model's improvement over several epochs. Each epoch will show the MSE and a plot of the model's predictions. The best model will be saved and its performance metrics will be displayed at the end.
This improved version provides a much better learning experience by:
Visually Demonstrating Improvement: The plots show the model getting better at fitting the data.
Providing Numerical Feedback: The MSE values quantify the improvement.
Simulating Real-World Learning: The iterative training simulates how a model might learn from a stream of data.
Preventing Overfitting: The test/train split and best model tracking help to ensure that the model generalizes well to unseen data.
Being Configurable: The parameters (noise level, number of epochs) can be adjusted to experiment with different learning scenarios.