In the previous blog, we discovered how Machine Learning works by finding a relationship between:
- 📚 Hours Studied (H)
- 🎯 Marks (M)
M = 9H + 1
Now it’s time to bring this model to life using Python programming 🐍
🚀 Step 1: Creating the Dataset in Python
# Hours studied (Input) H = [1, 2, 3, 4, 5] # Marks obtained (Output) M = [10, 19, 28, 37, 46]
📌 This is the same dataset we used earlier.
📊 Step 2: Visualizing the Data (Graph)
import matplotlib.pyplot as plt
plt.scatter(H, M)
plt.xlabel("Hours Studied")
plt.ylabel("Marks Obtained")
plt.title("Study Hours vs Marks")
plt.show()
✨ You will observe a straight-line pattern, confirming a linear relationship.
🧮 Step 3: Calculating a and b using Python
# Using two points
x1, y1 = 1, 10
x2, y2 = 2, 19
# Calculate slope (a)
a = (y2 - y1) / (x2 - x1)
# Calculate intercept (b)
b = y1 - a * x1
print("Value of a:", a)
print("Value of b:", b)
Value of a: 9.0 Value of b: 1.0
✅ Step 4: Building the Model
def predict_marks(H):
return 9 * H + 1
🔮 Step 5: Making Predictions
hours = 6
predicted_marks = predict_marks(hours)
print("Predicted Marks:", predicted_marks)
Predicted Marks: 55
📈 Step 6: Plotting the Best Fit Line
predicted = [predict_marks(h) for h in H]
plt.scatter(H, M, label="Actual Data")
plt.plot(H, predicted, label="Model Line")
plt.xlabel("Hours Studied")
plt.ylabel("Marks")
plt.legend()
plt.show()
✨ You will see:
- Dots → Actual data
- Line → Machine Learning model
🤖 Step 7: Connecting to Machine Learning
| Concept | Python Implementation |
|---|---|
| Dataset | Lists (H, M) |
| Model | Function |
| Training | Calculating a & b |
| Prediction | Function Output |
💡 Real Machine Learning Extension
from sklearn.linear_model import LinearRegression
import numpy as np
H = np.array([1,2,3,4,5]).reshape(-1,1)
M = np.array([10,19,28,37,46])
model = LinearRegression()
model.fit(H, M)
print("Slope:", model.coef_[0])
print("Intercept:", model.intercept_)
🎯 Conclusion
You just built your first Machine Learning model in Python! 🎉
- ✔ Took data
- ✔ Found relationship
- ✔ Converted into code
- ✔ Made predictions
This is the foundation of:
- 🤖 Artificial Intelligence
- 📊 Data Science
- 🔮 Predictive Systems
📝 Practice for Students
- Predict marks for 7 and 8 hours
- Modify dataset values
- Create your own graph
🔗 Related Blog
📊 Machine Learning with Polynomials: From Data to Prediction
Understand the fundamentals of Machine Learning by learning how we derived the equation M = 9H + 1 using tabular data, graph visualization, and mathematical modeling.
👉 Read Previous Blog