You Won't Believe How Easy It Is to Build a Classifier with Python!

Create a Smart Fruit Classifier Now

Fruit Classifier

Fun with Machine Learning and Object-Oriented ProgrammingπŸ§ πŸ’»

 

Today, we're combining the power of machine learning with the elegance of object-oriented programming (OOP) to create a fun and interesting project for beginners. Get ready to build a "Smart Fruit Classifier" 🍏🍊🍌 that identifies different types of fruits based on their characteristics.

Sponsored
Connecting Dots@dharmesh on startups, scaleups and strategy

Why OOP in Machine Learning?

 

OOP helps in organizing your code better, making it reusable and easier to understand. Plus, it makes you feel like a wizard with the ability to create your own magical classes and objects! πŸ§™β€β™‚οΈβœ¨

 

Project: Smart Fruit Classifier

What is a Classifier?

A classifier is a type of machine learning model that is trained to categorize data into specific classes or categories. For example, given data about fruits, a classifier can learn to distinguish between apples, bananas, cherries, and other types of fruits based on their features like weight, color, and size. By learning from a labeled dataset, the classifier can make predictions about new, unseen data, determining which category it belongs to with a certain level of accuracy. In essence, classifiers help us automate the process of identifying and labeling data, making them essential tools in many applications, from spam detection in emails to recognizing objects in images

Objective:

Build a classifier that identifies fruits based on their features (weight, color, and size).

 

Tools:

  • Python 🐍

  • OOP πŸ‘¨β€πŸ’»

  • scikit-learn πŸ“Š

 

Step 1: Setting Up the Project

 

First, let's import the necessary libraries and define our fruit class.

 

import numpy as np

from sklearn.model_selection import train_test_split

from sklearn.tree import DecisionTreeClassifier

from sklearn.metrics import accuracy_score

 

class Fruit:

    def init(self, weight, color, size, label):

        self.weight = weight  # Weight in grams (g)

        self.color = color  # Color: Red=1, Green=2, Yellow=3

        self.size = size  # Size: Small=1, Medium=2, Large=3

        self.label = label

 

    def features(self):

        return [self.weight, self.color, self.size]

 

Step 2: Creating Some Fruit Objects

 

Let’s create a few fruit objects. Imagine yourself in a fruit market, picking the best fruits for your classifier! πŸπŸŒπŸ’

 

fruits = [

    Fruit(150, 1, 3, 'Apple'),

    Fruit(120, 3, 2, 'Banana'),

    Fruit(10, 1, 1, 'Cherry'),

    Fruit(5, 2, 1, 'Grape'),

    Fruit(180, 2, 3, 'Pear'),

    Fruit(140, 1, 3, 'Apple'),

    Fruit(130, 3, 2, 'Banana'),

    Fruit(12, 1, 1, 'Cherry'),

    Fruit(7, 2, 1, 'Grape'),

    Fruit(160, 2, 3, 'Pear'),

    Fruit(155, 1, 3, 'Apple'),

    Fruit(125, 3, 2, 'Banana'),

    Fruit(11, 1, 1, 'Cherry'),

    Fruit(6, 2, 1, 'Grape'),

    Fruit(170, 2, 3, 'Pear')

]

 

Step 3: Preparing the Dataset

 

We need to convert our fruit objects into a dataset that scikit-learn can understand.

 

X = np.array([fruit.features() for fruit in fruits])

y = np.array([fruit.label for fruit in fruits])

 

# Splitting the dataset into training and testing sets

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

 

# Printing the training and testing data

print("Training Data:")

print(X_train)

print(y_train)

 

print("\nTesting Data:")

print(X_test)

print(y_test)

 

Step 4: Building and Training the Classifier

 

Time to build our decision tree classifier. Think of it as the wise old tree in your backyard that knows all the secrets of your fruits. πŸŒ³πŸ”

 

class FruitClassifier:

    def init(self):

        self.model = DecisionTreeClassifier()

 

    def train(self, X_train, y_train):

        self.model.fit(X_train, y_train)

 

    def predict(self, X_test):

        return self.model.predict(X_test)

 

# Creating an instance of FruitClassifier

fruit_classifier = FruitClassifier()

fruit_classifier.train(X_train, y_train)

 

Step 5: Making Predictions and Evaluating

 

Let’s see how well our classifier performs. Fingers crossed! 🀞

 

predictions = fruit_classifier.predict(X_test)

accuracy = accuracy_score(y_test, predictions)

 

print(f"\nPredicted results: {predictions}")print(f"\nPredicted results: {predictions}")

print(f"Accuracy: {accuracy * 100:.2f}%")

Output

Sample Testing Data 1

Sample Testing Data 2

Conclusion

Congratulations! πŸŽ‰ You've successfully built a smart fruit classifier using the principles of object-oriented programming and machine learning. In this project, you learned how to:

1. Organize Data with OOP: By creating a Fruit class, you effectively organized fruit data, making it easier to manage and expand.

2. Prepare and Split Data: You transformed your fruit objects into a dataset suitable for machine learning and split it into training and testing sets.

3. Build and Train a Model: Using a decision tree classifier, you trained a model to recognize different types of fruits based on their features.

4. Evaluate Model Performance: You assessed the accuracy of your classifier, understanding the importance of having a diverse and sufficient dataset.

This project not only introduced you to the basics of machine learning but also demonstrated the power of combining it with object-oriented programming to create reusable and scalable code.

Weekly Challenge

Create your own classifier for another set of objects. It could be anythingβ€”vehicles, animals, or even types of pizza! πŸ•πŸš—πŸΆ 

Let's learn and laugh together!

Sponsored
Connecting Dots@dharmesh on startups, scaleups and strategy

Coding with a Smile

Indentation Matters: Python's strict indentation rules are like a well-choreographed dance. Miss a step, and the whole routine falls apart. Who knew that an extra space could lead to such drama? It's like performing ballet with a chainsawβ€”precision is key!

Ready for More Python Fun? πŸ“¬

Subscribe to our newsletter now and get a free Python cheat sheet! πŸ“‘ Dive deeper into Python programming with more exciting projects and tutorials designed just for beginners.

Keep exploring, keep coding, πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»and enjoy your journey into artificial intelligence, machine learning, data analytics, data science and more with Python!

Stay tuned for our next exciting project in the following edition!

Happy coding!πŸš€πŸ“Šβœ¨