把它用pytorch改写:clear; dir=('pictures'); testdir=('testPictures'); trainingSet = imageSet(dir,'recursive'); testSet = imageSet(testdir,'recursive'); [trainingFeatures,trainingLabels,testFeatures,testLabels]=extractFeature(trainingSet,testSet); %% %训练一个svm分类器 %fitcecoc 使用1对1的方案 classifier = fitcecoc(trainingFeatures, trainingLabels); save classifier.mat classifier; % 使用测试图像的特征向量预测样本标签 predictedLabels = predict(classifier, testFeatures); %% 评估分类器 %使用没有标签的图像数据进行测试,生成一个混淆矩阵表明分类效果 confMat=confusionmat(testLabels, predictedLabels) % accuracy=(confMat(1,1)/sum(confMat(1,:))+confMat(2,2)/sum(confMat(2,:))+... % confMat(3,3)/sum(confMat(3,:))+confMat(4,4)/sum(confMat(4,:)))/4 accuracy=(confMat(1,1)/sum(confMat(1,:))+confMat(2,2)/sum(confMat(2,:))+... confMat(3,3)/sum(confMat(3,:)))/3
时间: 2024-02-03 09:11:16 浏览: 172
使用Pytorch来拟合函数方式
以下是将给定代码用 PyTorch 改写的示例:
```python
import torch
import torchvision
import torchvision.transforms as transforms
trainset = torchvision.datasets.ImageFolder(root='pictures', transform=transforms.ToTensor())
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2)
testset = torchvision.datasets.ImageFolder(root='testPictures', transform=transforms.ToTensor())
testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=2)
classes = trainset.classes
# 定义卷积神经网络
class Net(torch.nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = torch.nn.Conv2d(3, 6, 5)
self.pool = torch.nn.MaxPool2d(2, 2)
self.conv2 = torch.nn.Conv2d(6, 16, 5)
self.fc1 = torch.nn.Linear(16 * 5 * 5, 120)
self.fc2 = torch.nn.Linear(120, 84)
self.fc3 = torch.nn.Linear(84, len(classes))
def forward(self, x):
x = self.pool(torch.nn.functional.relu(self.conv1(x)))
x = self.pool(torch.nn.functional.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = torch.nn.functional.relu(self.fc1(x))
x = torch.nn.functional.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
# 定义损失函数和优化器
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# 训练网络
for epoch in range(2): # 多次迭代
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()
if i % 2000 == 1999: # 每 2000 个小批量打印一次平均损失
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 2000))
running_loss = 0.0
print('Finished Training')
# 测试网络
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
images, labels = data
outputs = net(images)
_, 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))
```
注意:此代码仅作为示例,可能需要根据具体情况进行修改和调整。
阅读全文