PyTorch is an open-source machine learning library developed by Facebook's AI Research lab (FAIR). It is widely used for building and training deep learning models, especially in research and development. PyTorch provides dynamic computational graphs, automatic differentiation, and a rich ecosystem that includes tools for computer vision, natural language processing, and more.
import torch
import torch.nn as nn
import torch.optim as optim
# Create a simple neural network
class SimpleNN(nn.Module):
def __init__(self):
super(SimpleNN, self).__init__()
self.fc1 = nn.Linear(2, 1)
def forward(self, x):
return torch.sigmoid(self.fc1(x))
# Create a toy dataset
data = torch.tensor([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=torch.float32)
labels = torch.tensor([[0], [1], [1], [0]], dtype=torch.float32)
# Instantiate the model, loss function, and optimizer
model = SimpleNN()
criterion = nn.BCELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
# Train the model
for epoch in range(10000):
optimizer.zero_grad()
predictions = model(data)
loss = criterion(predictions, labels)
loss.backward()
optimizer.step()
# Test the trained model
with torch.no_grad():
test_data = torch.tensor([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=torch.float32)
predictions = model(test_data)
print("Predictions after training:")
print(predictions)
This example demonstrates creating and training a simple neural network using PyTorch:
Feel free to run this code in a Python environment with PyTorch installed to explore the capabilities of PyTorch for deep learning!
To install PyTorch, you can use the following command:
pip install torch