AI Development Lesson 2: Python for AI

🤖 AI Development CourseLesson 2 of 10 · 20% complete

Python dominates AI/ML — 90%+ of AI libraries are Python-first. This lesson covers the Python features specifically needed for AI work.

Setup

# Recommended: Anaconda (includes all AI packages)
# Or: create a virtual env
python -m venv ai_env
source ai_env/bin/activate  # Mac/Linux
# ai_env\Scripts\activate  # Windows

# Essential AI packages:
pip install numpy pandas matplotlib scikit-learn
pip install torch torchvision  # PyTorch
pip install openai  # OpenAI API
pip install jupyter  # Jupyter notebooks

# Start Jupyter:
jupyter notebook

Python Features Used in AI

import numpy as np

# List comprehensions (common for data prep)
squares = [x**2 for x in range(10)]
filtered = [x for x in data if x > 0]

# Lambda functions
sorted_data = sorted(items, key=lambda x: x['score'], reverse=True)

# Generators (memory-efficient for large datasets)
def batch_generator(data, batch_size):
    for i in range(0, len(data), batch_size):
        yield data[i:i + batch_size]

# Type hints (standard in modern AI code)
def predict(features: list[float]) -> float:
    return model.predict([features])[0]

# Dataclasses for structured data
from dataclasses import dataclass

@dataclass
class TrainingConfig:
    learning_rate: float = 0.001
    batch_size: int = 32
    epochs: int = 100
    dropout: float = 0.3

Jupyter Notebooks

# Jupyter is the standard for AI/data science work
# Cells can be code or markdown
# Output shows inline (great for exploring data)

# Each cell runs independently
# Shift+Enter: run cell and go to next
# Ctrl+Enter: run cell, stay
# B: insert cell below
# M: convert cell to markdown

🏋️ Practice Task

Set up a Jupyter environment. Create a notebook called “ai_playground.ipynb”. In cells: import numpy and create a 5×5 matrix of random numbers. Compute the mean, std, min, max. Create a function that normalizes an array to [0,1] range. Plot the distribution of a random dataset using matplotlib.

💡 Hint: Normalize: (arr – arr.min()) / (arr.max() – arr.min()). import matplotlib.pyplot as plt; plt.hist(data, bins=20); plt.show()

Similar Posts

Leave a Reply

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