preamble
This article focuses on the second half of the use of convolutional neural networks.
Also, a little code comment was added to the last post, mainly to explain the use of the formula (w-f+2p)/s+1.
So, if the code in this post doesn't make much sense, flip through the previous post.
code implementation
Previously, we have learned the concepts, and in conjunction with our previous learning, we can read the following code directly.
The code uses, dataset.CIFAR10 dataset.
The CIFAR-10 dataset consists of 60,000 32x32 color images divided into 10 different categories, namely, airplanes, cars, birds, cats, deer, dogs, frogs, horses, boats, and trucks.
Each category contains 6000 images, of which 50000 are used for training and 10000 for testing.
import torch
import as nn
import torchvision
import as transforms
import as plt
import numpy as np
import as F #nnfail,Look for the activation function here.
# device config
device = ('cuda' if .is_available() else 'cpu')
# hyper parameters
input_size = 784 # 28x28
hidden_size = 100
num_classes = 10
batch_size = 100
learning_rate = 0.001
num_epochs = 2
transform = (
[(), ((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
train_dataset = .CIFAR10(
root='./data', train=True, download=True, transform=transform)
test_dataset = .CIFAR10(
root='./data', train=False, download=True, transform=transform)
train_loader = . (
dataset=train_dataset, batch_size=batch_size, shuffle=True)
test_loader = (
dataset=test_dataset, batch_size=batch_size, shuffle=False)
print('each100classifier for individual things or people, general, catch-all classifier,How much is it divided into?:', len(test_loader))
classes = ('plane', 'car', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck')
class ConvNet():
def __init__(self):
super(ConvNet,self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
= nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = (16*5*5, 120) #这classifier for individual things or people, general, catch-all classifier在forwardreasonable grounds
self.fc2 = (120, 84)
self.fc3 = (84, 10)
def forward(self, x):
x = ((self.conv1(x)))
x = ((self.conv2(x))) #here arexturn into ([4, 16, 5, 5])
# print("After two convolutions and two poolings:",)
x = (-1,16*5*5)#here are的16*5*5just likexback of3classifier for individual things or people, general, catch-all classifier维度相乘
x = (self.fc1(x)) #fc1defined when,inputxalready are6*5*5(modal particle intensifying preceding clause)
x = (self.fc2(x))
x= self.fc3(x)
return x
model = ConvNet().to(device)
criterion = ()
optimizer = ((), lr=learning_rate)
n_total_steps = len(train_loader)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# origin shape:[4,3,32,32]=4,3,1024
# input layer: 3 input channels, 6 output channels, 5 kernel size
images = (device)
labels = (device)
# Forward pass
outputs = model(images)
loss = criterion(outputs, labels)
# Backward and optimize
optimizer.zero_grad()
()
()
if (i+1) % 2000 == 0:
print(
f'Epoch [{epoch+1}/{num_epochs}], Step [{i+1}/{n_total_steps}], Loss: {():.4f}')
print('Finished Training')
# test
with torch.no_grad():
n_correct = 0
n_samples = 0
n_class_correct = [0 for i in range(10)] #generating 10 classifier for individual things or people, general, catch-all classifier 0 listings
n_class_samples = [0 for i in range(10)]
for images, labels in test_loader:
images = (device)
labels = (device)
print(':', )
outputs = model(images)
# max returns(value ,index)
_, predicted = (outputs, 1)
n_samples += (0)
n_correct += (predicted == labels).sum().item()
for i in range(batch_size):
label = labels[i]
# print("label:",label) #here are存的是 0~9figures 输出just like这样的 label: tensor(2) predicted[i]It's the same number.
pred = predicted[i]
if (label == pred):
n_class_correct[label] += 1
n_class_samples[label] += 1
acc = 100.0*n_correct/n_samples # Calculated correct rate
print(f'accuracy ={acc}')
for i in range(10):
acc = 100.0*n_class_correct[i]/n_class_samples[i]
print(f'Accuracy of {classes[i]}: {acc} %')
The results of the run are as follows:
accuracy =10.26
Accuracy of plane: 0.0 %
Accuracy of car: 0.0 %
Accuracy of bird: 0.0 %
Accuracy of cat: 0.0 %
Accuracy of deer: 0.0 %
Accuracy of dog: 0.0 %
Accuracy of frog: 0.0 %
Accuracy of horse: 0.0 %
Accuracy of ship: 89.6 %
Accuracy of truck: 13.0 %
This is because I set num_epochs=2, which means the number of loops is too low, so the accuracy of the results is low.
We just need to increase the value of epochs to improve the accuracy.
Portal:
Learning Artificial Intelligence from Zero - Python-Pytorch Learning - Full Episode
Thus we are done learning about convolutional neural networks.
Note: This post is original, please contact the author for authorization and attribution for any form of reproduction!
If you think this article is still good, please click [Recommend] below, thank you very much!
/kiba/p/18381036