-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeras_simple_conv.py
136 lines (114 loc) · 4.6 KB
/
keras_simple_conv.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from DataPESQ import DataPESQ
import itertools as it
from cachetools import cached, TTLCache
import os
cache = TTLCache(maxsize=3000, ttl=9000)
test_flag = False
load = False
path = 'data\PESQ_DB.xlsx'
init_momentum = 0.9
arhitecture = [30,30]
epochs = 100
def own_evaluate(model, test_data, test_labels, string):
test_labels_array = list(map(lambda x: [x], test_labels))
x = list(map(lambda x: x[0], test_data))
y = list(map(lambda x: x[1], test_data))
# print(test_labels_array)
true_results = np.concatenate((test_data, test_labels_array), axis=1)
prediction = model.predict(test_data)
prediction_vector = np.concatenate((prediction),axis=None)
model_results = np.concatenate((test_data, prediction), axis=1)
diff = test_labels - prediction_vector
# diff = list(map(lambda x: np.array(x), diff))
# diff_results = np.concatenate((test_data, diff), axis=1)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, diff)
# plt.show()
plt.savefig(string + '\\figure.png',bbox_inches='tight')
return
@cached(cache)
def split_data(path):
dataObj = DataPESQ(path)
data = dataObj.get_data()
np.random.shuffle(data)
sample_train = round(len(data) * 0.8)
sample_test = len(data) - sample_train
print(len(data), sample_train, sample_test)
training, test = data[sample_test:], data[:sample_test]
print(np.shape(training))
print(np.shape(test))
return training, test
def explore_models(trainig_data, training_labels, epochs):
model = keras.Sequential()
model.add(keras.layers.Conv1D(filters=64, kernel_size=2, padding='same', activation='relu', input_shape=(512,149)))
model.add(keras.layers.MaxPooling1D(pool_size=2))
model.add(keras.layers.Conv1D(filters=32, kernel_size=2, padding='same', activation='relu'))
model.add(keras.layers.MaxPooling1D(pool_size=2))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(64, activation='relu'))
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(1))
model.compile(optimizer=tf.train.RMSPropOptimizer(0.01),
loss='mse',
metrics=['mse'])
model.fit(trainig_data, training_labels, epochs=epochs)
return model
def __main__():
print("Pre-processing data ...")
trainig, test = split_data(path)
trainig_labels = list(it.chain.from_iterable(list(map(lambda x: x[:1],trainig))))
trainig_data = list(map(lambda x: x[1:],trainig))
test_labels = list(it.chain.from_iterable(list(map(lambda x: x[:1],test))))
test_data = list(map(lambda x: x[1:],test))
trainig_data = np.array(trainig_data)
trainig_labels = np.array(trainig_labels)
test_data = np.array(test_data)
test_labels = np.array(test_labels)
callbacks = [
# Interrupt training if `val_loss` stops improving for over 2 epochs
keras.callbacks.EarlyStopping(patience=2, monitor='val_loss'),
# Write TensorBoard logs to `./logs` directory
keras.callbacks.TensorBoard(log_dir='.\logs')
]
print("Test = ", test_flag)
if test_flag:
arhitecture = [30, 30]
model = explore_models(arhitecture, trainig_data, trainig_labels, epochs)
own_evaluate(model, test_data, test_labels, 'test')
exit(0)
try:
# string = 'model\conv'
# os.makedirs(string)
model = explore_models(trainig_data, trainig_labels, epochs)
test_loss, test_acc = model.evaluate(test_data, test_labels)
print(test_loss, test_acc)
except Exception:
pass
#
# for i in range(1,51):
# for j in range(1,51):
# try:
# arhitecture = [i, j]
# string = 'models\model' + '-' + str(i) + '-' + str(j)
# os.makedirs(string)
# model = explore_models(arhitecture, trainig_data, trainig_labels, epochs)
# file = open(string + '\log.txt', 'w')
# test_loss, test_acc = model.evaluate(test_data, test_labels)
# print(test_acc)
# file.write('test accuracy')
# file.write(str(test_acc))
# file.close()
# print("Evaluating Model ... Done")
# own_evaluate(model, test_data, test_labels, string)
#
# # model.evaluate(test_data, test_labels)
# model.save(string + '\model.h5')
# except Exception:
# pass
__main__()