microsoft/AI-For-Beginners

Public

mirrored fromhttps://github.com/microsoft/AI-For-BeginnersAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
copilot/update-symbolic-api-endpoint

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

examples/01-hello-ai-world.py

138lines ยท modecode

1"""
2Hello AI World - Your First AI Program
3=======================================
4
5This is a simple pattern recognition example that demonstrates core AI concepts:
6- Learning from data
7- Making predictions
8- Understanding patterns
9
10What this program does:
11- Learns a simple mathematical pattern (y = 2x)
12- Uses that pattern to make predictions
13- No complex libraries needed - just pure Python!
14
15Perfect for understanding AI basics before diving into neural networks.
16"""
17
18import random
19
20class SimpleAILearner:
21 """
22 A very simple AI that learns linear relationships.
23 This demonstrates the fundamental concept of AI: learning from data.
24 """
25
26 def __init__(self):
27 # The "weight" is what our AI learns
28 # It starts with a random guess
29 self.weight = random.uniform(0, 5)
30 self.learning_rate = 0.01 # How fast our AI learns
31
32 def predict(self, x):
33 """
34 Make a prediction based on what we've learned.
35
36 Args:
37 x: Input value
38
39 Returns:
40 Predicted output
41 """
42 return self.weight * x
43
44 def train(self, training_data, epochs=100):
45 """
46 Train the AI to learn the pattern in the data.
47
48 Args:
49 training_data: List of (input, output) pairs
50 epochs: Number of times to go through all the data
51 """
52 print("๐ŸŽ“ Training started...")
53 print(f"Initial guess for weight: {self.weight:.2f}")
54
55 for epoch in range(epochs):
56 total_error = 0
57
58 # Learn from each example
59 for x, y_actual in training_data:
60 # Make a prediction
61 y_predicted = self.predict(x)
62
63 # Calculate error (how wrong we were)
64 error = y_actual - y_predicted
65 total_error += abs(error)
66
67 # Update our weight to reduce error (this is learning!)
68 self.weight += self.learning_rate * error * x
69
70 # Print progress every 20 epochs
71 if (epoch + 1) % 20 == 0:
72 avg_error = total_error / len(training_data)
73 print(f"Epoch {epoch + 1}/{epochs} - Average error: {avg_error:.4f} - Weight: {self.weight:.2f}")
74
75 print(f"โœ… Training complete! Final weight: {self.weight:.2f}")
76
77
78def main():
79 """
80 Main function - Let's teach our AI!
81 """
82 print("=" * 60)
83 print("Welcome to Hello AI World!")
84 print("=" * 60)
85 print()
86 print("Today, we'll teach an AI to learn a simple pattern:")
87 print("Given x, predict y where y = 2x")
88 print()
89
90 # Step 1: Create training data
91 # The pattern we want the AI to learn: y = 2 * x
92 print("๐Ÿ“Š Creating training data...")
93 training_data = [
94 (1, 2), # When x=1, y should be 2
95 (2, 4), # When x=2, y should be 4
96 (3, 6), # When x=3, y should be 6
97 (4, 8), # When x=4, y should be 8
98 (5, 10), # When x=5, y should be 10
99 ]
100 print(f"Training examples: {training_data}")
101 print()
102
103 # Step 2: Create and train our AI
104 ai = SimpleAILearner()
105 ai.train(training_data, epochs=100)
106 print()
107
108 # Step 3: Test our AI with new data
109 print("๐Ÿงช Testing our AI with new inputs...")
110 print("-" * 60)
111 test_inputs = [6, 7, 10, 15]
112
113 for x in test_inputs:
114 prediction = ai.predict(x)
115 actual = 2 * x # The true answer
116 print(f"Input: {x:2d} | Prediction: {prediction:6.2f} | Actual: {actual:6.2f} | Difference: {abs(prediction - actual):.2f}")
117
118 print("-" * 60)
119 print()
120
121 # Explanation
122 print("๐Ÿ’ก What just happened?")
123 print("1. We gave the AI examples of the pattern (y = 2x)")
124 print("2. The AI learned by adjusting its 'weight' to minimize errors")
125 print("3. After training, it can predict outputs for new inputs!")
126 print()
127 print("๐ŸŽ‰ Congratulations! You just trained your first AI!")
128 print()
129 print("๐Ÿš€ Next steps:")
130 print(" - Try changing the training data to learn different patterns")
131 print(" - Experiment with the learning_rate (line 29)")
132 print(" - Modify epochs to see how training time affects accuracy")
133 print()
134
135
136if __name__ == "__main__":
137 # This runs when you execute the script
138 main()
139