深度学习之昆虫种类识别

源代码:

#导入所需的包
import os
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from keras import layers
from keras import models
from keras import optimizers
plt.rcParams['font.sans-serif'] = ['SimHei']#图片数据集可通过百度爬虫爬取(简单粗暴)
# 导入图片数据
# 蝗虫图片
filedir = 'data/HC'
file_list1 = []
for root, dirs, files in os.walk(filedir):for file in files:if os.path.splitext(file)[1] == ".jpg":file_list1.append(os.path.join(root + '/', file))
# 批量改变图片像素
for filename in file_list1:try:im = Image.open(filename)im = im.convert('RGB')new_im = im.resize((128, 128))save_name = 'data/HC_128/' + filename[11:]new_im.save(save_name)except OSError as e:print(e.args)
# 重新建立新图像列表
filedir = 'data/HC_128'
file_list_1 = []
for root, dirs, files in os.walk(filedir):for file in files:if os.path.splitext(file)[1] == ".jpg":file_list_1.append(os.path.join(root + '/', file))
# 蚜虫图片
filedir = 'data/YC'
file_list2 = []
for root, dirs, files in os.walk(filedir):for file in files:if os.path.splitext(file)[1] == ".jpg":file_list2.append(os.path.join(root + '/', file))# 批量改变图片像素
for filename in file_list2:try:im = Image.open(filename)im = im.convert('RGB')new_im = im.resize((128, 128))save_name = 'data/YC_128/' + filename[11:]new_im.save(save_name)except OSError as e:print(e.args)
# 重新建立新图像列表
filedir = 'data/YC_128'
os.listdir(filedir)file_list_2 = []
for root, dirs, files in os.walk(filedir):for file in files:if os.path.splitext(file)[1] == ".jpg":file_list_2.append(os.path.join(root + '/', file))# 合并列表数据
file_list_all = file_list_1 + file_list_2
# 将图片转换为数组
M = []
for filename in file_list_all:im = Image.open(filename)width, height = im.sizeim_L = im.convert("L")Core = im_L.getdata()arr1 = np.array(Core, dtype='float32') / 255.0# arr1.shapelist_img = arr1.tolist()M.extend(list_img)
x = np.array(M).reshape(len(file_list_all), width, height)
print(x.shape)
#设置图像标签
class_name = ['蝗虫', '蚜虫']
# 用字典存储图像信息
dict_label = {0: '蝗虫', 1: '蚜虫'}
print(dict_label[0])
print(dict_label[1])
# 用列表输入标签,0表示蝗虫,1表示蚜虫
label = [0] * len(file_list_1) + [1] * len(file_list_2)
y = np.array(label)
# 按照4:1的比例将数据集划分为训练集和测试集
train_images, test_imgages, train_labels, test_labels = train_test_split(x, y, test_size=0.2, random_state=0)
# 显示一张图片
plt.figure()
plt.imshow(train_images[1])
plt.show()#显示前30张图片
'''
plt.figure(figsize=(10,10))
for i in range(30):plt.subplot(5,6,i+1)plt.xticks([])plt.yticks([])plt.grid(False)plt.imshow(train_images[i])plt.xlabel(class_name[train_labels[i]])
plt.show()
'''#构造神经网络并训练模型
model = models.Sequential()
model.add(layers.Flatten(input_shape=(128,128)))
model.add(layers.Dense(64,activation='relu'))
model.add(layers.Dense(64,activation='relu'))
model.add(layers.Dense(2,activation='softmax'))model.compile(optimizer = optimizers.RMSprop(lr=1e-4),loss = 'sparse_categorical_crossentropy',metrics = ['acc'])history = model.fit(train_images,train_labels, epochs = 100)
history1 = model.fit(test_imgages,test_labels, epochs = 100)
test_loss,test_acc = model.evaluate(test_imgages,test_labels)
print('Test acc:',test_acc)
print(model.summary())#绘制训练精度和训练损失
acc = history.history['acc']
loss = history.history['loss']
epochs = range(1,len(acc)+1)
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.title('Training  accuracy')
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.title('Training  loss')
plt.legend()
plt.show()
#绘制测试精度和测试损失
acc = history1.history['acc']
loss = history1.history['loss']
epochs = range(1,len(acc)+1)
plt.plot(epochs, acc, 'bo', label='Test acc')
plt.title('Test  accuracy')
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'bo', label='Test loss')
plt.title('Test  loss')
plt.legend()
plt.show()#预测一个图像
pre = model.predict(test_imgages)
print(dict_label[np.argmax(pre[1])])#定义画图函数
def plot_image(i,pre_array,true_label,img):pre_array,true_label,img = pre_array[i],true_label[i],img[i]plt.grid(False)plt.xticks([])plt.yticks([])plt.imshow(img)pre_label = np.argmax(pre_array)if pre_label == true_label:color = '#00bc57'else:color = 'red'   plt.xlabel("{} {:2.0f}% ({})".format(class_name[pre_label],100*np.max(pre_array),                                  class_name[true_label]),color= color )def plot_value_array(i,pre_array,true_label):pre_array,true_label = pre_array[i],true_label[i]plt.grid(False)plt.xticks([])plt.yticks([])thisplot = plt.bar(range(len(class_name)),pre_array,color = '#FF7F0E',width = 0.2 )   plt.ylim([0,1])pre_label = np.argmax(pre_array)thisplot[pre_label].set_color('red')thisplot[true_label].set_color('#00bc57')#查看预测图像的真实标签和预测标签
i=5
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i,pre,test_labels,test_imgages)
plt.subplot(1,2,2)
plot_value_array(i,pre,test_labels)
plt.show()

运行结果截图:


代码还有待改善,持续更新新中······

深度学习之昆虫种类识别相关推荐

  1. 中科院DeepMind联手,用深度学习揭示大脑如何识别人脸|Nature子刊

    点击上方"视学算法",选择加"星标"或"置顶" 重磅干货,第一时间送达 梦晨 发自 凹非寺 量子位 报道 | 公众号 QbitAI Deep ...

  2. DeepEye:一个基于深度学习的程序化交易识别与分类方法

    DeepEye:一个基于深度学习的程序化交易识别与分类方法 徐广斌,张伟 上海证券交易所资本市场研究所,上海 200120  上海证券交易所产品创新中心,上海 200120    摘要:基于沪市A股交 ...

  3. 《基于深度学习的加密流量识别研究》-2022毕设笔记

    参考文献: 基于深度学习的网络流量分类及异常检测方法研究_王伟 基于深度学习的加密流量分类技术研究与实现_马梦叠 基于深度学习的加密流量识别研究综述及展望_郭宇斌 基于深度学习的加密流量算法识别研究_ ...

  4. 基于深度学习的犬种识别软件(YOLOv5清新界面版,Python代码)

    摘要:基于深度学习的犬种识别软件用于识别常见多个犬品种,基于YOLOv5算法检测犬种,并通过界面显示记录和管理,智能辅助人们辨别犬种.本文详细介绍博主自主开发的犬种检测系统,在介绍算法原理的同时,给出 ...

  5. 浙江大学《深度学习与行人重识别》课程课件

    点击上方,选择星标或置顶,不定期资源大放送! 阅读大概需要3分钟 Follow小博主,每天更新前沿干货 课程介绍 该课程为浙江大学罗浩博士于2018年10月录制的<基于深度学习和行人重识别> ...

  6. 【深度学习】DIY 人脸识别技术的探索(一)

    [深度学习]DIY 人脸识别技术的探索(一) 文章目录 摘要 问题重述 模型假设 定义与符号说明 问题分析 模型的建立与求解 参考 摘要 伴随着人工智能技术的发展,人们对信息安全有了更高的要求,传统的 ...

  7. 【深度学习】DIY 人脸识别技术的探索(二)

    [深度学习]DIY 人脸识别技术的探索(二) 文章目录 训练模型 工具 结果展示 问题二的模型建立与求解 基于 KNN 的人脸识别模型 训练模型 MTCNN 可以并行训练(3 个网络同时训练,前提是内 ...

  8. 蚂蚁金服张洁:基于深度学习的支付宝人脸识别技术解秘-1

    蚂蚁金服张洁:基于深度学习的支付宝人脸识别技术解秘(1) 2015-08-13 10:22 于雪 51CTO 字号:T | T 用户身份认证是互联网金融发展的基石.今年三月,在德国汉诺威举办的IT展览 ...

  9. Nature论文解读:深度学习助力毫秒之间识别癌细胞

    论文动机 流式细胞仪作为一种生物医学诊断技术,可以准确测量细胞特性.当前仪器已经实现了细胞的分类识别,但由于数据处理耗时的问题,尚不能对细胞进行实时分选. 基于之前的工作,本文作者提出采用深度学习来解 ...

最新文章

  1. Django实战教程 分页列表
  2. Java使用Tomcat数据源的方式
  3. 文件共享服务器第二部,第二章-构建Samba文件共享服务器.docx
  4. tutte定理证明hall定理_深入浅出|中心极限定理(Central Limit Theorem)及证明
  5. 从最年轻的白手起家富豪到身陷囹圄,这个80后创始人也就用了3年
  6. (转)教你记住ASP.NET WebForm页面的生命周期
  7. 远程桌面提示RPC不可用
  8. 变量的语法扩展(JS)
  9. 华为ensp(telnet)实验
  10. LCD驱动芯片HT16c21使用注意事项
  11. Mac/Linux 安装ab(Apache Benchmark)
  12. UIAlertView/UIAlertController封装使用
  13. iframe自动播放
  14. 《地球信息科学学报》发表宋关福博士论文:当GIS遇到人工智能
  15. 35岁不是程序员职场中的绊脚石
  16. python给女朋友_Python 给女朋友道歉的一天
  17. 若依 监控中心monitor的使用
  18. 人工智能技术的应用越来越广,极大促进了无人机产业的发展
  19. jar包冲突的解决,依赖树的打印与分析
  20. Instruments使用

热门文章

  1. operator*() 和 operator-()
  2. 互联网文艺复兴者——互联网之父Vinton G. Cerf
  3. 跨境电商一周要闻:蜜淘获B轮$3000万融资
  4. jmeter循环和计数器
  5. JSP中获取项目根目录
  6. centos7 离线安装docker和docker-compose
  7. @Cacheable 设置缓存过期时间
  8. 爱因斯坦 《社会与个人》
  9. 产品经理基础入门课程
  10. 好用的录音机软件有哪些?这些软件值得收藏