Diff of /Models/main-DenseCNN.py [000000] .. [259458]

Switch to unified view

a b/Models/main-DenseCNN.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.DenseCNN import DenseCNN
18
from Models.Loss_Function.Loss import loss
19
from Models.Evaluation_Metrics.Metrics import evaluation
20
21
# Model Name
22
Model = 'Densely_Connected_Convolutional_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
num_epoch = 300   # The number of Epochs that the Model run
46
keep_rate = 0.75  # Keep rate of the Dropout
47
48
lr = tf.constant(1e-4, dtype=tf.float32)  # Learning rate
49
lr_decay_epoch = 50    # Every (50) epochs, the learning rate decays
50
lr_decay       = 0.50  # Learning rate Decay by (50%)
51
52
batch_size = 64
53
n_batch = train_data.shape[0] // batch_size
54
55
# Define Placeholders
56
x = tf.placeholder(tf.float32, [None, 4096])
57
y = tf.placeholder(tf.float32, [None, 4])
58
keep_prob = tf.placeholder(tf.float32)
59
60
# Load Model Network
61
prediction = DenseCNN(Input=x, keep_prob=keep_prob)
62
63
# Load Loss Function
64
loss = loss(y=y, prediction=prediction, l2_norm=True)
65
66
# Load Optimizer
67
train_step = tf.train.AdamOptimizer(lr).minimize(loss)
68
69
# Load Evaluation Metrics
70
Global_Average_Accuracy = evaluation(y=y, prediction=prediction)
71
72
# Merge all the summaries
73
merged = tf.summary.merge_all()
74
train_writer = tf.summary.FileWriter(SAVE + '/train_Writer', sess.graph)
75
test_writer = tf.summary.FileWriter(SAVE + '/test_Writer')
76
77
# Initialize all the variables
78
sess.run(tf.global_variables_initializer())
79
for epoch in range(num_epoch + 1):
80
    # U can use learning rate decay or not
81
    # Here, we set a minimum learning rate
82
    # If u don't want this, u definitely can modify the following lines
83
    learning_rate = sess.run(lr)
84
    if epoch % lr_decay_epoch == 0 and epoch != 0:
85
        if learning_rate <= 1e-6:
86
            lr = lr * 1.0
87
            sess.run(lr)
88
        else:
89
            lr = lr * lr_decay
90
            sess.run(lr)
91
92
    # Randomly shuffle the training dataset and train the Model
93
    for batch_index in range(n_batch):
94
        random_batch = random.sample(range(train_data.shape[0]), batch_size)
95
        batch_xs = train_data[random_batch]
96
        batch_ys = train_labels[random_batch]
97
        sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys, keep_prob: keep_rate})
98
99
    # Show Accuracy and Loss on Training and Test Set
100
    # Here, for training set, we only show the result of first 100 samples
101
    # If u want to show the result on the entire training set, please modify it.
102
    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})
103
    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})
104
    test_writer.add_summary(Test_summary, epoch)
105
106
    # Show the Model Capability
107
    print("Iter " + str(epoch) + ", Testing Accuracy: " + str(test_accuracy) + ", Training Accuracy: " + str(train_accuracy))
108
    print("Iter " + str(epoch) + ", Testing Loss: " + str(test_loss) + ", Training Loss: " + str(train_loss))
109
    print("Learning rate is ", learning_rate)
110
    print('\n')
111
112
    # Save the prediction and labels for testing set
113
    # The "labels_for_test.csv" is the same as the "test_label.csv"
114
    # We will use the files to draw ROC CCurve and AUC
115
    if epoch == num_epoch:
116
        output_prediction = sess.run(prediction, feed_dict={x: test_data, y: test_labels, keep_prob: 1.0})
117
        np.savetxt(SAVE + "prediction_for_test.csv", output_prediction, delimiter=",")
118
        np.savetxt(SAVE + "labels_for_test.csv", test_labels, delimiter=",")
119
120
train_writer.close()
121
test_writer.close()
122
sess.close()