🐍 Python Tutorial: Introduction to AI & Deep Learning

Artificial Intelligence (AI) is the broader concept of machines being able to perform tasks that typically require human intelligence. Deep learning is a subset of machine learning that uses neural networks with many layers (deep neural networks) to learn from large amounts of data. Python offers powerful libraries like PyTorch and Keras (built on TensorFlow) to build and train deep learning models efficiently.


1. PyTorch

PyTorch is a popular open-source deep learning framework developed by Facebook's AI Research lab. It’s known for its dynamic computation graph, ease of debugging, and strong Python integration.

import torch
import torch.nn as nn
import torch.optim as optim

# Define a simple neural network
class SimpleNN(nn.Module):
    def __init__(self):
        super(SimpleNN, self).__init__()
        self.fc1 = nn.Linear(10, 50)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(50, 2)

    def forward(self, x):
        x = self.fc1(x)
        x = self.relu(x)
        x = self.fc2(x)
        return x

# Create the model, loss function and optimizer
model = SimpleNN()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

# Dummy input and target
inputs = torch.randn(5, 10)
targets = torch.tensor([0, 1, 0, 1, 0])

# Forward pass
outputs = model(inputs)
loss = criterion(outputs, targets)

# Backward pass and optimization step
loss.backward()
optimizer.step()

print('Loss:', loss.item())

2. Keras

Keras is a high-level deep learning API, running on top of TensorFlow. It is user-friendly, modular, and easy to extend, making it ideal for beginners and rapid prototyping.

from tensorflow import keras
from tensorflow.keras import layers

# Define a simple sequential model
model = keras.Sequential([
    layers.Dense(50, activation='relu', input_shape=(10,)),
    layers.Dense(2)
])

# Compile the model with loss function and optimizer
model.compile(optimizer='adam',
              loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

# Dummy data
import numpy as np
x_train = np.random.random((5, 10))
y_train = np.array([0, 1, 0, 1, 0])

# Train the model
model.fit(x_train, y_train, epochs=5)

# Evaluate
loss, accuracy = model.evaluate(x_train, y_train)
print('Loss:', loss)
print('Accuracy:', accuracy)

Additional Resources & References


← Back : Machine LearningNext: Security Best Practicces