I’ll create a machine learning example using $Python$ to demonstrate linear regression on a simple dataset, then visualize the results.
1 | import numpy as np |
Let me explain this example step by step:
Data Generation:
- We create synthetic data with a known relationship: $y = 4 + 3x + noise$
- $100$ data points are generated with random noise added
- The true relationship has an intercept of $4$ and a slope of $3$
Data Splitting:
- The data is split into training ($80$%) and testing ($20$%) sets
- This helps us evaluate how well our model generalizes to new data
Model Training:
- We use scikit-learn’s LinearRegression model
- The model learns the relationship between $X$ and $y$ from the training data
Results Analysis:
- The model finds the intercept and slope that best fit the data
- R-squared score shows how well the model fits the test data
- A score close to $1.0$ indicates a good fit
Visualization:
- Blue dots: Training data points
- Green dots: Testing data points
- Red line: The predicted relationship found by the model
- The grid helps see how well the line fits the data
When you run this code, you’ll see:
- The model parameters (intercept and slope) should be close to the true values ($4$ and $3$)
- The R-squared score should be relatively high (> $0.8$)
- The visualization will show how well the linear regression line fits the data points
Intercept: 4.14 Slope: 2.80 R-squared score: 0.81

This is a basic example of supervised learning where we:
- Generate data with a known pattern
- Train a model to discover that pattern
- Evaluate how well the model learned
- Visualize the results









