Artificial Intelligence (AI) may sound complex, but with the right tools and mindset, you can start building simple AI projects in just a few lines of Python code. In this blog post, we’ll walk you through building a basic machine learning model using Python’s popular library scikit-learn. This example uses real data and demonstrates how machines can learn patterns and make predictions.

What Will You Build?

We’ll build a simple AI model that can predict a person’s weight based on their height. This is a classic example of linear regression, a basic machine learning algorithm.

Prerequisites

To follow along, make sure you have the following installed:

  • Python 3.x
  • scikit-learn library
  • pandas and matplotlib for data handling and visualization

You can install them using pip:

pip install scikit-learn pandas matplotlib

Step 1: Import Required Libraries

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

Step 2: Prepare the Dataset

We’ll use a small dataset of height and weight.

# Sample data
data = {
'Height': [150, 160, 170, 180, 190],
'Weight': [50, 60, 65, 80, 90]
}

df = pd.DataFrame(data)

Step 3: Visualize the Data

It’s always helpful to visualize your data before training a model.

plt.scatter(df['Height'], df['Weight'], color='blue')
plt.xlabel('Height (cm)')
plt.ylabel('Weight (kg)')
plt.title('Height vs Weight')
plt.show()

Step 4: Train the AI Model

Now, we’ll split the data into features (X) and labels (y), then train the model.

X = df[['Height']]  # Features
y = df['Weight'] # Labels

model = LinearRegression()
model.fit(X, y)

Step 5: Make Predictions

Once trained, the model can make predictions. Let’s predict the weight of someone who is 175 cm tall.

predicted_weight = model.predict([[175]])
print(f"Predicted weight for 175 cm: {predicted_weight[0]:.2f} kg")

Step 6: Visualize the Prediction

We can also visualize the regression line:

plt.scatter(df['Height'], df['Weight'], color='blue')
plt.plot(df['Height'], model.predict(X), color='red') # Regression line
plt.xlabel('Height (cm)')
plt.ylabel('Weight (kg)')
plt.title('Height vs Weight Prediction')
plt.show()

Summary

In this blog post, you built a simple AI model using Python and machine learning. You:

  • Used scikit-learn to create a linear regression model
  • Trained it using real-world-like data
  • Made predictions and visualized the results

This is just the beginning of what you can do with AI. Next, you can try more complex datasets, learn about classification models, or even dive into neural networks.

AI doesn’t have to be intimidating. With just a few lines of code and the right tools, you can start exploring the world of machine learning and artificial intelligence today.

Leave a Reply

Your email address will not be published. Required fields are marked *