-
Notifications
You must be signed in to change notification settings - Fork 0
/
rx_models.py
204 lines (163 loc) · 7.51 KB
/
rx_models.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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
"""AI based RX
RX models
input, RX data (FTN + AWGN, ...)
output, 0/1 message bit values
v0.0.2 > save_mdl improved (saving configuration to xml file inserted)
v0.0.1 > keras api import fix
last update: 14 May 2024, 14:59
"""
import pandas as pd
from rx_config import *
# from tensorflow import keras
from keras import Sequential
from keras.api.layers import Input, Dense, LSTM, Dropout, GRU
from keras.api.models import save_model, load_model
from keras.api.metrics import BinaryAccuracy, F1Score, Precision, Recall
# from keras.optimizers import SGD, Nadam
from datetime import datetime
from utils import check_path_base
def base_bpsk(batch_size=32):
model = Sequential()
model._name = 'base_nn_bpsk'
model.add(Dense(3, input_shape=(2,), activation='relu'))
model.add(Dense(1, activation=tf.keras.activations.hard_sigmoid))
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
return model
def song_bpsk(L, m, batch_size=32):
model = Sequential()
model._name = 'song_bpsk'
model.add(Dense(320, input_shape=(L, ), batch_size=batch_size, activation='relu'))
model.add(Dense(160, activation='relu'))
model.add(Dense(80, activation='relu'))
model.add(Dense(40, activation='relu'))
model.add(Dense(m, activation='tanh'))
# model.compile(optimizer='adam', loss='mse', metrics=[BinaryAccuracy(), F1Score()])
model.compile(optimizer='adam', loss='mse', metrics='accuracy')
return model
def lstm_bpsk(isi=7, batch_size=32):
# (n_samples, time_steps, features)
model = Sequential()
model._name = 'lstm_bpsk'
# https://wandb.ai/ayush-thakur/dl-question-bank/reports/LSTM-RNN-in-Keras-Examples-of-One-to-Many-Many-to-One-Many-to-Many---VmlldzoyMDIzOTM
# https://stackoverflow.com/questions/74811755/input-0-of-layer-lstm-is-incompatible-with-the-layer-expected-shape-1-none,
# https://stackoverflow.com/a/74812987
model.add(LSTM(32, input_shape=(2*isi+1, 1),
return_sequences=True,
# stateful=True,
batch_input_shape=(batch_size, 2*isi+1, 1))) # batch_size, timesteps, data_dim
model.add(Dropout(rate=0.2))
# https://stackoverflow.com/a/47505918
# model.add(LSTM(units=8, return_sequences=True, stateful=True))
# model.add(Dense(21, activation='relu'))
# model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation=tf.keras.activations.hard_sigmoid))
# model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
model.compile(optimizer=tf.keras.optimizers.Nadam(),
loss='mse',
metrics=[BinaryAccuracy(), F1Score()])
# https://stackoverflow.com/a/58954176
# model.summary()
return model
def gru_temel(lon=7, batch_size=32, init_lr=0.001):
# (n_samples, time_steps, features)
model = Sequential()
model.name = 'gru_temel'
model.add(Input(shape=(2*lon+1, 1),
# batch_size=batch_size
)
)
model.add(GRU(units=2*lon+1, # dimensionality of OUTPUT space
activation='tanh',
recurrent_activation='sigmoid',
recurrent_dropout=0,
unroll=False,
use_bias=True,
reset_after=True,
kernel_initializer='glorot_uniform',
recurrent_initializer='orthogonal',
bias_initializer='zeros')
)
model.add(Dropout(rate=0.3))
# model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation=tf.keras.activations.hard_sigmoid))
# model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
model.compile(optimizer=tf.keras.optimizers.Nadam(learning_rate=init_lr),
loss='mse',
metrics=[BinaryAccuracy(), F1Score()])
# model.summary()
return model
def gru_plus(isi=7, batch_size=32, init_lr=0.001):
# (n_samples, time_steps, features)
model = Sequential()
model._name = 'gru_plus'
model.add(GRU(32, input_shape=(2*isi+1, 2)))
model.add(Dropout(rate=0.2))
# model.add(Dense(8, activation='relu'))
model.add(Dense(4, activation=tf.keras.activations.hard_sigmoid))
# model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
model.compile(optimizer=tf.keras.optimizers.Nadam(),
loss='categorical_crossentropy',
metrics=[BinaryAccuracy(), F1Score()])
# model.summary()
return model
def dense_nn_qpsk():
model = Sequential()
model._name = 'dense_nn_qpsk'
model.add(Dense(4, input_shape=(2,), activation='linear')) # input shape(2,N) : (real, imag)
# model.add(Dense(8, activation='linear'))
model.add(Dense(4, activation=tf.keras.activations.hard_sigmoid))
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
return model
def dense_nn_deep():
model = Sequential()
model._name = 'dense_nn_bpsk'
model.add(Dense(8, input_shape=(1,), activation='relu'))
model.add(Dense(2, activation='relu'))
# model.add(Dense(1, activation='tanh'))
model.add(Dense(1, activation=tf.keras.activations.hard_sigmoid))
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
return model
def save_mdl(model, modulation, config, history=None):
"""
Save the model parameters and model weight
model : model structure to save
modulation: type of modulation, IQ, 'bpsk' or 'qpsk'
config: configuration and parameters that set through the model training
history: train history if available
"""
damga = datetime.utcnow()
# uid = 'tau{:.2f}_'.format(tau) + model.name + '_' + damga.strftime('%Y%b%d_%H%M')
# uid = 'tau{:.2f}_'.format(tau) + damga.strftime('%y%m%dv%H%M')
uid = damga.strftime('%y%m%dv%H%M')
dir_path = 'models/' + modulation + '/' + model.name + '/' + uid + '/'
full_path = dir_path + 'model.keras'
check_path_base(full_path)
# save_model(model, filepath='models/' + uid, overwrite=True, save_format='tf') -13.may.2024
save_model(model, filepath=full_path, overwrite=True)
print('{name} is saved to {path}'.format(name=uid, path=full_path))
# save the configurations and train parameters of current model
# with open('/'.join(full_path.split('/')[:-1])+'/configurations.xml', 'w') as f:
with open(dir_path + '/configurations.xml', 'w') as f:
for key, value in config.items():
# f.write('{:>25}: {:<30}{}\n'.format(str(key), str(value), 'comment'))
f.write('{:>25}: {:<30}\n'.format(str(key), str(value)))
if history:
# https://stackoverflow.com/questions/41061457/
# keras-how-to-save-the-training-history-attribute-of-the-history-object
# convert the history.history dict to a pandas DataFrame:
hist_df = pd.DataFrame(history.history)
# save to json:
# hist_json_file = '/'.join(full_path.split('/')[:-1])+'/history.json'
hist_json_file = dir_path + '/history.json'
with open(hist_json_file, mode='w') as f:
hist_df.to_json(f)
return dir_path
# references
# Activation functions:
# Hard sigmoid
# https://www.tensorflow.org/api_docs/python/tf/keras/activations/hard_sigmoid
# if x < -2.5: return 0
# if x > 2.5: return 1
# if -2.5 <= x <= 2.5: return 0.2 * x + 0.5
# GRU and LSTM
# https://analyticsindiamag.com/lstm-vs-gru-in-recurrent-neural-network-a-comparative-study/