Machine Learning (ML) is a branch of artificial intelligence that enables computers to learn from data and make predictions or decisions without being explicitly programmed. Python is a popular language for ML due to its simplicity, vast ecosystem of libraries, and strong community support.
Types of Machine Learning
- Supervised Learning – The model is trained on labeled data (e.g., predicting stock prices based on past trends).
- Unsupervised Learning – The model identifies patterns in unlabeled data (e.g., customer segmentation).
- Reinforcement Learning – The model learns by interacting with an environment and receiving rewards (e.g., training a self-driving car).
Example: Predicting House Prices using Linear Regression
Let’s implement a simple machine learning model using Python and Scikit-Learn.
Step 1: Install Required Libraries
pip install numpy pandas scikit-learn matplotlib
Step 2: Import Required Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error
Step 3: Load Sample Data
We’ll use a simple dataset where square_feet
is the feature (input) and price
is the target (output).
# Sample dataset
data = {
"square_feet": [650, 700, 720, 800, 850, 900, 950, 1000, 1100, 1200],
"price": [70000, 75000, 76000, 85000, 88000, 92000, 98000, 105000, 115000, 125000]
}
df = pd.DataFrame(data)
# Split into features (X) and target (y)
X = df[["square_feet"]]
y = df["price"]
# Split into training and test sets (80% train, 20% test)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
Step 4: Train a Linear Regression Model
# Create and train the model
model = LinearRegression()
model.fit(X_train, y_train)
# Make predictions
y_pred = model.predict(X_test)
Step 5: Evaluate the Model
# Calculate errors
mae = mean_absolute_error(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
print(f"Mean Absolute Error: {mae}")
print(f"Mean Squared Error: {mse}")
Step 6: Visualizing the Results
# Plot training data
plt.scatter(X_train, y_train, color="blue", label="Training Data")
# Plot test data
plt.scatter(X_test, y_test, color="red", label="Test Data")
# Plot regression line
plt.plot(X, model.predict(X), color="green", linestyle="dashed", label="Prediction Line")
plt.xlabel("Square Feet")
plt.ylabel("Price")
plt.legend()
plt.show()
Conclusion
This was a basic introduction to Machine Learning with Python using a Linear Regression model. You can extend this by:
- Using larger datasets
- Experimenting with different ML algorithms
- Applying feature engineering techniques