深度學習實戰筆記四:在自己處理的數據集上訓練CNN網絡並進行預測

#cnn 識別狗狗類別
#用類構造代碼
#dog圖片的訓練、保存
#預測以及結果輸出

import os
import numpy as np
from PIL import Image
from keras.models import Sequential
from keras.layers import Convolution2D,Flatten,MaxPooling2D,Dense,Activation
from keras.optimizers import Adam
from keras.utils import np_utils

class PreFile(object):#對數據進行預處理
  def __init__(self,DogType):
    self.FilePath = FilePath
    Self.DogType = DogType

  def FileReName(self):
    count=0
    for type in self.DogType:
      subfolder = os.listdir(self.FilePath+type)
      for subclass in subfolder:
        print('count_class:->>',count)
        print(subclass)
        print(self.FilePath+type+'/'+subclass) #打印圖片路徑以及名字
        os.rename(self.FilePath+type+'/'+subclass,self.FilePath+type+'/'+str(type_counter)+'_'+str(file_counter)+'.jpg')
      count+=1
    
  def FileResize(self,Width,Height,Output_folder):
    for type in self.DogType:
      print(type)
      files = os.listdir(self.FilePath+type)
      for i in files:
        img_open = Image.open(self.Path+type+'/'+i)
        conv_RGB = img_open.convert('RGB')#統一將所有圖片轉換成RGB格式
        new_img = conv_RGB.resize((Width,Height),Image.BILINEAR)
        new_img.save(os.path.join(Output_folder,os.path.basename(i)))


class Training(object):
  def __init__(self,batch_size,number_batch,categories,train_folder):
    self.batch_size = batch_size
    self.number_batch = number_batch
    self.categoried = categories
    self.train_folder = train_folder

  def read_train_image(self,filename):
    img = Image.open(self.train_folder+filename)
    return np.array(img)
  def train(self):
    train_img_list = [] #X_train
    train_label_list = [] #Y_train

    for file in os.listdir(self.train_folder):
      file_img_in_array = self.read_train_image(filename=file)
      train_img_list.append(file_img_in_array)
      train_label_list.append(int(file.split('_')[0]))
      print(file.split('_')[0])
     #網絡喫的是numpy數組,所以必須轉化
    train_img_list = np.array(train_img_list)
    train_label_list = np.array(train_label_list)

    train_label_list = np_utils.to_categorical(train_label_list,self.categoried)

    train_img_list = train_img_list.astype('float32')
    train_img_list/=255.0


    model = Sequential()

    #輸入是(100,100,3)
    #CNN layer 1st
    model.add(Convolution2D(
        input_shape=(100,100,3),
        filters = 32, #所以輸出應該是(100,100,32)
        kernel_size = (5,5),
        padding = 'same',
    ))

    model.add(Activation('relu'))
    model.add(MaxPooling2D(
        pool_size = (2,2),
        strides = (2,2),#所以輸出變成(50,50,32)
        padding = 'same'
    ))


     #CNN layer 2nd
    model.add(Convolution2D(
        filters = 64, #所以輸出應該是(50,50,64)
        kernel_size = (2,2),
        padding = 'same',
    ))

    model.add(Activation('relu'))
    model.add(MaxPooling2D(
        pool_size = (2,2),
        strides = (2,2),#所以輸出變成(25,25,64)
        padding = 'same'
    ))

    model.add(Flatten()) #降維打擊

    model.add(Dense(1024))

    model.add(Activation('relu'))

    model.add(Dense(512))
    model.add(Activation('relu'))

    model.add(Dense(self.categoried))
    model.add(Activation('softmax'))

    #添加優化器
    adam = Adam(lr=0.0001)

    #編譯
    model.compile(
        optimizer = adam,
        loss='categorical_crossentropy',
        metrics=['accuracy']
    )

    model.fit(
        x=train_img_list,
        y=train_label_list,
        epochs = self.number_batch,
        batch_size=self.batch_size,
        verbose = 1,
        #validation_data #如果有test數據
     
    )

    model.save('/content/drive/My Drive/app/dogfinder.h5')

def MAIN():
  DogType=['erha','demu','labuladuo','samoye']
  Train = Training(batch_size=128,number_batch=30,categories=4,train_folder='/content/drive/My Drive/app/my_image/DogRawTrain/')
  Train.train()

if __name__=="__main__":
  MAIN()



模型訓練結果:
在這裏插入圖片描述

預測

from keras.models import load_model #加載模型
import matplotlib.image as processimage #處理照片
import matplotlib.pyplot as plt #打印照片
import numpy as np 
from PIL import Image

class Prediction(object):
  #初始化函數
  def __init__(self,ModelFile,PredictFile,DogType,Width=100,Height=100):
    self.modelfile = ModelFile
    self.predict_file = PredictFile
    self.Width = Width
    self.Height = Height
    self.DogType = DogType
    

  def Predict(self):
    model = load_model(self.modelfile)
    #print('load model')
    image_open = Image.open(self.predict_file)
    #print('open image')
    conv_RGB = image_open.convert('RGB')
    
    new_img = conv_RGB.resize((self.Width,self.Height),Image.BILINEAR)
    new_img.save(self.predict_file)#覆蓋掉了原來的文件
    print('Image Resized')
    
    image= processimage.imread(self.predict_file)
    image_to_array = np.array(image)/255.0
    image_to_array = image_to_array.reshape(-1,100,100,3)
    print('Image2Array')
    prediction = model.predict(image_to_array)
    Final_Pred = [result.argmax() for result in prediction]
    print(prediction)
    print(Final_Pred)

    count = 0
    for i in prediction[0]:
      percent = '%.2f%%'%(i*100)
      print(self.DogType[count],'概率',percent)
      count+=1

DogType=['erha','demu','labuladuo','samoye']
Pred = Prediction(DogType=DogType,PredictFile='/content/drive/My Drive/app/my_image/DogRawTest/erha2.jpg',ModelFile='/content/drive/My Drive/app/dogfinder.h5')
Pred.Predict()

模型預測結果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章