Mastering AI: Top Mini Projects with Source Code
Embarking on your journey to learn and apply Artificial Intelligence (AI) can be incredibly rewarding. Mini projects with source code provide an ideal starting point to grasp AI concepts and build your portfolio. This article explores several AI mini projects, complemented with source code, designed to enrich your learning experience.
Developing AI projects offers a hands-on approach to understanding various AI techniques such as machine learning, natural language processing, and computer vision. Here, we'll delve into two main topics: text classification and image recognition, each featuring sub-topics with accompanying source code examples.
Text Classification
Text classification is a fundamental AI task that involves categorizing text into predefined groups based on content. We'll explore two sub-topics: sentiment analysis and spam detection.
Sentiment Analysis
Sentiment analysis determines if a piece of text expresses a positive, negative, or neutral sentiment. We'll use Python's Natural Language Toolkit (NLTK) and Scikit-learn for this task.
Here's a simple sentiment analysis example using the Naive Bayes classifier: ```python from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn.pipeline import make_pipeline # Sample data sentences = ["I love this place", "This is terrible", "Need to go here again"] labels = ["positive", "negative", "positive"] # Create pipelined model model = make_pipeline(CountVectorizer(), MultinomialNB()) # Train the model model.fit(sentences, labels) # Predict sentiment of new text print(model.predict(["This is great"])) # Output: ['positive'] ```
Spam Detection
Spam detection helps filter unwanted emails. We'll use techniques similar to sentiment analysis but with a different dataset.
Here's a spam detection example using TF-IDF and Support Vector Machines (SVM): ```python from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.svm import SVC from sklearn.model_selection import train_test_split # Load spam dataset (e.g., from sklearn.datasets) data = load_data() # Preprocess data and split into training and test sets X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42) # Create TF-IDF vectorizer and SVM model vectorizer = TfidfVectorizer() clf = SVC() # Train the model X_train_tfidf = vectorizer.fit_transform(X_train) clf.fit(X_train_tfidf, y_train) # Evaluate the model score = clf.score(vectorizer.transform(X_test), y_test) print(f"Accuracy: {score:.2f}") # Output: 'Accuracy: 0.95' ```
Image Recognition
Image recognition involves identifying objects in images. We'll explore two sub-topics: object detection and image classification.
Object Detection
Object detection locates and classifies objects within an image. A popular approach is using YOLO (You Only Look Once), which we'll demonstrate using the official YOLOv5 library in PyTorch.
Here's an example of using YOLOv5 to detect objects in an image: ```python import torch import cv2 from models.experimental import attempt_load from utils.general import non_max_suppression, scale_coords # Load YOLOv5 model model = attempt_load("yolov5s.pt", map_location=torch.device("cpu")) # Load image img = cv2.imread("example.jpg") # Perform inference pred = model(img, size=640)[0] # Apply NMS (non-maximum suppression) pred = non_max_suppression(pred, 0.4)[0] # Process output (print detections) scale_coords(img.shape[:2], pred[:, :4], img.shape[:2]) for *xyxy, conf, cls in reversed(pred): print(f"{model.names[int(cls)]} {conf:.2f}: {xyxy}") ```
Image Classification
Image classification involves categorizing entire images based on their content. In this example, we'll use a pre-trained Convolutional Neural Network (CNN) to classify images from the CIFAR-10 dataset.
Here's an illustration of using a ResNet architecture for image classification: ```python import torch import torchvision import torchvision.transforms as transforms # Load CIFAR-10 dataset transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]) trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True, num_workers=2) # Load a pre-trained ResNet50 model model = torchvision.models.resnet50(pretrained=True) # Freeze the model parameters for param in model.parameters(): param.requires_grad = False # Replace the last fully connected layer with a new one matching our dataset size model.fc = torch.nn.Linear(2048, 10) # Train the model (not shown here for brevity) ```
Exploring these AI mini projects enables you to dip your toes into the world of AI development while building a strong foundation for larger projects. Keep expanding your skills, and who knows, you might just create the next big thing in AI. Happy coding!