PyTorch常见的代码实现
时间: 2024-05-01 14:20:21 浏览: 87
PyTorch是一个基于Python的科学计算库,用于构建深度学习模型。以下是PyTorch中常见的代码实现:
1. 张量创建和操作
```python
import torch
# 创建一个张量
x = torch.tensor([1, 2, 3])
# 创建一个随机张量
y = torch.randn(3, 3)
# 张量加法
z = x + y
# 张量乘法
w = x.matmul(y)
# 改变张量形状
z = z.view(9)
```
2. 模型定义和训练
```python
import torch.nn as nn
import torch.optim as optim
# 定义一个网络
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(10, 5)
self.fc2 = nn.Linear(5, 1)
def forward(self, x):
x = nn.functional.relu(self.fc1(x))
x = self.fc2(x)
return x
# 定义损失函数和优化器
net = Net()
criterion = nn.MSELoss()
optimizer = optim.SGD(net.parameters(), lr=0.01)
# 训练模型
for epoch in range(10):
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print('[%d] loss: %.3f' % (epoch + 1, running_loss / len(trainloader)))
```
3. 数据加载和预处理
```python
import torch.utils.data as data
from torchvision import datasets, transforms
# 定义一个数据集
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))])
trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
trainloader = data.DataLoader(trainset, batch_size=32, shuffle=True)
# 加载数据集
for i, data in enumerate(trainloader, 0):
inputs, labels = data
```
这些是PyTorch中常见的代码实现,它们涵盖了PyTorch的大部分功能,但并非全部。
阅读全文