百度飞桨七日深度学习手势识别

2024-04-25 06:32

本文主要是介绍百度飞桨七日深度学习手势识别,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

百度飞桨七日深度学习手势识别,paddlepaddle免费GPU算力,以及很好的封装,对初学者灰常友好~~~~。

下面是其中的手势识别作业,采用LeNet网络,初步感受了调参的魅力(雾😄),激发了学习理论的决心。

# 查看当前挂载的数据集目录, 该目录下的变更重启环境后会自动还原
# View dataset directory. This directory will be recovered automatically after resetting environment. 
!ls /home/aistudio/data
# 查看工作区文件, 该目录下的变更将会持久保存. 请及时清理不必要的文件, 避免加载过慢.
# View personal work directory. All changes under this directory will be kept even after reset. Please clean unnecessary files in time to speed up environment loading.
!ls /home/aistudio/work

!cd /home/aistudio/data/data23668 && unzip -qo Dataset.zip
!cd /home/aistudio/data/data23668/Dataset && rm -f */.DS_Store # 删除无关文件 
import os
import time
import random
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import paddle
import paddle.fluid as fluid
import paddle.fluid.layers as layers
from multiprocessing import cpu_count
from paddle.fluid.dygraph import Pool2D,Conv2D
from paddle.fluid.dygraph import Linear

# 生成图像列表
data_path = '/home/aistudio/data/data23668/Dataset'
character_folders = os.listdir(data_path)
# print(character_folders)
if(os.path.exists('./train_data.list')):os.remove('./train_data.list')
if(os.path.exists('./test_data.list')):os.remove('./test_data.list')for character_folder in character_folders:with open('./train_data.list', 'a') as f_train:with open('./test_data.list', 'a') as f_test:if character_folder == '.DS_Store':continuecharacter_imgs = os.listdir(os.path.join(data_path,character_folder))count = 0 for img in character_imgs:if img =='.DS_Store':continueif count%10 == 0:f_test.write(os.path.join(data_path,character_folder,img) + '\t' + character_folder + '\n')else:f_train.write(os.path.join(data_path,character_folder,img) + '\t' + character_folder + '\n')count +=1
print('列表已生成')
# 定义训练集和测试集的reader
def data_mapper(sample):img, label = sampleimg = Image.open(img)img = img.resize((100, 100), Image.ANTIALIAS)img = np.array(img).astype('float32')img = img.transpose((2, 0, 1))img = img/255.0return img, labeldef data_reader(data_list_path):def reader():with open(data_list_path, 'r') as f:lines = f.readlines()for line in lines:img, label = line.split('\t')yield img, int(label)return paddle.reader.xmap_readers(data_mapper, reader, cpu_count(), 512)
# 用于训练的数据提供器
train_reader = paddle.batch(reader=paddle.reader.shuffle(reader=data_reader('./train_data.list'), buf_size=256), batch_size=32)
# 用于测试的数据提供器
test_reader = paddle.batch(reader=data_reader('./test_data.list'), batch_size=32) 
#定义LeNet网络
class LeNet(fluid.dygraph.Layer):def __init__(self, training= True):super(LeNet, self).__init__()self.conv1 = Conv2D(num_channels=3, num_filters=32, filter_size=3, act='relu')self.pool1 = Pool2D(pool_size=2, pool_stride=2)self.conv2 = Conv2D(num_channels=32, num_filters=32, filter_size=3, act='relu')self.pool2 = Pool2D(pool_size=2, pool_stride=2)self.conv3 = Conv2D(num_channels=32, num_filters=64, filter_size=3, act='relu')self.pool3 = Pool2D(pool_size=2, pool_stride=2)#self.conv4 = Conv2D(num_channels=32, num_filters=64, filter_size=3, act='relu')#self.pool4 = Pool2D(pool_size=2, pool_stride=2)self.fc1 = Linear(input_dim=6400, output_dim=4096, act='relu')self.drop_ratiol = 0.5 if training else 0.0self.fc2 = Linear(input_dim=4096, output_dim=10)def forward(self, inputs):conv1 = self.conv1(inputs)  # 32 32 98 98pool1 = self.pool1(conv1)  # 32 32 49 49conv2 = self.conv2(pool1)  # 32 32 47 47pool2 = self.pool2(conv2)  # 32 32 23 23conv3 = self.conv3(pool2)  # 32 64 21 21pool3 = self.pool3(conv3)  # 32 64 10 10#conv4 = self.conv4(pool3)  # 32 64 21 21#pool4 = self.pool4(conv4)  # 32 64 10 10rs_1 = fluid.layers.reshape(pool3, [pool3.shape[0], -1])fc1 = self.fc1(rs_1)drop1 = fluid.layers.dropout(fc1, self.drop_ratiol)y = self.fc2(drop1)return y
```python#用动态图进行训练
with fluid.dygraph.guard():model=MyDNN() #模型实例化model.train() #训练模式opt=fluid.optimizer.SGDOptimizer(learning_rate=0.01, parameter_list=model.parameters())#优化器选用SGD随机梯度下降,学习率为0.001.epochs_num=20 #迭代次数for pass_num in range(epochs_num):for batch_id,data in enumerate(train_reader()):images=np.array([x[0].reshape(3,100,100) for x in data],np.float32)labels = np.array([x[1] for x in data]).astype('int64')labels = labels[:, np.newaxis]# print(images.shape)image=fluid.dygraph.to_variable(images)label=fluid.dygraph.to_variable(labels)predict=model(image)#预测# print(predict)loss=fluid.layers.cross_entropy(predict,label)avg_loss=fluid.layers.mean(loss)#获取loss值acc=fluid.layers.accuracy(predict,label)#计算精度if batch_id!=0 and batch_id%50==0:print("train_pass:{},batch_id:{},train_loss:{},train_acc:{}".format(pass_num,batch_id,avg_loss.numpy(),acc.numpy()))avg_loss.backward()opt.minimize(avg_loss)model.clear_gradients()fluid.save_dygraph(model.state_dict(),'MyDNN')#保存模型
#模型校验
with fluid.dygraph.guard():accs = []model_dict, _ = fluid.load_dygraph('MyDNN')model = MyDNN()model.load_dict(model_dict) #加载模型参数model.eval() #训练模式for batch_id,data in enumerate(test_reader()):#测试集images=np.array([x[0].reshape(3,100,100) for x in data],np.float32)labels = np.array([x[1] for x in data]).astype('int64')labels = labels[:, np.newaxis]image=fluid.dygraph.to_variable(images)label=fluid.dygraph.to_variable(labels)predict=model(image)       acc=fluid.layers.accuracy(predict,label)accs.append(acc.numpy()[0])avg_acc = np.mean(accs)print(avg_acc)
#读取预测图像,进行预测def load_image(path):img = Image.open(path)img = img.resize((100, 100), Image.ANTIALIAS)img = np.array(img).astype('float32')img = img.transpose((2, 0, 1))img = img/255.0print(img.shape)return img#构建预测动态图过程
with fluid.dygraph.guard():infer_path = '手势.JPG'model=MyDNN()#模型实例化model_dict,_=fluid.load_dygraph('MyDNN')model.load_dict(model_dict)#加载模型参数model.eval()#评估模式infer_img = load_image(infer_path)infer_img=np.array(infer_img).astype('float32')infer_img=infer_img[np.newaxis,:, : ,:]infer_img = fluid.dygraph.to_variable(infer_img)result=model(infer_img)display(Image.open('手势.JPG'))print(np.argmax(result.numpy()))

这篇关于百度飞桨七日深度学习手势识别的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/933921

相关文章

深度解析Java DTO(最新推荐)

《深度解析JavaDTO(最新推荐)》DTO(DataTransferObject)是一种用于在不同层(如Controller层、Service层)之间传输数据的对象设计模式,其核心目的是封装数据,... 目录一、什么是DTO?DTO的核心特点:二、为什么需要DTO?(对比Entity)三、实际应用场景解析

深度解析Java项目中包和包之间的联系

《深度解析Java项目中包和包之间的联系》文章浏览阅读850次,点赞13次,收藏8次。本文详细介绍了Java分层架构中的几个关键包:DTO、Controller、Service和Mapper。_jav... 目录前言一、各大包1.DTO1.1、DTO的核心用途1.2. DTO与实体类(Entity)的区别1

深度解析Python装饰器常见用法与进阶技巧

《深度解析Python装饰器常见用法与进阶技巧》Python装饰器(Decorator)是提升代码可读性与复用性的强大工具,本文将深入解析Python装饰器的原理,常见用法,进阶技巧与最佳实践,希望可... 目录装饰器的基本原理函数装饰器的常见用法带参数的装饰器类装饰器与方法装饰器装饰器的嵌套与组合进阶技巧

深度解析Spring Boot拦截器Interceptor与过滤器Filter的区别与实战指南

《深度解析SpringBoot拦截器Interceptor与过滤器Filter的区别与实战指南》本文深度解析SpringBoot中拦截器与过滤器的区别,涵盖执行顺序、依赖关系、异常处理等核心差异,并... 目录Spring Boot拦截器(Interceptor)与过滤器(Filter)深度解析:区别、实现

深度解析Spring AOP @Aspect 原理、实战与最佳实践教程

《深度解析SpringAOP@Aspect原理、实战与最佳实践教程》文章系统讲解了SpringAOP核心概念、实现方式及原理,涵盖横切关注点分离、代理机制(JDK/CGLIB)、切入点类型、性能... 目录1. @ASPect 核心概念1.1 AOP 编程范式1.2 @Aspect 关键特性2. 完整代码实

SpringBoot开发中十大常见陷阱深度解析与避坑指南

《SpringBoot开发中十大常见陷阱深度解析与避坑指南》在SpringBoot的开发过程中,即使是经验丰富的开发者也难免会遇到各种棘手的问题,本文将针对SpringBoot开发中十大常见的“坑... 目录引言一、配置总出错?是不是同时用了.properties和.yml?二、换个位置配置就失效?搞清楚加

Python中图片与PDF识别文本(OCR)的全面指南

《Python中图片与PDF识别文本(OCR)的全面指南》在数据爆炸时代,80%的企业数据以非结构化形式存在,其中PDF和图像是最主要的载体,本文将深入探索Python中OCR技术如何将这些数字纸张转... 目录一、OCR技术核心原理二、python图像识别四大工具库1. Pytesseract - 经典O

Python基于微信OCR引擎实现高效图片文字识别

《Python基于微信OCR引擎实现高效图片文字识别》这篇文章主要为大家详细介绍了一款基于微信OCR引擎的图片文字识别桌面应用开发全过程,可以实现从图片拖拽识别到文字提取,感兴趣的小伙伴可以跟随小编一... 目录一、项目概述1.1 开发背景1.2 技术选型1.3 核心优势二、功能详解2.1 核心功能模块2.

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

Python中文件读取操作漏洞深度解析与防护指南

《Python中文件读取操作漏洞深度解析与防护指南》在Web应用开发中,文件操作是最基础也最危险的功能之一,这篇文章将全面剖析Python环境中常见的文件读取漏洞类型,成因及防护方案,感兴趣的小伙伴可... 目录引言一、静态资源处理中的路径穿越漏洞1.1 典型漏洞场景1.2 os.path.join()的陷