垃圾图像分类 ResNet34 python
数据下载链接 https://pan.baidu.com/s/1wr3h2Wc720uqUeIroTCIJA百度网盘为您提供文件的网络备份、同步和分享服务。空间大、速度快、安全稳固,支持教育网加速,支持手机端。注册使用百度网盘即可享受免费存储空间https://pan.baidu.com/s/1wr3h2Wc720uqUeIroTCIJA
提取码:mqic
为什么要进行垃圾分类?
当废物处理不当 - 时,就会发生回收污染 - ,就像回收带有油的比萨盒(堆肥)一样。 或者当废物得到正确处理但未正确准备 - 时,例如回收未冲洗过的果酱罐。
污染是回收行业的一个巨大问题,可以通过自动化废物分类来缓解。 只是为了踢球,我想我会尝试制作一个图像分类器的原型来对垃圾和可回收物进行分类 - 这个分类器可以在光学分拣系统中得到应用。
构建图像分类器
在这个项目中,我将训练一个卷积神经网络,使用 fastai 库(构建在 PyTorch 上)将图像分类为
waste_types = ['hazardous_waste_dry_battery','hazardous_waste_expired_drugs','hazardous_waste_ointment','kitchen_waste_bone','kitchen_waste_eggshell','kitchen_waste_fish_bone','kitchen_waste_fruit_peel','kitchen_waste_meal','kitchen_waste_pulp','kitchen_waste_tea','kitchen_waste_vegetable','other_garbage_bamboo_chopsticks','other_garbage_cigarette','other_garbage_fast_food_box','other_garbage_flowerpot','other_garbage_soiled_plastic','other_garbage_toothpick','recyclables_anvil','recyclables_bag','recyclables_bottle','recyclables_can','recyclables_cardboard','recyclables_cosmetic_bottles','recyclables_drink_bottle','recyclables_edible_oil_barrel','recyclables_glass_cup','recyclables_metal_food_cans','recyclables_old_clothes','recyclables_paper_bags','recyclables_pillow','recyclables_plastic_bowl','recyclables_plastic_hanger','recyclables_plug_wire','recyclables_plush_toys','recyclables_pot','recyclables_powerbank','recyclables_seasoning_bottle','recyclables_shampoo_bottle','recyclables_shoes','recyclables_toys']
我的建模管道:
下载并提取图像
将图像组织到不同的文件夹中
训练模型
做出和评估测试预测
下一步
一些基本的准备
%reload_ext autoreload
%autoreload 2
%matplotlib inline%config InlineBackend.figure_format = 'retina'
from fastai.vision import *
from fastai.metrics import error_rate
from pathlib import Path
from glob2 import glob
from sklearn.metrics import confusion_matriximport pandas as pd
import numpy as np
import os
import zipfile as zf
import shutil
import re
import seaborn as sns
1. 提取数据
首先,我们需要提取“train.zip”的内容。
files = zf.ZipFile("dataset-resized.zip",'r')
files.extractall()
files.close()
解压缩后,数据集调整大小的文件夹有40个子文件夹:
os.listdir(os.path.join(os.getcwd(),"dataset-resized"))
2. 将图片整理到不同的文件夹中
现在我们已经提取了数据,我将按照 50-25-25 的比例将图像分成训练、验证和测试图像文件夹。 首先,我定义了一些有助于我快速构建它的函数。 如果你对构建数据集不感兴趣,则可以直接运行忽略它。
## helper functions #### splits indices for a folder into train, validation, and test indices with random sampling## input: folder path## output: train, valid, and test indices
def split_indices(folder,seed1,seed2): n = len(os.listdir(folder))full_set = list(range(1,n+1))## train indicesrandom.seed(seed1)train = random.sample(list(range(1,n+1)),int(.5*n))## tempremain = list(set(full_set)-set(train))## separate remaining into validation and testrandom.seed(seed2)valid = random.sample(remain,int(.5*len(remain)))test = list(set(remain)-set(valid))return(train,valid,test)## gets file names for a particular type of trash, given indices## input: waste category and indices## output: file names
def get_names(waste_type,indices):file_names = [waste_type+str(i)+".jpg" for i in indices]return(file_names) ## moves group of source files to another folder## input: list of source files and destination folder## no output
def move_files(source_files,destination_folder):for file in source_files:shutil.move(file,destination_folder)
之后训练集和验证集里面各有四十个文件夹
## paths will be train/cardboard, train/glass, etc...
subsets = ['train','valid']
waste_types = waste_types = ['hazardous_waste_dry_battery','hazardous_waste_expired_drugs','hazardous_waste_ointment','kitchen_waste_bone','kitchen_waste_eggshell','kitchen_waste_fish_bone','kitchen_waste_fruit_peel','kitchen_waste_meal','kitchen_waste_pulp','kitchen_waste_tea','kitchen_waste_vegetable','other_garbage_bamboo_chopsticks','other_garbage_cigarette','other_garbage_fast_food_box','other_garbage_flowerpot','other_garbage_soiled_plastic','other_garbage_toothpick','recyclables_anvil','recyclables_bag','recyclables_bottle','recyclables_can','recyclables_cardboard','recyclables_cosmetic_bottles','recyclables_drink_bottle','recyclables_edible_oil_barrel','recyclables_glass_cup','recyclables_metal_food_cans','recyclables_old_clothes','recyclables_paper_bags','recyclables_pillow','recyclables_plastic_bowl','recyclables_plastic_hanger','recyclables_plug_wire','recyclables_plush_toys','recyclables_pot','recyclables_powerbank','recyclables_seasoning_bottle','recyclables_shampoo_bottle','recyclables_shoes','recyclables_toys']## create destination folders for data subset and waste type
for subset in subsets:for waste_type in waste_types:folder = os.path.join('data',subset,waste_type)if not os.path.exists(folder):os.makedirs(folder)if not os.path.exists(os.path.join('data','test')):os.makedirs(os.path.join('data','test'))## move files to destination folders for each waste type
for waste_type in waste_types:source_folder = os.path.join('train',waste_type)train_ind, valid_ind, test_ind = split_indices(source_folder,1,1)## move source files to traintrain_names = get_names(waste_type,train_ind)train_source_files = [os.path.join(source_folder,name) for name in train_names]train_dest = "data/train/"+waste_typemove_files(train_source_files,train_dest)## move source files to validvalid_names = get_names(waste_type,valid_ind)valid_source_files = [os.path.join(source_folder,name) for name in valid_names]valid_dest = "data/valid/"+waste_typemove_files(valid_source_files,valid_dest)## move source files to testtest_names = get_names(waste_type,test_ind)test_source_files = [os.path.join(source_folder,name) for name in test_names]## I use data/test here because the images can be mixed upmove_files(test_source_files,"data/test")
为了可重复性,我将两个随机样本的种子设置为 1。 现在数据已经组织好,我们可以开始模型训练了。
## get a path to the folder with images
path = Path(os.getcwd())/"data"
path
out:PosixPath('/home/jupyter/data')
tfms = get_transforms(do_flip=True,flip_vert=True)
data = ImageDataBunch.from_folder(path,test="test",ds_tfms=tfms,bs=16)
data #可以把data打印出来看看
data.show_batch(rows=4,figsize=(10,8)) #显示图片
训练模型!
什么是resnet34?
残差神经网络是具有很多层的卷积神经网络 (CNN)。特别是,resnet34 是一个 34 层的 CNN,已经在 ImageNet 数据库上进行了预训练。预训练的 CNN 将在新的图像分类任务上表现得更好,因为它已经学习了一些视觉特征并且可以将这些知识转移(因此是转移学习)。
由于它们能够描述更多的复杂性,理论上深度神经网络在训练数据上应该比浅层网络表现得更好。但实际上,深度神经网络在经验上的表现往往比浅层神经网络差。
创建 Resnets 是为了使用一种称为快捷连接的黑客来规避这个故障。如果某个层中的某些节点具有次优值,则可以调整权重和偏差;如果一个节点是最优的(它的残差为 0),为什么不把它放在一边?仅根据需要对节点进行调整(当存在非零残差时)。
当需要调整时,快捷连接应用恒等函数将信息传递给后续层。这在可能的情况下缩短了神经网络,并允许 resnet 具有深层架构并表现得更像浅层神经网络。 resnet34中的34只是指层数。
Anand Saha 在这里给出了更深入的解释。
learn = create_cnn(data,models.resnet34,metrics=error_rate)
learn.model
learn.lr_find(start_lr=1e-6,end_lr=1e1)
learn.recorder.plot()
learn.fit_one_cycle(20,max_lr=5.13e-03)
我的模型运行了 20 个 epoch。 这种拟合方法的酷炫之处在于,学习率随着每个 epoch 的增长而降低,让我们越来越接近最佳状态。 在 8.6% 时,验证错误看起来非常好……让我们看看它在测试数据上的表现如何。
首先,我们可以看看哪些图像分类错误最多。
interp = ClassificationInterpretation.from_learner(learn)
losses,idxs = interp.top_losses()
interp.plot_top_losses(9, figsize=(15,11))
doc(interp.plot_top_losses)
interp.plot_confusion_matrix(figsize=(12,12), dpi=60)
interp.most_confused(min_val=2)
现在就到了最激动人心的时刻
4. 对测试数据做出新的预测
要了解这种模式的真正表现,我们需要对测试数据进行预测。 首先,我将使用 learner.get_preds() 方法对测试数据进行预测。
注意:learner.predict() 只对单个图像进行预测,而 learner.get_preds() 对一组图像进行预测。 我强烈建议阅读文档以了解有关 predict() 和 get_preds() 的更多信息。
preds = learn.get_preds(ds_type=DatasetType.Test)
get_preds(ds_type) 中的 ds_type 参数采用 DataSet 参数。 示例值为 DataSet.Train、DataSet.Valid 和 DataSet.Test。 我提到这一点是因为我错误地传入了实际数据 (learn.data.test_ds),这给了我错误的输出并且花了很长时间进行调试。 不要犯这个错误! 不要传入数据——传入数据集类型!
print(preds[0].shape)
preds[0]
结果就在yhat里面!
## saves the index (0 to 5) of most likely (max) predicted class for each image
max_idxs = np.asarray(np.argmax(preds[0],axis=1))yhat = []
for max_idx in max_idxs:yhat.append(data.classes[max_idx])
yhat
.....
recyclables_plush_toys kitchen_waste_eggshell recyclables_edible_oil_barrel hazardous_waste_expired_drugs kitchen_waste_eggshell recyclables_shoes recyclables_plug_wire kitchen_waste_vegetable recyclables_shoes recyclables_toys recyclables_seasoning_bottle recyclables_bag kitchen_waste_fruit_peel other_garbage_cigarette recyclables_can recyclables_anvil other_garbage_cigarette recyclables_shoes recyclables_paper_bags kitchen_waste_fish_bone other_garbage_bamboo_chopsticks other_garbage_bamboo_chopsticks other_garbage_flowerpot recyclables_bottle kitchen_waste_vegetable kitchen_waste_pulp recyclables_edible_oil_barrel recyclables_plastic_bowl other_garbage_fast_food_box recyclables_pot recyclables_cardboard recyclables_glass_cup recyclables_plastic_hanger recyclables_paper_bags recyclables_seasoning_bottle kitchen_waste_bone recyclables_seasoning_bottle recyclables_powerbank recyclables_drink_bottle kitchen_waste_fruit_peel recyclables_seasoning_bottle recyclables_powerbank recyclables_plush_toys recyclables_plush_toys recyclables_seasoning_bottle recyclables_bottle recyclables_edible_oil_barrel recyclables_edible_oil_barrel recyclables_plastic_bowl recyclables_metal_food_cans other_garbage_cigarette hazardous_waste_expired_drugs kitchen_waste_fish_bone recyclables_shoes kitchen_waste_pulp recyclables_plastic_bowl recyclables_powerbank
....
或者可以看另外两篇图像分类的
最简单的直接用训练好的模型
https://blog.csdn.net/long_songs/article/details/122095136https://blog.csdn.net/long_songs/article/details/122095136
猫狗图像分类:
CNN 猫狗图像分类_long_songs的博客-CSDN博客导入基本要的库import torchimport torch.nn as nnimport torch.nn.functional as Fimport torchvisionimport torchvision.datasets as dsetimport torchvision.transforms as transformsimport torch.optim as optimimport torchvision.models as modelsimpor...https://blog.csdn.net/long_songs/article/details/122104681?spm=1001.2014.3001.5501
垃圾图像分类 ResNet34 python相关推荐
- 基于卷积神经网络的垃圾图像分类算法
点击上方"小白学视觉",选择加"星标"或"置顶" 重磅干货,第一时间送达 垃圾分类作为资源回收利用的重要环节之一, 可以有效地提高资源回收利 ...
- 【洞幺邦】基于卷积神经网络的垃圾图像分类识别
摘要:随着社会的飞速发展,生活中产生的消耗废品日益剧增,如何更好地分类与回收这些"垃圾"已经成为了急需解决的问题.为了我国能够更好更快的建立健全城市垃圾分类处理制度以及方便人们对于 ...
- 毕业设计 opencv python 深度学习垃圾图像分类系统
文章目录 0 前言 课题简介 一.识别效果 二.实现 1.数据集 2.实现原理和方法 3.网络结构 最后 0 前言
- python是不是特别垃圾-11道Python最基本的面试题,不会好好反思吧!
分享给大家的11道Python面试题,好多小伙伴都很积极的去思考分析,给我留言的同学非常多,非常欣慰有这么多好学的小伙伴,大家一起学习,一起加油,把Python学好,今天我就把11道面试题细细解答一下 ...
- python是不是特别垃圾-深度解析Python垃圾回收机制(超级详细)
我们知道,目前的计算机都采用的是图灵机架构,其本质就是用一条无限长的纸带,对应今天的存储器.随后在工程学的推演中,逐渐出现了寄存器.易失性存储器(内存)以及永久性存储器(硬盘)等产品.由于不同的存储器 ...
- python清理垃圾_用Python自动清理系统垃圾,再也不用360安全卫士了
用Python自动清理系统垃圾,再也不用360安全卫士了 在Windows在安装和使用过程中都会产生相当多的垃圾文件,包括临时文件(如:.tmp.._mp)日志文件(.log).临时帮助文件(.gid ...
- 垃圾识别系统Python
介绍 垃圾识别系统,使用Python作为主要开发语言,基于深度学习TensorFlow框架,搭建卷积神经网络算法.并通过对5种垃圾数据集进行训练,最后得到一个识别精度较高的模型.并基于Django框架 ...
- 垃圾图像分类,街景图像识别!华为云AI主题赛火热招募中!
人工智能技术是将定义我们这个时代的转型技术, 但是要将AI技术成功落地应用,充满挑战性 为了帮助大家从入门到放弃(不是) 从理论到实际运用混元形意太极(也不是) 深度学习图像分类模型 华为云特别推出 ...
- python实现knn分类_KNN图像分类及Python实现
NN,Nearest Neighbor,最近邻 KNN,K-Nearest Neighbor,K最近邻 KNN分类的思路: 分类的过程其实是直接将测试集的每一个图片和训练集中的所有图片进行比较,计算距 ...
最新文章
- python 判断 图片是否相同
- C++面向对象程序设计的一些知识点(5)
- Python可视化:Seaborn(二)
- mac恢复iphone_免费下载:旧Mac和iPhone壁纸的令人震惊的完整档案
- osgi 如何引入包_OSGi Testsuite:引入类名过滤器
- springSecurity 登录以及用户账号密码解析原理
- OpenGL学习笔记:画点、直线和多边形(第二讲)
- PyQt4开发环境搭建指导
- 【修正补发】Scratch2exe-ch将sb2文件转换为exe文件
- Windows常见扩展名介绍
- 一致 先验分布 后验分布_先验分布、后验分布、似然估计这几个概念是什么意思,它们之间的关系是什么?...
- 大数据——把Kafka中的数据传输到HBase中
- SpringBoot集成支付平台
- 南京Uber优步司机奖励政策(1月18日~1月24日)
- Spring Cloud Netfilx Ribbon(负载均衡工具)
- Angular 项目的搭建步骤
- ROS 安装正常却没法启动
- pythonaccess系统_Win7(64位系统)中用Python连接access数据库(access2010)
- linux 中文小方块,debian系统中文显示方块数字字母及黑块问号的解决办法
- java蜘蛛纸牌课程设计_Java课程设计——蜘蛛纸牌
热门文章
- 解决方案模板(标题立问题简述)
- 一百个最有用的网站地址
- 解决multiple ‘X-Frame-Options‘ headers with conflicting values (‘DENY, SAMEORIGIN‘)
- pytorch实现 chatbot聊天机器人
- 反驳项立刚,运营商业绩增长就是因为5G商用向用户多收30多元
- Activiti详解与案例
- IEC60079-11 附录3电气间隙和爬电距离的计算
- Linux压缩|解压_CodingPark编程公园
- 企业的考勤管理系统应该具备哪些功能!
- 程序员该如何说话?做人?做事?