I'll create a Python program that demonstrates machine learning using a simple linear regression model for predicting house prices. This example will show the model's learning progress visually.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
class HousePriceLearningDemo:
def __init__(self):
# Generate synthetic house price data
np.random.seed(42)
self.X = np.random.rand(100, 1) * 100 # House size (sq ft)
self.y = 50 * self.X + 20000 + np.random.randn(100, 1) * 5000 # Price with some noise
# Split the data
self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(
self.X, self.y, test_size=0.2, random_state=42
)
# Initialize the model
self.model = LinearRegression()
# Tracking learning progress
self.mse_history = []
self.iterations = []
def train_and_visualize(self, num_iterations=10):
plt.figure(figsize=(15, 5))
for i in range(num_iterations):
# Train the model
self.model.fit(self.X_train[:i+1], self.y_train[:i+1])
# Predict and calculate MSE
y_pred = self.model.predict(self.X_test)
mse = mean_squared_error(self.y_test, y_pred)
# Store learning progress
self.mse_history.append(mse)
self.iterations.append(i+1)
# Visualization
plt.clf()
# Subplot 1: Training Data and Regression Line
plt.subplot(1, 2, 1)
plt.scatter(self.X_train[:i+1], self.y_train[:i+1], color='blue', label='Training Data')
plt.plot(self.X_test, y_pred, color='red', label='Regression Line')
plt.title(f'Iteration {i+1}: House Price Prediction')
plt.xlabel('House Size (sq ft)')
plt.ylabel('Price ($)')
plt.legend()
# Subplot 2: Learning Progress
plt.subplot(1, 2, 2)
plt.plot(self.iterations, self.mse_history, marker='o')
plt.title('Model Learning Progress')
plt.xlabel('Number of Training Samples')
plt.ylabel('Mean Squared Error')
plt.tight_layout()
plt.pause(0.5)
plt.show()
def print_final_model_details(self):
print("\nFinal Model Details:")
print(f"Coefficient (Price per sq ft): ${self.model.coef_[0][0]:.2f}")
print(f"Intercept (Base Price): ${self.model.intercept_[0]:.2f}")
print(f"Final Mean Squared Error: {self.mse_history[-1]:.2f}")
def main():
print("House Price Prediction Machine Learning Demo")
demo = HousePriceLearningDemo()
demo.train_and_visualize(num_iterations=20)
demo.print_final_model_details()
if __name__ == "__main__":
main()
This program demonstrates machine learning through a house price prediction model with the following features:
- Data Generation: Creates synthetic house price data based on house size
- Machine Learning Model: Uses Linear Regression
- Visualization:
- Left subplot shows training data and regression line
- Right subplot shows learning progress (Mean Squared Error reduction)
- Interactive Learning: Shows model improvement with each iteration
- Final Model Details: Prints coefficient, intercept, and final error
When you run this program, you'll see:
- A dynamic visualization of the model learning
- How the regression line adapts
- How the Mean Squared Error decreases
Key machine learning concepts demonstrated:
- Model training
- Prediction
- Error measurement
- Iterative improvement
Requirements:
- NumPy
- Matplotlib
- Scikit-learn
Enjoy watching your machine learning model learn and improve in real-time!