写一段pytorch的示例代码
时间: 2023-09-18 19:05:51 浏览: 100
### 回答1:
以下是一段pytorch的示例代码:
import torch
# 创建一个5x3的矩阵
x = torch.rand(5, 3)
# 计算矩阵的行列式
y = torch.det(x)
# 计算矩阵的逆
z = torch.inverse(x)
print(x)
print(y)
print(z)
### 回答2:
以下是一个简单的PyTorch示例代码,用于训练一个简单的神经网络模型来分类手写数字图像:
```python
import torch
import torchvision
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
# 加载训练和测试数据集
train_dataset = torchvision.datasets.MNIST(root='./data', train=True, transform=torchvision.transforms.ToTensor(), download=True)
test_dataset = torchvision.datasets.MNIST(root='./data', train=False, transform=torchvision.transforms.ToTensor(), download=True)
# 创建数据加载器
train_loader = DataLoader(dataset=train_dataset, batch_size=64, shuffle=True)
test_loader = DataLoader(dataset=test_dataset, batch_size=64, shuffle=False)
# 定义神经网络模型
class NeuralNet(nn.Module):
def __init__(self):
super(NeuralNet, self).__init__()
self.flatten = nn.Flatten()
self.fc1 = nn.Linear(784, 128)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.flatten(x)
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
# 创建模型实例并定义损失函数和优化器
model = NeuralNet()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.001)
# 训练模型
for epoch in range(10):
for images, labels in train_loader:
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# 在测试集上评估模型准确率
correct = 0
total = 0
with torch.no_grad():
for images, labels in test_loader:
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = correct / total
print('Accuracy: {:.2f}%'.format(accuracy * 100))
```
这段代码使用PyTorch框架训练了一个简单的神经网络模型,用于对手写数字图像进行分类。它首先加载了MNIST数据集,并创建了数据加载器。然后定义了一个包含两个线性层的神经网络模型。接下来,通过循环训练10个epochs,在每个训练批次中计算模型的输出、损失并进行反向传播更新模型参数。最后,使用测试数据集评估了模型的准确率。
### 回答3:
下面是一个简单的 PyTorch 示例代码,用于创建一个简单的全连接神经网络并训练一个分类任务。
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.datasets as datasets
import torchvision.transforms as transforms
# 定义全连接神经网络模型
class NeuralNetwork(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(NeuralNetwork, self).__init__()
self.layer1 = nn.Linear(input_size, hidden_size)
self.relu = nn.ReLU()
self.layer2 = nn.Linear(hidden_size, num_classes)
def forward(self, x):
out = self.layer1(x)
out = self.relu(out)
out = self.layer2(out)
return out
# 超参数设置
input_size = 784 # 输入特征维度(28x28的图像展开后为784)
hidden_size = 500 # 隐藏层神经元数目
num_classes = 10 # 分类数目(手写数字0-9)
learning_rate = 0.001
batch_size = 64
num_epochs = 10
# 加载MNIST数据集
train_dataset = datasets.MNIST(root='./data', train=True, transform=transforms.ToTensor(), download=True)
test_dataset = datasets.MNIST(root='./data', train=False, transform=transforms.ToTensor())
# 构建数据加载器
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False)
# 初始化模型和损失函数
model = NeuralNetwork(input_size, hidden_size, num_classes)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 模型训练
total_step = len(train_loader)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# 图像数据展开
images = images.reshape(-1, 28*28)
# 正向传播
outputs = model(images)
loss = criterion(outputs, labels)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i+1) % 100 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
# 模型评估
model.eval()
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
images = images.reshape(-1, 28*28)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Test Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))
```
这段代码展示了如何使用 PyTorch 创建一个简单的全连接神经网络模型,并使用 MNIST 数据集进行图像分类任务。代码中包含了模型的构建、数据加载、训练和评估过程。在训练过程中,通过反向传播和优化器来最小化损失函数,以提高模型的准确度。在评估过程中,使用测试集来计算模型的准确率。
阅读全文