Install & Compatibility
Where this runs
tested against v? · pip install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.920 runs
build_error
glibcpy 3.10–3.920 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
nn
✓ import torch.nn as nn
optim
✓ import torch.optim as optim
DataLoader
✓ from torch.utils.data import DataLoader, TensorDataset
This quickstart demonstrates a simple linear regression model in PyTorch. It covers defining a dataset and dataloader, creating a neural network module, setting up a loss function and optimizer, and running a basic training loop. It uses randomly generated data for a simple y = 2x + 1 relationship.
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import TensorDataset, DataLoader
# 1. Prepare Data
x_data = torch.randn(100, 1)
y_data = 2 * x_data + 1 + torch.randn(100, 1) * 0.1 # y = 2x + 1 + noise
# Create a Dataset and DataLoader
dataset = TensorDataset(x_data, y_data)
dataloader = DataLoader(dataset, batch_size=10, shuffle=True)
# 2. Define Model
class LinearRegression(nn.Module):
def __init__(self):
super(LinearRegression, self).__init__()
self.linear = nn.Linear(1, 1) # One input feature, one output feature
def forward(self, x):
return self.linear(x)
model = LinearRegression()
# 3. Define Loss and Optimizer
criterion = nn.MSELoss() # Mean Squared Error Loss
optimizer = optim.SGD(model.parameters(), lr=0.01) # Stochastic Gradient Descent
# 4. Train the Model
num_epochs = 100
for epoch in range(num_epochs):
for batch_x, batch_y in dataloader:
# Forward pass
outputs = model(batch_x)
loss = criterion(outputs, batch_y)
# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch+1) % 10 == 0:
print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')
# 5. Make Predictions
predicted_value = model(torch.tensor([[5.0]]))
print(f"\nPredicted value for x=5.0: {predicted_value.item():.4f}")
print(f"Learned parameters: Weight={model.linear.weight.item():.4f}, Bias={model.linear.bias.item():.4f}")
Debug
Known issues
breakingThe `torch.autograd.Variable` class was deprecated and is now effectively an alias for `torch.Tensor`. Direct tensor operations now support autograd automatically.fixUse `torch.Tensor` directly. All tensors automatically track history if `requires_grad=True`.
affects: <0.4.0 (breaking), 0.4.0-1.x (deprecated), 2.x+ (removed/alias)
deprecatedThe `volatile=True` argument for tensors was deprecated and removed. It was used to signal that computations in a graph should not track gradients (e.g., during inference).fixFor inference or operations where gradients are not needed, use the `with torch.no_grad():` context manager.
affects: <0.4.0 (used), 0.4.0-1.x (deprecated), 2.x+ (removed)
gotchaExtracting a scalar value from a single-element tensor using `float(tensor)` or `int(tensor)` will raise a runtime error if the tensor has more than one element.fixAlways use `tensor.item()` to extract a Python scalar from a single-element tensor.
affects: All versions
gotchaWhen installing PyTorch, the `pip install pytorch` command provides the CPU version by default. For GPU acceleration, specific installation instructions are required, typically involving `pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cuXXx` where `cuXXx` specifies your CUDA version.fixConsult the official PyTorch website (pytorch.org/get-started/locally/) to obtain the correct `pip` command for your specific operating system, CUDA version, and Python environment.
affects: All versions
gotchaMoving models or tensors between CPU and GPU devices. Using `.cuda()` on tensors/models will move them to the default GPU, but `.to(device)` is more flexible.fixDefine a `device` variable (e.g., `device = 'cuda' if torch.cuda.is_available() else 'cpu'`) and consistently use `tensor.to(device)` or `model.to(device)` for all relevant components.
affects: All versions
Upgrade
Version history
1.0.2latest on PyPI · released Apr 24, 2019
Audit
Dependencies
torchrequiredCore PyTorch library, installed by 'pytorch' meta-package.
torchvisionrequiredComputer vision library for PyTorch, installed by 'pytorch' meta-package.
torchaudiorequiredAudio processing library for PyTorch, installed by 'pytorch' meta-package.
numpyoptionalOften used for data preprocessing and interoperability, implicitly relied upon.