From 9ed64cba457b5bee5874fd73ac00992750f71e60 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 3 Oct 2025 10:15:08 +0000 Subject: [PATCH] Add beginner-friendly examples with detailed comments Co-authored-by: leestott <2511341+leestott@users.noreply.github.com> --- README.md | 13 + examples/01-hello-ai-world.py | 138 ++++++++++ examples/02-simple-neural-network.py | 259 ++++++++++++++++++ examples/03-image-classifier.ipynb | 384 +++++++++++++++++++++++++++ examples/04-text-sentiment.py | 268 +++++++++++++++++++ examples/README.md | 80 ++++++ 6 files changed, 1142 insertions(+) create mode 100644 examples/01-hello-ai-world.py create mode 100644 examples/02-simple-neural-network.py create mode 100644 examples/03-image-classifier.ipynb create mode 100644 examples/04-text-sentiment.py create mode 100644 examples/README.md diff --git a/README.md b/README.md index 41623b3a..b4c62d00 100644 --- a/README.md +++ b/README.md @@ -104,6 +104,19 @@ For a gentle introduction to _AI in the Cloud_ topics you may consider taking th ## Getting Started +### ๐ŸŽฏ New to AI? Start Here! + +If you're completely new to AI and want quick, hands-on examples, check out our [**Beginner-Friendly Examples**](./examples/README.md)! These include: + +- ๐ŸŒŸ **Hello AI World** - Your first AI program (pattern recognition) +- ๐Ÿง  **Simple Neural Network** - Build a neural network from scratch +- ๐Ÿ–ผ๏ธ **Image Classifier** - Classify images with detailed comments +- ๐Ÿ’ฌ **Text Sentiment** - Analyze positive/negative text + +These examples are designed to help you understand AI concepts before diving into the full curriculum. + +### ๐Ÿ“š Full Curriculum Setup + - We have created a [setup lesson](./lessons/0-course-setup/setup.md) to help you with setting up your development environment. - For Educators, we have created a [curricula setup lesson](./lessons/0-course-setup/for-teachers.md) for you too! - How to [Run the code in a VSCode or a Codepace](./lessons/0-course-setup/how-to-run.md) diff --git a/examples/01-hello-ai-world.py b/examples/01-hello-ai-world.py new file mode 100644 index 00000000..88ea5b1b --- /dev/null +++ b/examples/01-hello-ai-world.py @@ -0,0 +1,138 @@ +""" +Hello AI World - Your First AI Program +======================================= + +This is a simple pattern recognition example that demonstrates core AI concepts: +- Learning from data +- Making predictions +- Understanding patterns + +What this program does: +- Learns a simple mathematical pattern (y = 2x) +- Uses that pattern to make predictions +- No complex libraries needed - just pure Python! + +Perfect for understanding AI basics before diving into neural networks. +""" + +import random + +class SimpleAILearner: + """ + A very simple AI that learns linear relationships. + This demonstrates the fundamental concept of AI: learning from data. + """ + + def __init__(self): + # The "weight" is what our AI learns + # It starts with a random guess + self.weight = random.uniform(0, 5) + self.learning_rate = 0.01 # How fast our AI learns + + def predict(self, x): + """ + Make a prediction based on what we've learned. + + Args: + x: Input value + + Returns: + Predicted output + """ + return self.weight * x + + def train(self, training_data, epochs=100): + """ + Train the AI to learn the pattern in the data. + + Args: + training_data: List of (input, output) pairs + epochs: Number of times to go through all the data + """ + print("๐ŸŽ“ Training started...") + print(f"Initial guess for weight: {self.weight:.2f}") + + for epoch in range(epochs): + total_error = 0 + + # Learn from each example + for x, y_actual in training_data: + # Make a prediction + y_predicted = self.predict(x) + + # Calculate error (how wrong we were) + error = y_actual - y_predicted + total_error += abs(error) + + # Update our weight to reduce error (this is learning!) + self.weight += self.learning_rate * error * x + + # Print progress every 20 epochs + if (epoch + 1) % 20 == 0: + avg_error = total_error / len(training_data) + print(f"Epoch {epoch + 1}/{epochs} - Average error: {avg_error:.4f} - Weight: {self.weight:.2f}") + + print(f"โœ… Training complete! Final weight: {self.weight:.2f}") + + +def main(): + """ + Main function - Let's teach our AI! + """ + print("=" * 60) + print("Welcome to Hello AI World!") + print("=" * 60) + print() + print("Today, we'll teach an AI to learn a simple pattern:") + print("Given x, predict y where y = 2x") + print() + + # Step 1: Create training data + # The pattern we want the AI to learn: y = 2 * x + print("๐Ÿ“Š Creating training data...") + training_data = [ + (1, 2), # When x=1, y should be 2 + (2, 4), # When x=2, y should be 4 + (3, 6), # When x=3, y should be 6 + (4, 8), # When x=4, y should be 8 + (5, 10), # When x=5, y should be 10 + ] + print(f"Training examples: {training_data}") + print() + + # Step 2: Create and train our AI + ai = SimpleAILearner() + ai.train(training_data, epochs=100) + print() + + # Step 3: Test our AI with new data + print("๐Ÿงช Testing our AI with new inputs...") + print("-" * 60) + test_inputs = [6, 7, 10, 15] + + for x in test_inputs: + prediction = ai.predict(x) + actual = 2 * x # The true answer + print(f"Input: {x:2d} | Prediction: {prediction:6.2f} | Actual: {actual:6.2f} | Difference: {abs(prediction - actual):.2f}") + + print("-" * 60) + print() + + # Explanation + print("๐Ÿ’ก What just happened?") + print("1. We gave the AI examples of the pattern (y = 2x)") + print("2. The AI learned by adjusting its 'weight' to minimize errors") + print("3. After training, it can predict outputs for new inputs!") + print() + print("๐ŸŽ‰ Congratulations! You just trained your first AI!") + print() + print("๐Ÿš€ Next steps:") + print(" - Try changing the training data to learn different patterns") + print(" - Experiment with the learning_rate (line 29)") + print(" - Modify epochs to see how training time affects accuracy") + print() + + +if __name__ == "__main__": + # This runs when you execute the script + main() diff --git a/examples/02-simple-neural-network.py b/examples/02-simple-neural-network.py new file mode 100644 index 00000000..95c5c0ef --- /dev/null +++ b/examples/02-simple-neural-network.py @@ -0,0 +1,259 @@ +""" +Simple Neural Network from Scratch +=================================== + +This example builds a basic neural network without using any ML frameworks. +It helps you understand what's happening "under the hood" in neural networks. + +What you'll learn: +- How neurons work +- Forward propagation (making predictions) +- Backward propagation (learning from mistakes) +- The sigmoid activation function + +Use case: Learn to classify points as "above" or "below" a line. +""" + +import random +import math + +def sigmoid(x): + """ + Sigmoid activation function: converts any value to a number between 0 and 1. + + This is like asking "how confident are we?" + - Values close to 1 mean "very confident YES" + - Values close to 0 mean "very confident NO" + - Values around 0.5 mean "not sure" + + Args: + x: Input value + + Returns: + Value between 0 and 1 + """ + # Prevent overflow for very large/small numbers + if x > 100: + return 1.0 + if x < -100: + return 0.0 + return 1 / (1 + math.exp(-x)) + + +def sigmoid_derivative(x): + """ + Derivative of sigmoid function - needed for learning. + This tells us how much to adjust our weights. + + Args: + x: Sigmoid output value + + Returns: + Derivative value + """ + return x * (1 - x) + + +class SimpleNeuron: + """ + A single artificial neuron - the building block of neural networks. + + Think of it as a tiny decision maker that: + 1. Takes inputs (like features of data) + 2. Multiplies them by learned weights + 3. Adds them up with a bias + 4. Applies an activation function + 5. Outputs a prediction + """ + + def __init__(self, num_inputs): + """ + Initialize the neuron with random weights. + + Args: + num_inputs: Number of input values this neuron will receive + """ + # Each input gets a weight (how important is this input?) + self.weights = [random.uniform(-1, 1) for _ in range(num_inputs)] + # Bias helps adjust the output + self.bias = random.uniform(-1, 1) + # Store the last output for learning + self.output = 0 + + def feedforward(self, inputs): + """ + Calculate the neuron's output (prediction). + This is called "forward propagation". + + Args: + inputs: List of input values + + Returns: + Neuron's output (between 0 and 1) + """ + # Step 1: Multiply each input by its weight and sum them + total = sum(w * x for w, x in zip(self.weights, inputs)) + + # Step 2: Add bias + total += self.bias + + # Step 3: Apply activation function (sigmoid) + self.output = sigmoid(total) + + return self.output + + def train(self, inputs, target, learning_rate=0.1): + """ + Teach the neuron to improve its predictions. + This is called "backpropagation". + + Args: + inputs: The input values + target: What the output should have been + learning_rate: How much to adjust weights + """ + # Calculate error + error = target - self.output + + # Calculate adjustment amount using derivative + delta = error * sigmoid_derivative(self.output) + + # Update weights + for i in range(len(self.weights)): + self.weights[i] += learning_rate * delta * inputs[i] + + # Update bias + self.bias += learning_rate * delta + + return abs(error) + + +def generate_training_data(num_samples=100): + """ + Generate sample data for training. + + Task: Classify points as above (1) or below (0) the line y = x. + + Args: + num_samples: How many training examples to create + + Returns: + List of (inputs, target) tuples + """ + data = [] + for _ in range(num_samples): + # Random point in 2D space (x, y coordinates) + x = random.uniform(0, 10) + y = random.uniform(0, 10) + + # Label: 1 if point is above the line y=x, 0 if below + label = 1 if y > x else 0 + + data.append(([x, y], label)) + + return data + + +def visualize_decision(neuron, test_points): + """ + Show how the neuron classifies different points. + + Args: + neuron: Trained neuron + test_points: List of points to test + """ + print("\n๐ŸŽฏ Testing the trained neuron:") + print("-" * 70) + print(f"{'Point':<15} | {'Prediction':<15} | {'Actual':<15} | {'Correct?'}") + print("-" * 70) + + correct = 0 + for point, actual in test_points: + prediction = neuron.feedforward(point) + predicted_class = 1 if prediction > 0.5 else 0 + actual_class = actual + is_correct = "โœ“" if predicted_class == actual_class else "โœ—" + + if predicted_class == actual_class: + correct += 1 + + print(f"({point[0]:5.2f}, {point[1]:5.2f}) | {prediction:14.4f} | {actual_class:^15} | {is_correct}") + + print("-" * 70) + accuracy = (correct / len(test_points)) * 100 + print(f"Accuracy: {accuracy:.1f}% ({correct}/{len(test_points)} correct)") + + +def main(): + """ + Main function - Build and train a neural network! + """ + print("=" * 70) + print("Simple Neural Network from Scratch") + print("=" * 70) + print("\n๐Ÿ“š Task: Learn to classify points as above or below the line y = x") + print() + + # Step 1: Generate training data + print("๐Ÿ“Š Generating training data...") + training_data = generate_training_data(num_samples=100) + print(f"Created {len(training_data)} training examples") + + # Show a few examples + print("\nExample training data:") + for i in range(3): + point, label = training_data[i] + position = "above" if label == 1 else "below" + print(f" Point ({point[0]:.2f}, {point[1]:.2f}) is {position} the line y=x") + + # Step 2: Create neuron + print("\n๐Ÿง  Creating a neuron with 2 inputs (x and y coordinates)...") + neuron = SimpleNeuron(num_inputs=2) + print(f"Initial weights: [{neuron.weights[0]:.3f}, {neuron.weights[1]:.3f}]") + print(f"Initial bias: {neuron.bias:.3f}") + + # Step 3: Train the neuron + print("\n๐ŸŽ“ Training the neuron...") + epochs = 50 + + for epoch in range(epochs): + total_error = 0 + + # Train on each example + for inputs, target in training_data: + neuron.feedforward(inputs) + error = neuron.train(inputs, target, learning_rate=0.1) + total_error += error + + # Show progress + if (epoch + 1) % 10 == 0: + avg_error = total_error / len(training_data) + print(f"Epoch {epoch + 1}/{epochs} - Average error: {avg_error:.4f}") + + print("\nโœ… Training complete!") + print(f"Final weights: [{neuron.weights[0]:.3f}, {neuron.weights[1]:.3f}]") + print(f"Final bias: {neuron.bias:.3f}") + + # Step 4: Test the neuron + test_data = generate_training_data(num_samples=10) + visualize_decision(neuron, test_data) + + # Explanation + print("\n๐Ÿ’ก What just happened?") + print("1. The neuron started with random weights") + print("2. It looked at 100 example points and their correct labels") + print("3. Each time it was wrong, it adjusted its weights slightly") + print("4. After 50 rounds, it learned to classify points correctly!") + print() + print("๐ŸŽ‰ You just built a neural network from scratch!") + print() + print("๐Ÿš€ Try this:") + print(" - Change num_samples to train on more/fewer examples") + print(" - Modify epochs to train for longer/shorter") + print(" - Change learning_rate (line 185) and see what happens") + print(" - Try different decision boundaries (modify generate_training_data)") + print() + + +if __name__ == "__main__": + main() diff --git a/examples/03-image-classifier.ipynb b/examples/03-image-classifier.ipynb new file mode 100644 index 00000000..866f62f8 --- /dev/null +++ b/examples/03-image-classifier.ipynb @@ -0,0 +1,384 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Simple Image Classifier\n", + "\n", + "This notebook shows you how to classify images using a pre-trained neural network.\n", + "\n", + "**What you'll learn:**\n", + "- How to load and use a pre-trained model\n", + "- Image preprocessing\n", + "- Making predictions on images\n", + "- Understanding confidence scores\n", + "\n", + "**Use case:** Identify objects in images (like \"cat\", \"dog\", \"car\", etc.)\n", + "\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Step 1: Import Required Libraries\n", + "\n", + "Let's import the tools we need. Don't worry if you don't understand all of these yet!" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Core libraries\n", + "import numpy as np\n", + "from PIL import Image\n", + "import requests\n", + "from io import BytesIO\n", + "\n", + "# TensorFlow for deep learning\n", + "try:\n", + " import tensorflow as tf\n", + " from tensorflow.keras.applications import MobileNetV2\n", + " from tensorflow.keras.applications.mobilenet_v2 import preprocess_input, decode_predictions\n", + " print(\"โœ… TensorFlow loaded successfully!\")\n", + " print(f\" Version: {tf.__version__}\")\n", + "except ImportError:\n", + " print(\"โŒ Please install TensorFlow: pip install tensorflow\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Step 2: Load Pre-trained Model\n", + "\n", + "We'll use **MobileNetV2**, a neural network already trained on millions of images.\n", + "\n", + "This is called **Transfer Learning** - using a model someone else trained!" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print(\"๐Ÿ“ฆ Loading pre-trained MobileNetV2 model...\")\n", + "print(\" This may take a minute on first run (downloading weights)...\")\n", + "\n", + "# Load the model\n", + "# include_top=True means we use the classification layer\n", + "# weights='imagenet' means it was trained on ImageNet dataset\n", + "model = MobileNetV2(weights='imagenet', include_top=True)\n", + "\n", + "print(\"โœ… Model loaded!\")\n", + "print(f\" The model can recognize 1000 different object categories\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Step 3: Helper Functions\n", + "\n", + "Let's create functions to load and prepare images for our model." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def load_image_from_url(url):\n", + " \"\"\"\n", + " Load an image from a URL.\n", + " \n", + " Args:\n", + " url: Web address of the image\n", + " \n", + " Returns:\n", + " PIL Image object\n", + " \"\"\"\n", + " response = requests.get(url)\n", + " img = Image.open(BytesIO(response.content))\n", + " return img\n", + "\n", + "\n", + "def prepare_image(img):\n", + " \"\"\"\n", + " Prepare an image for the model.\n", + " \n", + " Steps:\n", + " 1. Resize to 224x224 (model's expected size)\n", + " 2. Convert to array\n", + " 3. Add batch dimension\n", + " 4. Preprocess for MobileNetV2\n", + " \n", + " Args:\n", + " img: PIL Image\n", + " \n", + " Returns:\n", + " Preprocessed image array\n", + " \"\"\"\n", + " # Resize to 224x224 pixels\n", + " img = img.resize((224, 224))\n", + " \n", + " # Convert to numpy array\n", + " img_array = np.array(img)\n", + " \n", + " # Add batch dimension (model expects multiple images)\n", + " img_array = np.expand_dims(img_array, axis=0)\n", + " \n", + " # Preprocess for MobileNetV2\n", + " img_array = preprocess_input(img_array)\n", + " \n", + " return img_array\n", + "\n", + "\n", + "def classify_image(img):\n", + " \"\"\"\n", + " Classify an image and return top predictions.\n", + " \n", + " Args:\n", + " img: PIL Image\n", + " \n", + " Returns:\n", + " List of (class_name, confidence) tuples\n", + " \"\"\"\n", + " # Prepare the image\n", + " img_array = prepare_image(img)\n", + " \n", + " # Make prediction\n", + " predictions = model.predict(img_array, verbose=0)\n", + " \n", + " # Decode predictions to human-readable labels\n", + " # top=5 means we get the top 5 most likely classes\n", + " decoded = decode_predictions(predictions, top=5)[0]\n", + " \n", + " # Convert to simpler format\n", + " results = [(label, float(confidence)) for (_, label, confidence) in decoded]\n", + " \n", + " return results\n", + "\n", + "\n", + "print(\"โœ… Helper functions ready!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Step 4: Test on Sample Images\n", + "\n", + "Let's try classifying some images from the internet!" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Sample images to classify\n", + "# These are from Unsplash (free stock photos)\n", + "test_images = [\n", + " {\n", + " \"url\": \"https://images.unsplash.com/photo-1514888286974-6c03e2ca1dba?w=400\",\n", + " \"description\": \"A cat\"\n", + " },\n", + " {\n", + " \"url\": \"https://images.unsplash.com/photo-1552053831-71594a27632d?w=400\",\n", + " \"description\": \"A dog\"\n", + " },\n", + " {\n", + " \"url\": \"https://images.unsplash.com/photo-1511919884226-fd3cad34687c?w=400\",\n", + " \"description\": \"A car\"\n", + " },\n", + "]\n", + "\n", + "print(f\"๐Ÿงช Testing on {len(test_images)} images...\")\n", + "print(\"=\" * 70)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Classify Each Image" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "for i, img_data in enumerate(test_images, 1):\n", + " print(f\"\\n๐Ÿ“ธ Image {i}: {img_data['description']}\")\n", + " print(\"-\" * 70)\n", + " \n", + " try:\n", + " # Load image\n", + " img = load_image_from_url(img_data['url'])\n", + " \n", + " # Display image\n", + " display(img.resize((200, 200))) # Show smaller version\n", + " \n", + " # Classify\n", + " results = classify_image(img)\n", + " \n", + " # Show predictions\n", + " print(\"\\n๐ŸŽฏ Top 5 Predictions:\")\n", + " for rank, (label, confidence) in enumerate(results, 1):\n", + " # Create a visual bar\n", + " bar_length = int(confidence * 50)\n", + " bar = \"โ–ˆ\" * bar_length\n", + " \n", + " print(f\" {rank}. {label:20s} {confidence*100:5.2f}% {bar}\")\n", + " \n", + " except Exception as e:\n", + " print(f\"โŒ Error: {e}\")\n", + "\n", + "print(\"\\n\" + \"=\" * 70)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Step 5: Try Your Own Images!\n", + "\n", + "Replace the URL below with any image URL you want to classify." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Try your own image!\n", + "# Replace this URL with any image URL\n", + "custom_image_url = \"https://images.unsplash.com/photo-1472491235688-bdc81a63246e?w=400\" # A flower\n", + "\n", + "print(\"๐Ÿ–ผ๏ธ Classifying your custom image...\")\n", + "print(\"=\" * 70)\n", + "\n", + "try:\n", + " # Load and show image\n", + " img = load_image_from_url(custom_image_url)\n", + " display(img.resize((300, 300)))\n", + " \n", + " # Classify\n", + " results = classify_image(img)\n", + " \n", + " # Show results\n", + " print(\"\\n๐ŸŽฏ Top 5 Predictions:\")\n", + " print(\"-\" * 70)\n", + " for rank, (label, confidence) in enumerate(results, 1):\n", + " bar_length = int(confidence * 50)\n", + " bar = \"โ–ˆ\" * bar_length\n", + " print(f\" {rank}. {label:20s} {confidence*100:5.2f}% {bar}\")\n", + " \n", + " # Highlight top prediction\n", + " top_label, top_confidence = results[0]\n", + " print(\"\\n\" + \"=\" * 70)\n", + " print(f\"\\n๐Ÿ† Best guess: {top_label} ({top_confidence*100:.2f}% confident)\")\n", + " \n", + "except Exception as e:\n", + " print(f\"โŒ Error: {e}\")\n", + " print(\" Make sure the URL points to a valid image!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## ๐Ÿ’ก What Just Happened?\n", + "\n", + "1. **We loaded a pre-trained model** - MobileNetV2 was trained on millions of images\n", + "2. **We preprocessed images** - Resized and formatted them for the model\n", + "3. **The model made predictions** - It output probabilities for 1000 object classes\n", + "4. **We decoded the results** - Converted numbers to human-readable labels\n", + "\n", + "### Understanding Confidence Scores\n", + "\n", + "- **90-100%**: Very confident (almost certainly correct)\n", + "- **70-90%**: Confident (probably correct)\n", + "- **50-70%**: Somewhat confident (might be correct)\n", + "- **Below 50%**: Not very confident (uncertain)\n", + "\n", + "### Why might predictions be wrong?\n", + "\n", + "- **Unusual angle or lighting** - Model was trained on typical photos\n", + "- **Multiple objects** - Model expects one main object\n", + "- **Rare objects** - Model only knows 1000 categories\n", + "- **Low quality image** - Blurry or pixelated images are harder\n", + "\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## ๐Ÿš€ Next Steps\n", + "\n", + "1. **Try different images:**\n", + " - Find images on [Unsplash](https://unsplash.com)\n", + " - Right-click โ†’ \"Copy image address\" to get URL\n", + "\n", + "2. **Experiment:**\n", + " - What happens with abstract art?\n", + " - Can it recognize objects from different angles?\n", + " - How does it handle multiple objects?\n", + "\n", + "3. **Learn more:**\n", + " - Explore [Computer Vision lessons](../lessons/4-ComputerVision/README.md)\n", + " - Learn to train your own image classifier\n", + " - Understand how CNNs (Convolutional Neural Networks) work\n", + "\n", + "---\n", + "\n", + "## ๐ŸŽ‰ Congratulations!\n", + "\n", + "You just built an image classifier using a state-of-the-art neural network!\n", + "\n", + "This same technique powers:\n", + "- Google Photos (organizing your photos)\n", + "- Self-driving cars (recognizing objects)\n", + "- Medical diagnosis (analyzing X-rays)\n", + "- Quality control (detecting defects)\n", + "\n", + "Keep exploring and learning! ๐Ÿš€" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.0" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/examples/04-text-sentiment.py b/examples/04-text-sentiment.py new file mode 100644 index 00000000..fe57dfa8 --- /dev/null +++ b/examples/04-text-sentiment.py @@ -0,0 +1,268 @@ +""" +Simple Text Sentiment Analysis +================================ + +This example shows how to analyze the sentiment (emotion) of text. +It's a simplified version that teaches NLP concepts without complex libraries. + +What you'll learn: +- Text preprocessing (cleaning and preparing text) +- Feature extraction (converting words to numbers) +- Sentiment classification (positive vs negative) + +Use case: Determine if a movie review is positive or negative. +""" + +import re +from collections import Counter + +class SimpleSentimentAnalyzer: + """ + A basic sentiment analyzer that learns from labeled examples. + + How it works: + 1. Learns which words appear more in positive vs negative texts + 2. Calculates a "sentiment score" for each word + 3. Uses these scores to predict sentiment of new text + """ + + def __init__(self): + # Store word scores (positive words get positive scores) + self.word_scores = {} + # Track if we've trained + self.is_trained = False + + def preprocess_text(self, text): + """ + Clean and prepare text for analysis. + + Steps: + 1. Convert to lowercase + 2. Remove punctuation + 3. Split into words + + Args: + text: Raw text string + + Returns: + List of cleaned words + """ + # Convert to lowercase + text = text.lower() + + # Remove punctuation and special characters + text = re.sub(r'[^a-z\s]', '', text) + + # Split into words + words = text.split() + + # Remove very short words (like "a", "i") + words = [w for w in words if len(w) > 2] + + return words + + def train(self, training_data): + """ + Learn sentiment patterns from labeled examples. + + Args: + training_data: List of (text, sentiment) tuples + where sentiment is 'positive' or 'negative' + """ + print("๐ŸŽ“ Training sentiment analyzer...") + + # Count words in positive and negative texts + positive_words = Counter() + negative_words = Counter() + + for text, sentiment in training_data: + words = self.preprocess_text(text) + + if sentiment == 'positive': + positive_words.update(words) + else: + negative_words.update(words) + + # Calculate sentiment score for each word + # Score > 0 means more positive, < 0 means more negative + all_words = set(positive_words.keys()) | set(negative_words.keys()) + + for word in all_words: + pos_count = positive_words[word] + neg_count = negative_words[word] + + # Calculate score: difference in appearances + # Add smoothing (+1) to avoid division by zero + total = pos_count + neg_count + self.word_scores[word] = (pos_count - neg_count) / (total + 1) + + self.is_trained = True + + # Show some learned words + print(f"โœ… Learned sentiment for {len(self.word_scores)} words") + print("\n๐Ÿ“Š Most positive words:") + sorted_words = sorted(self.word_scores.items(), key=lambda x: x[1], reverse=True) + for word, score in sorted_words[:5]: + print(f" '{word}': {score:+.3f}") + + print("\n๐Ÿ“Š Most negative words:") + for word, score in sorted_words[-5:]: + print(f" '{word}': {score:+.3f}") + + def analyze(self, text): + """ + Predict the sentiment of new text. + + Args: + text: Text to analyze + + Returns: + Tuple of (sentiment, confidence, score) + """ + if not self.is_trained: + raise Exception("Please train the analyzer first!") + + # Preprocess text + words = self.preprocess_text(text) + + # Calculate total sentiment score + total_score = 0 + word_count = 0 + + for word in words: + if word in self.word_scores: + total_score += self.word_scores[word] + word_count += 1 + + # Average score + if word_count > 0: + avg_score = total_score / word_count + else: + avg_score = 0 + + # Determine sentiment and confidence + sentiment = "positive" if avg_score > 0 else "negative" + confidence = min(abs(avg_score) * 100, 100) # Convert to percentage + + return sentiment, confidence, avg_score + + +def create_training_data(): + """ + Create sample training data (movie reviews with labels). + + In a real application, you'd have thousands of examples! + + Returns: + List of (review_text, sentiment) tuples + """ + return [ + # Positive reviews + ("This movie was absolutely amazing and wonderful! I loved every minute.", "positive"), + ("Brilliant performance! The acting was superb and the story captivating.", "positive"), + ("Fantastic film! Highly recommend to everyone. Best movie of the year!", "positive"), + ("Loved it! Great storytelling and beautiful cinematography.", "positive"), + ("Excellent movie with outstanding performances. A must watch!", "positive"), + ("Amazing! This film exceeded all my expectations. Truly remarkable.", "positive"), + ("Wonderful experience! The plot was engaging and entertaining.", "positive"), + ("Superb direction and acting! One of the best films I've seen.", "positive"), + + # Negative reviews + ("Terrible movie. Waste of time and money. Very disappointed.", "negative"), + ("Awful film! Poor acting and boring story. Would not recommend.", "negative"), + ("Horrible! The worst movie I have ever seen. Extremely disappointing.", "negative"), + ("Bad movie with terrible plot. Boring and predictable.", "negative"), + ("Disappointing film. Poor execution and weak performances.", "negative"), + ("Worst movie ever! Horrible acting and stupid storyline.", "negative"), + ("Terrible experience. Boring and poorly made. Don't waste your time.", "negative"), + ("Awful! Poor quality and uninteresting. Complete waste of time.", "negative"), + ] + + +def main(): + """ + Main function - Let's analyze some sentiments! + """ + print("=" * 70) + print("Simple Text Sentiment Analysis") + print("=" * 70) + print("\n๐Ÿ“š Task: Learn to identify positive and negative movie reviews") + print() + + # Step 1: Create training data + training_data = create_training_data() + print(f"๐Ÿ“Š Training data: {len(training_data)} movie reviews") + print() + + # Step 2: Create and train analyzer + analyzer = SimpleSentimentAnalyzer() + analyzer.train(training_data) + print() + + # Step 3: Test on new reviews + print("๐Ÿงช Testing on new movie reviews:") + print("=" * 70) + + test_reviews = [ + "This movie was fantastic! I really enjoyed it.", + "Boring and terrible. Not worth watching.", + "Amazing cinematography and wonderful acting!", + "The worst film I've seen this year. Awful.", + "Pretty good movie with some great moments.", + "Disappointing and poorly directed.", + ] + + for i, review in enumerate(test_reviews, 1): + sentiment, confidence, score = analyzer.analyze(review) + + # Visual indicator + indicator = "๐Ÿ˜Š" if sentiment == "positive" else "๐Ÿ˜ž" + + print(f"\nReview {i}:") + print(f" Text: \"{review}\"") + print(f" {indicator} Sentiment: {sentiment.upper()}") + print(f" ๐Ÿ“Š Confidence: {confidence:.1f}%") + print(f" ๐Ÿ“ˆ Score: {score:+.3f}") + + print("\n" + "=" * 70) + + # Interactive mode + print("\n๐Ÿ’ฌ Try it yourself! Enter your own review (or 'quit' to exit):") + print("-" * 70) + + while True: + user_input = input("\nYour review: ").strip() + + if user_input.lower() in ['quit', 'exit', 'q']: + break + + if not user_input: + continue + + try: + sentiment, confidence, score = analyzer.analyze(user_input) + indicator = "๐Ÿ˜Š" if sentiment == "positive" else "๐Ÿ˜ž" + + print(f"\n{indicator} Sentiment: {sentiment.upper()}") + print(f"๐Ÿ“Š Confidence: {confidence:.1f}%") + print(f"๐Ÿ“ˆ Score: {score:+.3f}") + except Exception as e: + print(f"Error: {e}") + + # Explanation + print("\n๐Ÿ’ก What just happened?") + print("1. The analyzer learned word patterns from example reviews") + print("2. It calculated 'sentiment scores' for words") + print("3. For new text, it combines word scores to predict sentiment") + print() + print("๐ŸŽ‰ You just built a sentiment analyzer!") + print() + print("๐Ÿš€ Next steps:") + print(" - Add more training examples to improve accuracy") + print(" - Try analyzing tweets, product reviews, or comments") + print(" - Explore more advanced NLP in lessons/5-NLP/") + print() + + +if __name__ == "__main__": + main() diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 00000000..e74a3be7 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,80 @@ +# Beginner-Friendly AI Examples + +Welcome! This directory contains simple, standalone examples to help you get started with AI and machine learning. Each example is designed to be beginner-friendly with detailed comments and step-by-step explanations. + +## ๐Ÿ“š Examples Overview + +| Example | Description | Difficulty | Prerequisites | +|---------|-------------|------------|---------------| +| [Hello AI World](./01-hello-ai-world.py) | Your first AI program - simple pattern recognition | โญ Beginner | Python basics | +| [Simple Neural Network](./02-simple-neural-network.py) | Build a neural network from scratch | โญโญ Beginner+ | Python, basic math | +| [Image Classifier](./03-image-classifier.ipynb) | Classify images with a pre-trained model | โญโญ Beginner+ | Python, numpy | +| [Text Sentiment](./04-text-sentiment.py) | Analyze text sentiment (positive/negative) | โญโญ Beginner+ | Python | + +## ๐Ÿš€ Getting Started + +### Prerequisites + +Make sure you have Python installed (3.8 or higher recommended). Install required packages: + +```bash +# For Python scripts +pip install numpy + +# For Jupyter notebooks (image classifier) +pip install jupyter numpy pillow tensorflow +``` + +Or use the conda environment from the main curriculum: + +```bash +conda env create --name ai4beg --file ../environment.yml +conda activate ai4beg +``` + +### Running the Examples + +**For Python scripts (.py files):** +```bash +python 01-hello-ai-world.py +``` + +**For Jupyter notebooks (.ipynb files):** +```bash +jupyter notebook 03-image-classifier.ipynb +``` + +## ๐Ÿ“– Learning Path + +We recommend following the examples in order: + +1. **Start with "Hello AI World"** - Learn the basics of pattern recognition +2. **Build a Simple Neural Network** - Understand how neural networks work +3. **Try the Image Classifier** - See AI in action with real images +4. **Analyze Text Sentiment** - Explore natural language processing + +## ๐Ÿ’ก Tips for Beginners + +- **Read the code comments carefully** - They explain what each line does +- **Experiment!** - Try changing values and see what happens +- **Don't worry about understanding everything** - Learning takes time +- **Ask questions** - Use the [Discussion board](https://github.com/microsoft/AI-For-Beginners/discussions) + +## ๐Ÿ”— Next Steps + +After completing these examples, explore the full curriculum: +- [Introduction to AI](../lessons/1-Intro/README.md) +- [Neural Networks](../lessons/3-NeuralNetworks/README.md) +- [Computer Vision](../lessons/4-ComputerVision/README.md) +- [Natural Language Processing](../lessons/5-NLP/README.md) + +## ๐Ÿค Contributing + +Found these examples helpful? Help us improve them: +- Report issues or suggest improvements +- Add more examples for beginners +- Improve documentation and comments + +--- + +*Remember: Every expert was once a beginner. Happy learning! ๐ŸŽ“*