Simple example of a Machine Learning (ML) model

 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:

bash

pip 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.

Comments

Popular posts from this blog

AI principles and methodologies

What Chatgpt can do for me