其实就我而言,神经网络就是一个算法,可以看看以下的图片,以及我写的对应的代码
class Tudui(nn.Module):
def __init__(self):
super(Tudui, self).__init__()
self.model = nn.Sequential(
nn.Conv2d(3, 32, 5, 1, 2),
nn.MaxPool2d(2),
nn.Conv2d(32, 32, 5, 1, 2),
nn.MaxPool2d(2),
nn.Conv2d(32,64,5,1,2),
nn.MaxPool2d(2),
nn.Flatten(),
nn.Linear(64 * 4 * 4, 64),
nn.Linear(64, 10)
)
def forward(self, x):
x = self.model(x)
return x
把图像放进神经网络后,即可得到处理后的图片,然后在通过以下优化器,来优化神经网络模型
# 优化器优化模型
optimizer.zero_grad()
loss.backward()
optimizer.step()
之后再拿原图与神经网络处理后的图片相比较,这行代码就是原图与神经网络处理的图片相同图片的总和数,然后再与总图片数相除,就得到成功识别的概率
accuracy = (outputs.argmax(1) == targets).sum(0)
可惜我写的神经网络太简单,太垃圾了,无论我怎么优化,训练了好几百次,成功率一直在66%左右,以下就是我写的源码
#准备数据集
import torchvision
from torch.utils.tensorboard import SummaryWriter
import torch
#准备数据集
from torch import nn
from torch.utils.data import DataLoader
import time
train_data = torchvision.datasets.CIFAR10("./dataset",train=True, transform=torchvision.transforms.ToTensor()
, download=True)
test_data = torchvision.datasets.CIFAR10("./dataset",train=False, transform=torchvision.transforms.ToTensor()
, download=True)
# length 长度
train_data_size = len(train_data)
test_data_size = len(test_data)
# 如果train_data_size=10, 训练数据集的长度为: 10
print("训练数据集的长度为:{}".format(train_data_size))
print("测试数据集的长度为:{}".format(test_data_size))
# 利用 DataLoader 来加载数据集
train_dataloader = DataLoader(train_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)
# 创建网络模型
class Tudui(nn.Module):
def __init__(self):
super(Tudui, self).__init__()
self.model = nn.Sequential(
nn.Conv2d(3, 32, 5, 1, 2),
nn.MaxPool2d(2),
nn.Conv2d(32, 32, 5, 1, 2),
nn.MaxPool2d(2),
nn.Conv2d(32,64,5,1,2),
nn.MaxPool2d(2),
nn.Flatten(),
nn.Linear(64 * 4 * 4, 64),
nn.Linear(64, 10)
)
def forward(self, x):
x = self.model(x)
return x
tudui = Tudui()
if torch.cuda.is_available():
tudui = tudui.cuda()
# 损失函数
loss_fn = nn.CrossEntropyLoss()
if torch.cuda.is_available():
loss_fn = loss_fn.cuda()
# 优化器
# learning_rate = 0.01
# 1 * (10)^(-2)
learning_rate = 1e-2
optimizer = torch.optim.SGD(tudui.parameters(), lr=learning_rate)
# 设置训练网络的一些参数
# 记录训练的次数
total_train_step = 0
# 记录测试的此时
total_test_step = 0
# 训练轮数
epoch = 1000
# 添加tensorboard
writer = SummaryWriter("./logs_train")
start_time = time.time()
for i in range(epoch):
print("-------------第{}轮训练开始--------------".format(i+1))
# 训练步骤开始
for data in train_dataloader:
imgs, targets = data
if torch.cuda.is_available():
imgs = imgs.cuda()
targets = targets.cuda()
outputs = tudui(imgs)
loss = loss_fn(outputs,targets)
# 优化器优化模型
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_train_step = total_train_step + 1
if total_train_step % 100 == 0:
end_time = time.time()
print(end_time - start_time)
print("训练次数:{},Loss:{}".format(total_train_step,loss.item()))
writer.add_scalar("train_loss", loss.item(), total_train_step)
# 测试步骤开始
total_test_loss = 0
total_accuracy = 0
with torch.no_grad():
for data in test_dataloader:
imgs, targets = data
if torch.cuda.is_available():
imgs = imgs.cuda()
targets = targets.cuda()
outputs = tudui(imgs)
loss = loss_fn(outputs, targets)
total_test_loss = total_test_loss + loss.item()
accuracy = (outputs.argmax(1) == targets).sum(0)
total_accuracy = total_accuracy + accuracy
print("整体测试集上的loss:{}".format(total_test_loss))
print("整体测试集上的正确率:{}".format(total_accuracy/test_data_size))
writer.add_scalar("test_data", total_test_loss,total_test_step)
writer.add_scalar("test_accuracy", total_accuracy/test_data_size,total_test_step)
total_test_step = total_test_step + 1
torch.save(tudui,"./model/weights{}.pth".format(i))
print("模型已保存")
writer.close()
然后下面是调用模型的代码
import torch
import torchvision
from PIL import Image
from torch import nn
from model import *
image_path = "./imgs/dog.jpg"
image = Image.open(image_path)
# print(image)
transfrom = torchvision.transforms.Compose([torchvision.transforms.Resize((32, 32)),
torchvision.transforms.ToTensor()])
image = transfrom(image)
image = image.cuda()
# print(image.shape)
model = torch.load("./model/weights999.pth")
# print(model)
image = torch.reshape(image, (1,3,32,32))
model.eval()
with torch.no_grad():
output = model(image)
print(output)
pred, idx = output.max(1)
print(pred.item())
# print(output.argmax(1).item())
if output.argmax(1).item() == 0:
print("airplane")
elif output.argmax(1).item() == 1:
print("automoblie")
elif output.argmax(1).item() == 2:
print("bird")
elif output.argmax(1).item() == 3:
print("cat")
elif output.argmax(1).item() == 4:
print("deer")
elif output.argmax(1).item() == 5:
print("dog")
elif output.argmax(1).item() == 6:
print("frog")
elif output.argmax(1).item() == 7:
print("horse")
elif output.argmax(1).item() == 8:
print("ship")
elif output.argmax(1).item() == 9:
print("truck")
# airplane,automoblie,bird,cat,deer,dog,frog,horse,ship,truck
效果太垃圾了我就不演示了,我给大家介绍一下yolov5目标检测吧,这个用的神经网络算法跟我的比不是一个量级的,但是他确实很厉害
我现在只会用目标检测,我把篮球的图片放到神经网络里面训练出模型,然后调用该模型,就不仅可以识别出这个篮球类型,还有这个物体在摄像头里面的坐标,然后通过opencv画框,画线即可。
这里我推荐使用的开发板是jetson nano,1k多左右就有,就有nvidia显卡,跑神经网络,深度学习,这个价位已经很不错了,
举个例子,上面的图片,可以得到物体的中心点,然后图片的中心点也是已知的,就可以知道物体中心点相对与图片中心点之间的(x,y)的差值,然后就可以把x,y的数据通过串口发送到主控板上面,就可以实现云台移动,智能车比赛的通过识别白线,黑线,然后修正方向。
同时还可以通过看框的大小,实现物体追踪,测距等功能。
这是我第一次发布博客,可能会有问题,还望指正