SHARE
TWEET

Untitled

a guest Nov 19th, 2019 89 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import numpy as np
  2. import tensorflow as tf
  3.  
  4. import keras
  5. from keras.models import Sequential
  6. from keras.layers import Conv2D, MaxPooling2D, AveragePooling2D
  7. from keras.layers import Dense, Activation, Dropout, Flatten
  8.  
  9. from keras.preprocessing import image
  10. from keras.preprocessing.image import ImageDataGenerator
  11.  
  12. import matplotlib.pyplot as plt
  13.  
  14. num_classes = 7
  15. batch_size = 256
  16. epochs = 25
  17.  
  18. with open("fer2013.csv") as f:
  19.     content = f.readlines()
  20.  
  21. lines = np.array(content)
  22.  
  23. num_of_instances = lines.size
  24. print("number of instances: ", num_of_instances)
  25. print("instance length: ", len(lines[0].split(",")[0].split(" ")))
  26.  
  27.  
  28. x_train, y_train, x_test, y_test = [], [], [], []
  29.  
  30. #----------------------------------
  31. #transfer train and test set data
  32.  
  33. for i in range(1, num_of_instances):
  34.     try:
  35.         emotion, img, usage = lines[i].split(",")
  36.  
  37.         val = img.split(" ")
  38.  
  39.         pixels = np.array(val, 'float32')
  40.  
  41.         emotion = keras.utils.to_categorical(emotion, num_classes)
  42.  
  43.         if 'Training' in usage:
  44.             y_train.append(emotion)
  45.             x_train.append(pixels)
  46.         elif 'PublicTest' in usage:
  47.             y_test.append(emotion)
  48.             x_test.append(pixels)
  49.  
  50.     except:
  51.         print("", end="")
  52.  
  53. #----------------------------------
  54. #data transformation for train and test sets
  55. x_train = np.array(x_train, 'float32')
  56. y_train = np.array(y_train, 'float32')
  57. x_test = np.array(x_test, 'float32')
  58. y_test = np.array(y_test, 'float32')
  59.  
  60. x_train /= 255
  61. x_test /= 255
  62.  
  63. x_train = x_train.reshape(x_train.shape[0], 48, 48, 1)
  64. x_train = x_train.astype('float32')
  65. x_test = x_test.reshape(x_test.shape[0], 48, 48, 1)
  66. x_test = x_test.astype('float32')
  67.  
  68. print(x_train.shape[0], 'train samples')
  69. print(x_test.shape[0], 'test samples')
  70.  
  71. #----------------------------------
  72. #construct CNN structure
  73.  
  74. model = Sequential()
  75.  
  76. #1st convolutional layer
  77. model.add(Conv2D(64, (5, 5), activation='relu', input_shape=(48, 48, 1)))
  78. model.add(MaxPooling2D(pool_size=(5, 5), strides=(2, 2)))
  79.  
  80. #2nd convolutional layer
  81. model.add(Conv2D(64, (3, 3), activation='relu'))
  82. model.add(Conv2D(64, (3, 3), activation='relu'))
  83. model.add(AveragePooling2D(pool_size=(3, 3), strides=(2, 2)))
  84.  
  85. #3rd convolutional layer
  86. model.add(Conv2D(64, (3, 3), activation='relu'))
  87. model.add(Conv2D(64, (3, 3), activation='relu'))
  88. model.add(AveragePooling2D(pool_size=(3, 3), strides=(2, 2)))
  89.  
  90. model.add(Flatten())
  91.  
  92. #fully connected neural networks
  93. model.add(Dense(1024, activation='relu'))
  94. model.add(Dropout(0.2))
  95. model.add(Dense(1024, activation='relu'))
  96. model.add(Dropout(0.2))
  97.  
  98. model.add(Dense(num_classes, activation='softmax'))
  99. #----------------------------------
  100. #batch process
  101.  
  102. gen = ImageDataGenerator()
  103. train_generator = gen.flow(x_train, y_train, batch_size=batch_size)
  104.  
  105. #----------------------------------
  106.  
  107. model.compile(loss='categorical_crossentropy'
  108.               , optimizer=keras.optimizers.Adam()
  109.               , metrics=['accuracy']
  110. )
  111.  
  112. #----------------------------------
  113.  
  114. fit = True
  115.  
  116. if fit == True:
  117.  
  118.     model.fit_generator(train_generator, steps_per_epoch=batch_size, epochs=epochs)
  119.  
  120. else:
  121.     model.load_weights('/data/facial_expression_model_weights.h5')
  122.  
  123. #----------------------------------
  124.  
  125. def emotion_analysis(emotions):
  126.     objects = ('angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral')
  127.     y_pos = np.arange(len(objects))
  128.  
  129.     plt.bar(y_pos, emotions, align='center', alpha=0.5)
  130.     plt.xticks(y_pos, objects)
  131.     plt.ylabel('percentage')
  132.     plt.title('emotion')
  133.  
  134.     plt.show()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top