end_to_end.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. import math
  2. import tensorflow as tf
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. from sklearn.metrics import accuracy_score
  6. from sklearn.preprocessing import OneHotEncoder
  7. from tensorflow.keras import layers, losses
  8. from tensorflow.keras import backend as K
  9. from models.custom_layers import ExtractCentralMessage, OpticalChannel, DigitizationLayer, BitsToSymbols, SymbolsToBits
  10. import itertools
  11. class EndToEndAutoencoder(tf.keras.Model):
  12. def __init__(self,
  13. cardinality,
  14. samples_per_symbol,
  15. messages_per_block,
  16. channel,
  17. bit_mapping=False):
  18. """
  19. The autoencoder that aims to find a encoding of the input messages. It should be noted that a "block" consists
  20. of multiple "messages" to introduce memory into the simulation as this is essential for modelling inter-symbol
  21. interference. The autoencoder architecture was heavily influenced by IEEE 8433895.
  22. :param cardinality: Number of different messages. Chosen such that each message encodes log_2(cardinality) bits
  23. :param samples_per_symbol: Number of samples per transmitted symbol
  24. :param messages_per_block: Total number of messages in transmission block
  25. :param channel: Channel Layer object. Must be a subclass of keras.layers.Layer with an implemented forward pass
  26. """
  27. super(EndToEndAutoencoder, self).__init__()
  28. # Labelled M in paper
  29. self.cardinality = cardinality
  30. self.bits_per_symbol = int(math.log(self.cardinality, 2))
  31. # Labelled n in paper
  32. self.samples_per_symbol = samples_per_symbol
  33. # Labelled N in paper
  34. if messages_per_block % 2 == 0:
  35. messages_per_block += 1
  36. self.messages_per_block = messages_per_block
  37. # Channel Model Layer
  38. if isinstance(channel, layers.Layer):
  39. self.channel = tf.keras.Sequential([
  40. layers.Flatten(),
  41. channel,
  42. ExtractCentralMessage(self.messages_per_block, self.samples_per_symbol)
  43. ], name="channel_model")
  44. else:
  45. raise TypeError("Channel must be a subclass of keras.layers.layer!")
  46. # Boolean identifying if bit mapping is to be learnt
  47. self.bit_mapping = bit_mapping
  48. # Model Hyper-parameters
  49. leaky_relu_alpha = 0
  50. relu_clip_val = 1.0
  51. # Layer configuration for the case when bit mapping is to be learnt
  52. if self.bit_mapping:
  53. encoding_layers = [
  54. layers.Input(shape=(self.messages_per_block, self.bits_per_symbol)),
  55. BitsToSymbols(self.cardinality),
  56. layers.TimeDistributed(layers.Dense(2 * self.cardinality)),
  57. layers.TimeDistributed(layers.LeakyReLU(alpha=leaky_relu_alpha)),
  58. # layers.TimeDistributed(layers.Dense(2 * self.cardinality)),
  59. # layers.TimeDistributed(layers.LeakyReLU(alpha=leaky_relu_alpha)),
  60. # layers.TimeDistributed(layers.Dense(self.samples_per_symbol, activation='sigmoid')),
  61. layers.TimeDistributed(layers.Dense(self.samples_per_symbol)),
  62. layers.TimeDistributed(layers.ReLU(max_value=relu_clip_val))
  63. ]
  64. decoding_layers = [
  65. layers.Dense(2 * self.cardinality),
  66. layers.LeakyReLU(alpha=leaky_relu_alpha),
  67. # layers.Dense(2 * self.cardinality),
  68. # layers.LeakyReLU(alpha=0.01),
  69. layers.Dense(self.bits_per_symbol, activation='sigmoid')
  70. ]
  71. # layer configuration for the case when only symbol mapping is to be learnt
  72. else:
  73. encoding_layers = [
  74. layers.Input(shape=(self.messages_per_block, self.cardinality)),
  75. layers.TimeDistributed(layers.Dense(2 * self.cardinality)),
  76. layers.TimeDistributed(layers.LeakyReLU(alpha=leaky_relu_alpha)),
  77. layers.TimeDistributed(layers.Dense(2 * self.cardinality)),
  78. layers.TimeDistributed(layers.LeakyReLU(alpha=leaky_relu_alpha)),
  79. layers.TimeDistributed(layers.Dense(self.samples_per_symbol, activation='sigmoid')),
  80. # layers.TimeDistributed(layers.Dense(self.samples_per_symbol)),
  81. # layers.TimeDistributed(layers.ReLU(max_value=relu_clip_val))
  82. ]
  83. decoding_layers = [
  84. layers.Dense(2 * self.cardinality),
  85. layers.LeakyReLU(alpha=leaky_relu_alpha),
  86. layers.Dense(2 * self.cardinality),
  87. layers.LeakyReLU(alpha=leaky_relu_alpha),
  88. layers.Dense(self.cardinality, activation='softmax')
  89. ]
  90. # Encoding Neural Network
  91. self.encoder = tf.keras.Sequential([
  92. *encoding_layers
  93. ], name="encoding_model")
  94. # Decoding Neural Network
  95. self.decoder = tf.keras.Sequential([
  96. *decoding_layers
  97. ], name="decoding_model")
  98. def generate_random_inputs(self, num_of_blocks, return_vals=False):
  99. """
  100. A method that generates a list of one-hot encoded messages. This is utilized for generating the test/train data.
  101. :param num_of_blocks: Number of blocks to generate. A block contains multiple messages to be transmitted in
  102. consecutively to model ISI. The central message in a block is returned as the label for training.
  103. :param return_vals: If true, the raw decimal values of the input sequence will be returned
  104. """
  105. cat = [np.arange(self.cardinality)]
  106. enc = OneHotEncoder(handle_unknown='ignore', sparse=False, categories=cat)
  107. mid_idx = int((self.messages_per_block - 1) / 2)
  108. if self.bit_mapping:
  109. rand_int = np.random.randint(2, size=(num_of_blocks * self.messages_per_block * self.bits_per_symbol, 1))
  110. out = rand_int
  111. out_arr = np.reshape(out, (num_of_blocks, self.messages_per_block, self.bits_per_symbol))
  112. if return_vals:
  113. return out_arr, out_arr, out_arr[:, mid_idx, :]
  114. else:
  115. rand_int = np.random.randint(self.cardinality, size=(num_of_blocks * self.messages_per_block, 1))
  116. out = enc.fit_transform(rand_int)
  117. out_arr = np.reshape(out, (num_of_blocks, self.messages_per_block, self.cardinality))
  118. if return_vals:
  119. out_val = np.reshape(rand_int, (num_of_blocks, self.messages_per_block, 1))
  120. return out_val, out_arr, out_arr[:, mid_idx, :]
  121. return out_arr, out_arr[:, mid_idx, :]
  122. def train(self, num_of_blocks=1e6, epochs=1, batch_size=None, train_size=0.8, lr=1e-3):
  123. """
  124. Method to train the autoencoder. Further configuration to the loss function, optimizer etc. can be made in here.
  125. :param num_of_blocks: Number of blocks to generate for training. Analogous to the dataset size.
  126. :param batch_size: Number of samples to consider on each update iteration of the optimization algorithm
  127. :param train_size: Float less than 1 representing the proportion of the dataset to use for training
  128. :param lr: The learning rate of the optimizer. Defines how quickly the algorithm converges
  129. """
  130. X_train, y_train = self.generate_random_inputs(int(num_of_blocks * train_size))
  131. X_test, y_test = self.generate_random_inputs(int(num_of_blocks * (1 - train_size)))
  132. opt = tf.keras.optimizers.Adam(learning_rate=lr)
  133. # TODO: Investigate different optimizers (with different learning rates and other parameters)
  134. # SGD
  135. # RMSprop
  136. # Adam
  137. # Adadelta
  138. # Adagrad
  139. # Adamax
  140. # Nadam
  141. # Ftrl
  142. if self.bit_mapping:
  143. loss_fn = losses.BinaryCrossentropy()
  144. else:
  145. loss_fn = losses.CategoricalCrossentropy()
  146. self.compile(optimizer=opt,
  147. loss=loss_fn,
  148. metrics=['accuracy'],
  149. loss_weights=None,
  150. weighted_metrics=None,
  151. run_eagerly=False
  152. )
  153. history = self.fit(x=X_train,
  154. y=y_train,
  155. batch_size=batch_size,
  156. epochs=epochs,
  157. shuffle=True,
  158. validation_data=(X_test, y_test)
  159. )
  160. plt.plot(history.history['accuracy'])
  161. plt.plot(history.history['val_accuracy'])
  162. plt.show()
  163. def test(self, num_of_blocks=1e3):
  164. X_test, y_test = self.generate_random_inputs(int(num_of_blocks))
  165. y_out = self.call(X_test)
  166. y_pred = tf.argmax(y_out, axis=1)
  167. y_true = tf.argmax(y_test, axis=1)
  168. symbol_error_rate = 1 - accuracy_score(y_true, y_pred)
  169. lst = [list(i) for i in itertools.product([0, 1], repeat=self.bits_per_symbol)]
  170. bits_pred = SymbolsToBits(self.cardinality)(tf.one_hot(y_pred, self.cardinality)).numpy().flatten()
  171. bits_true = SymbolsToBits(self.cardinality)(y_test).numpy().flatten()
  172. bit_error_rate = 1 - accuracy_score(bits_true, bits_pred)
  173. print("SYMBOL ERROR RATE: {}".format(symbol_error_rate))
  174. print("BIT ERROR RATE: {}".format(bit_error_rate))
  175. pass
  176. def view_encoder(self):
  177. '''
  178. A method that views the learnt encoder for each distint message. This is displayed as a plot with a subplot for
  179. each message/symbol.
  180. '''
  181. mid_idx = int((self.messages_per_block - 1) / 2)
  182. if self.bit_mapping:
  183. messages = np.zeros((self.cardinality, self.messages_per_block, self.bits_per_symbol))
  184. lst = [list(i) for i in itertools.product([0, 1], repeat=self.bits_per_symbol)]
  185. idx = 0
  186. for msg in messages:
  187. msg[mid_idx] = lst[idx]
  188. idx += 1
  189. else:
  190. # Generate inputs for encoder
  191. messages = np.zeros((self.cardinality, self.messages_per_block, self.cardinality))
  192. idx = 0
  193. for msg in messages:
  194. msg[mid_idx, idx] = 1
  195. idx += 1
  196. # Pass input through encoder and select middle messages
  197. encoded = self.encoder(messages)
  198. enc_messages = encoded[:, mid_idx, :]
  199. # Compute subplot grid layout
  200. i = 0
  201. while 2 ** i < self.cardinality ** 0.5:
  202. i += 1
  203. num_x = int(2 ** i)
  204. num_y = int(self.cardinality / num_x)
  205. # Plot all symbols
  206. fig, axs = plt.subplots(num_y, num_x, figsize=(2.5 * num_x, 2 * num_y))
  207. t = np.arange(self.samples_per_symbol)
  208. if isinstance(self.channel.layers[1], OpticalChannel):
  209. t = t / self.channel.layers[1].fs
  210. sym_idx = 0
  211. for y in range(num_y):
  212. for x in range(num_x):
  213. axs[y, x].plot(t, enc_messages[sym_idx].numpy().flatten(), 'x')
  214. axs[y, x].set_title('Symbol {}'.format(str(sym_idx)))
  215. sym_idx += 1
  216. for ax in axs.flat:
  217. ax.set(xlabel='Time', ylabel='Amplitude', ylim=(0, 1))
  218. for ax in axs.flat:
  219. ax.label_outer()
  220. plt.show()
  221. pass
  222. def view_sample_block(self):
  223. '''
  224. Generates a random string of input message and encodes them. In addition to this, the output is passed through
  225. digitization layer without any quantization noise for the low pass filtering.
  226. '''
  227. # Generate a random block of messages
  228. val, inp, _ = self.generate_random_inputs(num_of_blocks=1, return_vals=True)
  229. # Encode and flatten the messages
  230. enc = self.encoder(inp)
  231. flat_enc = layers.Flatten()(enc)
  232. chan_out = self.channel.layers[1](flat_enc)
  233. # Instantiate LPF layer
  234. lpf = DigitizationLayer(fs=self.channel.layers[1].fs,
  235. num_of_samples=self.messages_per_block * self.samples_per_symbol,
  236. sig_avg=0)
  237. # Apply LPF
  238. lpf_out = lpf(flat_enc)
  239. # Time axis
  240. t = np.arange(self.messages_per_block * self.samples_per_symbol)
  241. if isinstance(self.channel.layers[1], OpticalChannel):
  242. t = t / self.channel.layers[1].fs
  243. # Plot the concatenated symbols before and after LPF
  244. plt.figure(figsize=(2 * self.messages_per_block, 6))
  245. for i in range(1, self.messages_per_block):
  246. plt.axvline(x=t[i * self.samples_per_symbol], color='black')
  247. plt.plot(t, flat_enc.numpy().T, 'x')
  248. plt.plot(t, lpf_out.numpy().T)
  249. plt.plot(t, chan_out.numpy().flatten())
  250. plt.ylim((0, 1))
  251. plt.xlim((t.min(), t.max()))
  252. plt.title(str(val[0, :, 0]))
  253. plt.show()
  254. pass
  255. def call(self, inputs, training=None, mask=None):
  256. tx = self.encoder(inputs)
  257. rx = self.channel(tx)
  258. outputs = self.decoder(rx)
  259. return outputs
  260. SAMPLING_FREQUENCY = 336e9
  261. CARDINALITY = 32
  262. SAMPLES_PER_SYMBOL = 32
  263. MESSAGES_PER_BLOCK = 9
  264. DISPERSION_FACTOR = -21.7 * 1e-24
  265. FIBER_LENGTH = 0
  266. if __name__ == '__main__':
  267. optical_channel = OpticalChannel(fs=SAMPLING_FREQUENCY,
  268. num_of_samples=MESSAGES_PER_BLOCK * SAMPLES_PER_SYMBOL,
  269. dispersion_factor=DISPERSION_FACTOR,
  270. fiber_length=FIBER_LENGTH)
  271. ae_model = EndToEndAutoencoder(cardinality=CARDINALITY,
  272. samples_per_symbol=SAMPLES_PER_SYMBOL,
  273. messages_per_block=MESSAGES_PER_BLOCK,
  274. channel=optical_channel,
  275. bit_mapping=False)
  276. ae_model.train(num_of_blocks=1e5, epochs=5)
  277. ae_model.test()
  278. ae_model.view_encoder()
  279. ae_model.view_sample_block()
  280. # ae_model.summary()
  281. ae_model.encoder.summary()
  282. ae_model.channel.summary()
  283. ae_model.decoder.summary()
  284. pass