Pytorch搭建CNN网络读取40个42×42的矩阵,和40和0或1的标签
时间: 2023-11-22 20:56:10 浏览: 60
以下是一个简单的Pytorch CNN网络,可以用于读取40个大小为42x42的矩阵,并将它们与相应的标签进行训练和测试:
```python
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import torch.nn.functional as F
import numpy as np
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 9 * 9, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 2)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 9 * 9)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
# Define loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# Load data
data = np.load('data.npy')
labels = np.load('labels.npy')
# Split data into train and test sets
train_data = data[:30]
train_labels = labels[:30]
test_data = data[30:]
test_labels = labels[30:]
# Create PyTorch dataset and dataloader
class MyDataset(data.Dataset):
def __init__(self, data, labels):
super(MyDataset, self).__init__()
self.data = data
self.labels = labels
def __getitem__(self, index):
return self.data[index], self.labels[index]
def __len__(self):
return len(self.data)
train_dataset = MyDataset(train_data, train_labels)
train_dataloader = data.DataLoader(train_dataset, batch_size=10, shuffle=True)
# Train the network
for epoch in range(10):
running_loss = 0.0
for i, data in enumerate(train_dataloader, 0):
inputs, labels = data
optimizer.zero_grad()
outputs = net(inputs.float())
loss = criterion(outputs, labels.long())
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 3 == 2:
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 3))
running_loss = 0.0
print('Finished Training')
# Test the network
correct = 0
total = 0
with torch.no_grad():
for data in test_data:
images, labels = data
outputs = net(images.float())
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the test images: %d %%' % (
100 * correct / total))
```
其中,`data.npy`是一个包含40个大小为42x42的矩阵的numpy数组,`labels.npy`是一个包含相应标签的numpy数组。这个网络使用了2个卷积层和3个全连接层,可以通过调整网络结构和训练参数来优化性能。
阅读全文