on
ai 주식투자
- Get link
- X
- Other Apps
PyTorch: Dynamic and Flexible Machine Learning
PyTorch is an open-source machine learning library based on the Torch library, originally developed by Facebook's AI Research lab. It's known for its dynamic computation graph and Python-first approach, making it popular among researchers and developers.
Key Features & Why it's Useful:
Simple Example: (Creating a simple linear regression model)
import torch
import torch.nn as nn
import torch.optim as optim
# Define the model
class LinearRegression(nn.Module):
def __init__(self):
super(LinearRegression, self).__init__()
self.linear = nn.Linear(1, 1) # One input feature, one output
def forward(self, x):
return self.linear(x)
# Create the model
model = LinearRegression()
# Define the loss function and optimizer
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
# Sample data
x = torch.tensor([[1.0], [2.0], [3.0], [4.0], [5.0]])
y = torch.tensor([[2.0], [4.0], [6.0], [8.0], [10.0]])
# Train the model
for epoch in range(100):
# Forward pass
outputs = model(x)
loss = criterion(outputs, y)
# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Make a prediction
with torch.no_grad(): # Disable gradient calculation during prediction
prediction = model(torch.tensor([[6.0]]))
print(prediction) # Output: tensor([[12.]])
Comments
Post a Comment