Pytorch搭建CNN网络读取40个42×42的矩阵,和40和0或1的标签
时间: 2023-11-22 09:52:54 浏览: 77
高光谱图像分类(India数据集)-基于像素点分类(bp网络和cnn网络)
以下是基于PyTorch的CNN网络读取40个42x42的矩阵和相应的标签的示例代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
# 定义数据集
class MatrixDataset(Dataset):
def __init__(self, matrices, labels):
self.matrices = matrices
self.labels = labels
def __len__(self):
return len(self.matrices)
def __getitem__(self, idx):
matrix = self.matrices[idx]
label = self.labels[idx]
return matrix, label
# 定义CNN网络
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 16, kernel_size=3)
self.conv2 = nn.Conv2d(16, 32, kernel_size=3)
self.fc1 = nn.Linear(32 * 18 * 18, 128)
self.fc2 = nn.Linear(128, 2)
def forward(self, x):
x = nn.functional.relu(self.conv1(x))
x = nn.functional.max_pool2d(nn.functional.relu(self.conv2(x)), 2)
x = x.view(-1, 32 * 18 * 18)
x = nn.functional.relu(self.fc1(x))
x = self.fc2(x)
return nn.functional.log_softmax(x, dim=1)
# 训练函数
def train(model, device, train_loader, optimizer, epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
loss = nn.functional.nll_loss(output, target)
loss.backward()
optimizer.step()
if batch_idx % 10 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
# 测试函数
def test(model, device, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output = model(data)
test_loss += nn.functional.nll_loss(output, target, reduction='sum').item()
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
# 主程序
if __name__ == '__main__':
# 读取数据
matrices = []
labels = []
for i in range(40):
matrix = torch.randn(1, 42, 42) # 随机生成42x42的矩阵
matrices.append(matrix)
label = torch.randint(0, 2, (1,)) # 随机生成0或1的标签
labels.append(label)
dataset = MatrixDataset(matrices, labels)
train_loader = DataLoader(dataset, batch_size=4, shuffle=True)
# 初始化模型和优化器
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = Net().to(device)
optimizer = optim.Adam(model.parameters(), lr=0.001)
# 训练和测试
for epoch in range(1, 11):
train(model, device, train_loader, optimizer, epoch)
test(model, device, train_loader)
```
在上面的代码中,我们首先定义了一个 `MatrixDataset` 类来读取矩阵和标签。然后,我们定义了一个简单的CNN网络 `Net`,其中包含两个卷积层和两个全连接层。我们使用 `nn.functional` 中的激活函数和损失函数,以及 PyTorch 自带的优化器 Adam。接着,我们定义了训练函数 `train` 和测试函数 `test`,并在主程序中循环训练和测试。在训练过程中,我们使用随机梯度下降法优化模型参数,并使用交叉熵损失函数衡量模型性能。在测试过程中,我们计算模型在测试集上的准确率和损失函数值。
阅读全文