机器学习—— 垃圾分类

垃圾分类

一、选题背景

现在随着人口数量的增多,产生了越来越多的垃圾。为了保护好我们居住的环境,我们应该学会垃圾分类,尽到垃圾分类的义务,做一名合格的公民。垃圾分类可以减少对环境的污染,还可以减少垃圾的占地面积,同时可以将回收的垃圾进行二次利用。减少垃圾产量之后不仅可以美化城市环境,而且还能对某些有价值的垃圾进行回收,能够减少资源的浪费,还可以减少二氧化碳的排放量。

二、机器学习案例设计方案

  1. 本次项目所用的数据集是从kaggo平台下载的,在dataset文件下有四个类别文件,是四个大类的垃圾分类的名称

数据集分为:训练图像集、训练标签集、测试图像集、测试标签集、

   2.本次采用的深度学习的框架是 Tensorflow

 

Tensorflow的简介:TensorFlow™是一个基于数据流编程dataflow programming)的符号数学系统,被广泛应用于各类机器学习machine learning)算法的编程实现,其前身是谷歌的神经网络算法库DistBelief [1]  

Tensorflow拥有多层级结构,可部署于各类服务器PC终端和网页并支持GPUTPU高性能数值计算,被广泛应用于谷歌内部的产品开发和各领域的科学研究 [1-2]  

TensorFlow由谷歌人工智能团队谷歌大脑Google Brain)开发和维护,拥有包括TensorFlow HubTensorFlow LiteTensorFlow Research Cloud在内的多个项目以及各类应用程序接口Application Programming Interface, API [2]  。自2015119日起,TensorFlow依据阿帕奇授权协议Apache 2.0 open source license开放源代码 [2]  

Keras是基于TensorFlowTheano(由加拿大蒙特利尔大学开发的机器学习框架)的深度学习库,是由纯python编写而成的高层神经网络API,也仅支持python开发。它是为了支持快速实践而对tensorflow或者Theano的再次封装,让我们可以不用关注过多的底层细节,能够把想法快速转换为结果。它也很灵活,且比较容易学。Keras默认的后端为tensorflow,如果想要使用theano可以自行更改。tensorflowtheano都可以使用GPU进行硬件加速,往往可以比CPU运算快很多倍。因此如果你的显卡支持cuda的话,建议尽可能利用cuda加速模型训练。(当机器上有可用的GPU时,代码会自动调用GPU 进行并行计算。)

Keras已经被TensorFlow收录,添加到TensorFlow 中,成为其默认的框架,成为TensorFlow官方的高级API

 

     3.本次涉及图像的处理,卷积神经网络的建造

 

三、深度学习的实现步骤

  1. 本次的目的是:实现电脑对垃圾进行分类
  2. 数据切分成四份

 

 

 

 

 

 

    3.因为深度学习的卷积比较适合做图像类的处理,所以本次选用卷积神经网络模型下面对一些必要的参数进行解释

 

 

 

    4.开始搭建卷积神经网络模型

 

 

 

 

    5.开始训练模型

 

 

 

 

    6.测试

      模型的准确率可以达到98%

 

 

四、总结

  1. 通过本次的学习,让我初步了解深度学习的强大之处,电脑的算力远远超过人的大脑,在接下来的社会发展中肯定是人工智能越来越发达,计算机以后会越来越帮助人们的生活
  2. 在本次的设计中我明白了,一个好的模型是要通过好就的训练,不断的调整参数来进行训练,训练的数据也会对模型的准确率有影响,我想到的改进方法就是用算力更高的计算机,用更多的数据集以及参数来训练

 

 

五、程序代码

  1 import cv2
  2 
  3 import os
  4 
  5 from keras.utils import np_utils
  6 
  7 import numpy as np
  8 
  9 #随机生成10个数
 10 
 11 np.random.seed(10)
 12 
 13 import random
 14 
 15 import sys
 16 
 17  
 18 
 19 # train_images表示训练图像数据;  train_labels代表是训练图像对应的标签;  test_images代表是测试图像数据;   test_labels代表测试图像对应的标签
 20 
 21  
 22 
 23  
 24 
 25 # 将其中90%的图像数据做训练集和测试集,将四个类别的数据随机打乱,让每一个类别的数据都可以做成训练集数据
 26 
 27 def makeTrainTestData(images, labels, trainRatio=0.9):
 28 
 29  
 30 
 31     c = list(zip(images, labels))
 32 
 33  
 34 
 35     random.shuffle(c)
 36 
 37  
 38 
 39     images, labels = zip(*c)
 40 
 41  
 42 
 43     train_num = int(trainRatio * len(images))
 44 
 45  
 46 
 47     train_images, train_labels = images[:train_num], labels[:train_num]
 48 
 49  
 50 
 51     test_images, test_labels = images[train_num:], labels[train_num:]
 52 
 53  
 54 
 55     return (np.array(train_images), np.array(train_labels)), (np.array(test_images), np.array(test_labels))
 56 
 57  
 58 
 59 # 读取图像集,将图像集做成训练集和测试集
 60 
 61  
 62 
 63 def readData(path=r"./dataset7/", trainRatio=0.9):
 64 
 65  
 66 
 67     images = []
 68 
 69  
 70 
 71     labels = []
 72 
 73  
 74 
 75     subdirs = os.listdir(path)
 76 
 77  
 78 
 79     subdirs.sort()
 80 
 81  
 82 
 83     print(subdirs)
 84 
 85  
 86 
 87     classes = len(subdirs)
 88 
 89  
 90 
 91 # 读取每一个类别的数据,具体到每一个照片
 92 
 93  
 94 
 95     for subdir in range(classes):
 96 
 97  
 98 
 99         for index in os.listdir(os.path.join(path, subdirs[subdir])):
100 
101  
102 
103             indexDir = os.path.join(path, subdirs[subdir], index)
104 
105  
106 
107             sys.stdout.flush()
108 
109  
110 
111             print("label --> dir : {} --> {}".format(subdirs[subdir], indexDir))
112 
113  
114 
115             for indexdir in os.listdir(indexDir):
116 
117  
118 
119                 image_path = os.path.join(indexDir, indexdir)
120 
121  
122 
123                 img = cv2.imread(image_path)
124 
125  
126 
127                 img = cv2.resize(img, dsize=(32, 32), interpolation=cv2.INTER_AREA)
128 
129  
130 
131                 images.append(img)
132 
133  
134 
135                 labels.append(subdir)
136 
137  
138 
139     (train_images, train_labels), (test_images, test_labels) = makeTrainTestData(images, labels)
140 
141  
142 
143     np.save("train_images.npy", train_images)
144 
145  
146 
147     np.save("test_images.npy", test_images)
148 
149  
150 
151     np.save("train_labels.npy", train_labels)
152 
153  
154 
155     np.save("test_labels.npy", test_labels)
156 
157  
158 
159     return (train_images, train_labels), (test_images, test_labels)
160 
161  
162 
163 # 保存的形式为npy文件
164 
165 try:
166 
167     train_images = np.load("train_images.npy")
168 
169  
170 
171     test_images = np.load("test_images.npy")
172 
173  
174 
175     train_labels = np.load("train_labels.npy")
176 
177  
178 
179     test_labels = np.load("test_labels.npy")
180 
181 except:
182 
183     (train_images, train_labels), (test_images, test_labels) = readData()
184 
185  
186 
187 print(train_images.shape)                                                                    #打印训练集数据的形状
188 
189  
190 
191 print(test_images.shape)                                                                     #打印测试集数据的形状
192 
193  
194 
195 print(train_labels.shape)
196 
197  
198 
199 print(test_labels.shape)
200 
201  
202 
203 # 将训练集数据和测试集数据进行归一化处理
204 
205 train_image_norm=train_images.astype('float32')/255
206 
207 test_image_norm=test_images.astype('float32')/255
208 
209  
210 
211 # 将训练集和测试集进行oneho编码
212 
213 train_labels_ohe=np_utils.to_categorical(train_labels)
214 
215 test_labels_ohe=np_utils.to_categorical(test_labels)
216 
217  
218 
219 print(train_labels[:10])
220 
221 print(test_labels_ohe[:10])
222 
223  
224 
225  
226 
227 import matplotlib.pyplot as plt
228 
229  
230 
231 def plot_image(image):
232 
233     fig=plt.gcf()
234 
235     fig.set_size_inches(2,2)
236 
237     plt.imshow(image)
238 
239     plt.show()
240 
241  
242 
243 for i in range(0,10):
244 
245     b,g,r = cv2.split(train_images[i])
246 
247     img_rgb=cv2.merge([r,g,b])
248 
249     plot_image(img_rgb)
250 
251     print(train_labels[i])
252 
253  
254 
255  
256 
257  
258 
259 from keras.models import Sequential
260 
261 from keras.layers import Conv2D,MaxPooling2D,ZeroPadding2D,Dropout
262 
263 from keras.layers import Flatten,Dense
264 
265 import tensorflow as tf
266 
267 import keras.backend as K
268 
269 from keras.callbacks import LearningRateScheduler
270 
271  
272 
273  
274 
275 # 这个就是建模形          这个是采用卷积神经网络(CNN)
276 
277 model=Sequential()
278 
279 model.add(Conv2D(filters=48,
280 
281                  kernel_size=(3,3),
282 
283                  input_shape=(32,32,3),
284 
285                  activation='relu',
286 
287                  padding='same'))
288 
289  
290 
291 model.add(Dropout(0.25))
292 
293  
294 
295 model.add(MaxPooling2D(pool_size=(2,2)))
296 
297  
298 
299 model.add(Conv2D(filters=64,
300 
301                  kernel_size=(3,3),
302 
303                  activation='relu',
304 
305                  padding='same'))
306 
307  
308 
309 model.add(Dropout(0.25))
310 
311  
312 
313 model.add(MaxPooling2D(pool_size=(2,2)))
314 
315  
316 
317 model.add(Flatten())
318 
319 model.add(Dropout(0.2))
320 
321  
322 
323 model.add(Dense(units=1000,activation='relu'))
324 
325  
326 
327 model.add(Dropout(0.2))
328 
329  
330 
331 model.add(Dense(units=4,activation='softmax'))
332 
333  
334 
335 model.summary()
336 
337  
338 
339  
340 
341 try:
342 
343     model.load_weights("CNNModel.h5")
344 
345     print('be ready')
346 
347 except:
348 
349     print("not prepare well")
350 
351  
352 
353  
354 
355 def scheduler(epoch):
356 
357  
358 
359     if epoch % 100 == 0 and epoch != 0:
360 
361  
362 
363         lr = K.get_value(model.optimizer.lr)
364 
365  
366 
367         K.set_value(model.optimizer.lr, lr * 0.01)
368 
369  
370 
371         print("lr changed to {}".format(lr * 0.01))
372 
373  
374 
375     return K.get_value(model.optimizer.lr)
376 
377  
378 
379 reduce_lr = LearningRateScheduler(scheduler)
380 
381  
382 
383 while True:
384 
385  
386 
387     model.compile(tf.keras.optimizers.Adam(lr=0.001),
388 
389  
390 
391                   loss="categorical_crossentropy",
392 
393                   metrics=['acc'])
394 
395     train_history = model.fit(x=train_image_norm,
396 
397                               y=train_labels_ohe,
398 
399                               validation_split=0.1,
400 
401 
402                               epochs=10,
403 
404                               batch_size=64,
405 
406                               verbose=1,
407 
408                              callbacks=[reduce_lr])
409 
410     results = model.evaluate(test_image_norm, test_labels_ohe)
411 
412     print('accuracy=', results[1])
413 
414     if results[1] >= 0.97:
415 
416         model.save_weights("CNNModel.h5")
417 
418         print("Save the newly trained model")
419 
420         break
421 
422  
423 
424 # 验证这个模型的准确率是多少,用上面10%的数据作为验证数据来检验
425 
426 model.compile(loss="categorical_crossentropy",optimizer='adam',
427 
428 metrics=['accuracy'])
429 
430 
431 results=model.evaluate(test_image_norm,test_labels_ohe)
432 
433 print('accuracy=',results[1])
434 
435  
436 
437 print(str(reduce_lr))

 

posted @ 2022-12-24 16:58  泉信软工2班张论楷  阅读(338)  评论(0编辑  收藏  举报