a b/Models/main-DNN.py
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
4
# Import useful packages
5
from __future__ import absolute_import
6
from __future__ import print_function
7
from __future__ import division
8
9
# Hide the Configuration and Warnings
10
import os
11
os.environ["TF_CPP_MIN_LOG_LEVEL"] = '3'
12
13
import random
14
import numpy as np
15
import tensorflow as tf
16
from Models.DatasetAPI.DataLoader import DatasetLoader
17
from Models.Network.DNN import DNN
18
from Models.Loss_Function.Loss import loss
19
from Models.Evaluation_Metrics.Metrics import evaluation
20
21
# Model Name
22
Model = 'Deep_Neural_Network'
23
24
# Clear all the stack and use GPU resources as much as possible
25
tf.reset_default_graph()
26
config = tf.ConfigProto()
27
config.gpu_options.allow_growth = True
28
sess = tf.Session(config=config)
29
30
# Your Dataset Location, for example EEG-Motor-Movement-Imagery-Dataset
31
# The CSV file should be named as training_set.csv, training_label.csv, test_set.csv, and test_label.csv
32
DIR = 'DatasetAPI/EEG-Motor-Movement-Imagery-Dataset/'
33
SAVE = 'Saved_Files/' + Model + '/'
34
if not os.path.exists(SAVE):  # If the SAVE folder doesn't exist, create one
35
    os.mkdir(SAVE)
36
37
# Load the dataset, here it uses one-hot representation for labels
38
train_data, train_labels, test_data, test_labels = DatasetLoader(DIR=DIR)
39
train_labels = tf.one_hot(indices=train_labels, depth=4)
40
train_labels = tf.squeeze(train_labels).eval(session=sess)
41
test_labels = tf.one_hot(indices=test_labels, depth=4)
42
test_labels = tf.squeeze(test_labels).eval(session=sess)
43
44
# Model Hyper-parameters
45
n_class   = 4     # The number of classification classes
46
n_hidden  = 64    # The number of hidden units in the first fully-connected layer
47
num_epoch = 300   # The number of Epochs that the Model run
48
keep_rate = 0.75  # Keep rate of the Dropout
49
50
lr = tf.constant(1e-4, dtype=tf.float32)  # Learning rate
51
lr_decay_epoch = 50    # Every (50) epochs, the learning rate decays
52
lr_decay       = 0.50  # Learning rate Decay by (50%)
53
54
batch_size = 1024
55
n_batch = train_data.shape[0] // batch_size
56
57
# Initialize Model Parameters (Network Weights and Biases)
58
# This Model only uses Two fully-connected layers, and u sure can add extra layers DIY
59
weights_1 = tf.Variable(tf.truncated_normal([np.shape(test_data)[1], n_hidden], stddev=0.01))
60
biases_1  = tf.Variable(tf.constant(0.01, shape=[n_hidden]))
61
weights_2 = tf.Variable(tf.truncated_normal([n_hidden, n_class], stddev=0.01))
62
biases_2  = tf.Variable(tf.constant(0.01, shape=[n_class]))
63
64
# Define Placeholders
65
x = tf.placeholder(tf.float32, [None, 64 * 64])
66
y = tf.placeholder(tf.float32, [None, 4])
67
keep_prob = tf.placeholder(tf.float32)
68
69
# Load Model Network
70
prediction, features = DNN(Input=x,
71
                           keep_prob=keep_prob,
72
                           weights_1=weights_1,
73
                           biases_1=biases_1,
74
                           weights_2=weights_2,
75
                           biases_2=biases_2)
76
77
# Load Loss Function
78
loss = loss(y=y, prediction=prediction, l2_norm=True)
79
80
# Load Optimizer
81
train_step = tf.train.AdamOptimizer(lr).minimize(loss)
82
83
# Load Evaluation Metrics
84
Global_Average_Accuracy = evaluation(y=y, prediction=prediction)
85
86
# Merge all the summaries
87
merged = tf.summary.merge_all()
88
train_writer = tf.summary.FileWriter(SAVE + '/train_Writer', sess.graph)
89
test_writer = tf.summary.FileWriter(SAVE + '/test_Writer')
90
91
# Initialize all the variables
92
sess.run(tf.global_variables_initializer())
93
for epoch in range(num_epoch + 1):
94
    # U can use learning rate decay or not
95
    # Here, we set a minimum learning rate
96
    # If u don't want this, u definitely can modify the following lines
97
    learning_rate = sess.run(lr)
98
    if epoch % lr_decay_epoch == 0 and epoch != 0:
99
        if learning_rate <= 1e-6:
100
            lr = lr * 1.0
101
            sess.run(lr)
102
        else:
103
            lr = lr * lr_decay
104
            sess.run(lr)
105
106
    # Randomly shuffle the training dataset and train the Model
107
    for batch_index in range(n_batch):
108
        random_batch = random.sample(range(train_data.shape[0]), batch_size)
109
        batch_xs = train_data[random_batch]
110
        batch_ys = train_labels[random_batch]
111
        sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys, keep_prob: keep_rate})
112
113
    # Show Accuracy and Loss on Training and Test Set
114
    # Here, for training set, we only show the result of first 100 samples
115
    # If u want to show the result on the entire training set, please modify it.
116
    train_accuracy, train_loss = sess.run([Global_Average_Accuracy, loss], feed_dict={x: train_data[0:100], y: train_labels[0:100], keep_prob: 1.0})
117
    Test_summary, test_accuracy, test_loss = sess.run([merged, Global_Average_Accuracy, loss], feed_dict={x: test_data, y: test_labels, keep_prob: 1.0})
118
    test_writer.add_summary(Test_summary, epoch)
119
120
    # Show the Model Capability
121
    print("Iter " + str(epoch) + ", Testing Accuracy: " + str(test_accuracy) + ", Training Accuracy: " + str(train_accuracy))
122
    print("Iter " + str(epoch) + ", Testing Loss: " + str(test_loss) + ", Training Loss: " + str(train_loss))
123
    print("Learning rate is ", learning_rate)
124
    print('\n')
125
126
    # Save the prediction and labels for testing set
127
    # The "labels_for_test.csv" is the same as the "test_label.csv"
128
    # We will use the files to draw ROC CCurve and AUC
129
    if epoch == num_epoch:
130
        output_prediction = sess.run(prediction, feed_dict={x: test_data, y: test_labels, keep_prob: 1.0})
131
        np.savetxt(SAVE + "prediction_for_test.csv", output_prediction, delimiter=",")
132
        np.savetxt(SAVE + "labels_for_test.csv", test_labels, delimiter=",")
133
134
    # if you want to extract and save the features from fully-connected layer, use all the dataset and uncomment this.
135
    # All data is the total data = training data + testing data
136
    # We use the features from the overall dataset
137
    # ML models might be used to classify the features further
138
    # if epoch == num_epoch:
139
    #     Features = sess.run(features, feed_dict={x: all_data, y: all_labels, keep_prob: 1.0})
140
    #     np.savetxt(SAVE + "Features.csv", features, delimiter=",")
141
142
train_writer.close()
143
test_writer.close()
144
sess.close()