人臉表情識別 深度神經網絡 python實現 簡單模型 fer2013數據集
阿新 • • 發佈:2019-05-09
lib [1] clas nbsp ces ini batch 類別 rep
參考網址:https://sefiks.com/2018/01/01/facial-expression-recognition-with-keras/
1.數據集介紹及處理:
(1) 數據集Fer2013下載地址為:https://www.kaggle.com/c/challenges-in-representation-learning-facial-expression-recognition-challenge/data
該數據集中每張圖片的像素為48*48,該數據集用excel讀取後顯示的格式如下圖所示:
第一列為標簽(也即為什麽表情),第二列為像素值,第三列是代表該圖片是訓練集還是測試集,已經給你打亂了。只需要用即可
(2)pandas讀取數據集
import numpy as np import pandas as pd data = pd.read_csv(‘data/fer2013/fer2013.csv‘) num_of_instances = len(data) #獲取數據集的數量 print("數據集的數量為:",num_of_instances) pixels = data[‘pixels‘] emotions = data[‘emotion‘] usages = data[‘Usage‘]
(3)分離訓練集和測試集
num_classes = 7 #表情的類別數目 x_train,y_train,x_test,y_test = [],[],[],[] for emotion,img,usage in zip(emotions,pixels,usages): try: emotion = keras.utils.to_categorical(emotion,num_classes) # 獨熱向量編碼 val = img.split(" ") pixels = np.array(val,‘float32‘) if(usage == ‘Training‘): x_train.append(pixels) y_train.append(emotion) elif(usage == ‘PublicTest‘): x_test.append(pixels) y_test.append(emotion) except: print("",end="")
(4)把數據集轉換為numpy數組格式,方便後續處理
x_train = np.array(x_train) y_train = np.array(y_train) x_train = x_train.reshape(-1,48,48,1) x_test = np.array(x_test) y_test = np.array(y_test) x_test = x_test.reshape(-1,48,48,1)
(5)顯示其中的前4張圖片
import matplotlib.pyplot as plt %matplotlib inline for i in range(4): plt.subplot(221+i) plt.gray() plt.imshow(x_train[i].reshape([48,48]))
2. 創建網絡 進行訓練和測試
from keras.models import Sequential from keras.layers import Conv2D,MaxPool2D,Activation,Dropout,Flatten,Dense from keras.optimizers import Adam from keras.preprocessing.image import ImageDataGenerator batch_size = 8 epochs = 20 model = Sequential() #第一層卷積層 model.add(Conv2D(input_shape=(48,48,1),filters=32,kernel_size=3,padding=‘same‘,activation=‘relu‘)) model.add(Conv2D(filters=32,kernel_size=3,padding=‘same‘,activation=‘relu‘)) model.add(MaxPool2D(pool_size=2, strides=2)) #第二層卷積層 model.add(Conv2D(filters=64,kernel_size=3,padding=‘same‘,activation=‘relu‘)) model.add(Conv2D(filters=64,kernel_size=3,padding=‘same‘,activation=‘relu‘)) model.add(MaxPool2D(pool_size=2, strides=2)) #第三層卷積層 model.add(Conv2D(filters=128,kernel_size=3,padding=‘same‘,activation=‘relu‘)) model.add(Conv2D(filters=128,kernel_size=3,padding=‘same‘,activation=‘relu‘)) model.add(MaxPool2D(pool_size=2, strides=2)) model.add(Flatten()) #全連接層 model.add(Dense(64,activation = ‘relu‘)) model.add(Dropout(0.5)) model.add(Dense(7,activation = ‘softmax‘)) #進行訓練 model.compile(loss = ‘categorical_crossentropy‘,optimizer = Adam(),metrics=[‘accuracy‘]) model.fit(x_train,y_train,batch_size=batch_size,epochs=epochs) train_score = model.evaluate(x_train, y_train, verbose=0) print(‘Train loss:‘, train_score[0]) print(‘Train accuracy:‘, 100*train_score[1]) test_score = model.evaluate(x_test, y_test, verbose=0) print(‘Test loss:‘, test_score[0]) print(‘Test accuracy:‘, 100*test_score[1])
這是一種通用識別架構,由於我的電腦配置不行,程序正在訓練,不再貼運行結果。可自行修改網絡架構。
程序中需要註意的地方:同時遍歷多個數組或列表時,可用zip()函數進行遍歷。
人臉表情識別 深度神經網絡 python實現 簡單模型 fer2013數據集