Simple example of a Machine Learning (ML) model
- Get link
- X
- Other Apps
Here’s a simple example of a Machine Learning (ML) model using Python and Scikit-Learn to predict house prices using Linear Regression.
π Step 1: Install Required Libraries
If you haven’t installed scikit-learn and pandas, install them first:
bashpip install scikit-learn pandas numpy matplotlib
π Step 2: Import Libraries
python
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: Create Sample Data
python
# Creating a small dataset (house size vs. price)
data = {
"House_Size": [750, 800, 850, 900, 950, 1000, 1050, 1100, 1150, 1200],
"Price": [150000, 160000, 170000, 180000, 190000, 200000, 210000, 220000, 230000, 240000]
}
df = pd.DataFrame(data)
print(df.head()) # Display first few rows
π Step 4: Split Data into Training & Testing Sets
python
X = df[["House_Size"]] # Features (Input)
y = df["Price"] # Target (Output)
# Splitting data into 80% training and 20% testing
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
π Step 5: Train the ML Model (Linear Regression)
python
# Initialize and train the model
model = LinearRegression()
model.fit(X_train, y_train)
# Print model parameters
print(f"Intercept: {model.intercept_}")
print(f"Coefficient: {model.coef_[0]}")
π Step 6: Make Predictions
python
y_pred = model.predict(X_test)
# Display actual vs predicted values
comparison = pd.DataFrame({"Actual": y_test, "Predicted": y_pred})
print(comparison)
π Step 7: Evaluate Model Performance
python
mae = mean_absolute_error(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
print(f"Mean Absolute Error (MAE): {mae}")
print(f"Mean Squared Error (MSE): {mse}")
print(f"Root Mean Squared Error (RMSE): {rmse}")
π Step 8: Visualize the Model
python
plt.scatter(X, y, color="blue", label="Actual Data")
plt.plot(X, model.predict(X), color="red", label="Prediction Line")
plt.xlabel("House Size (sq ft)")
plt.ylabel("Price ($)")
plt.title("House Price Prediction")
plt.legend()
plt.show()
πΉ Expected Output
-
The linear regression model will fit a straight line through the data.
-
It will predict house prices based on their size.
-
You’ll get evaluation metrics like MAE, MSE, RMSE to measure accuracy.
π Want to Try a More Advanced Model?
-
Replace Linear Regression with Decision Trees or Random Forest.
-
Use a larger dataset like Boston Housing Dataset.
-
Deploy the model using Flask or FastAPI.
- Get link
- X
- Other Apps
Comments
Post a Comment