19
19
# import tables
20
20
21
21
from keras .models import Sequential , model_from_json , model_from_yaml
22
- from keras .layers import Dense , Dropout , Activation , Merge
22
+ from keras .layers import Dense , Dropout , Activation , Merge , Flatten , \
23
+ Convolution2D , MaxPooling2D
24
+ from keras .optimizers import SGD
23
25
from keras .callbacks import EarlyStopping
24
26
25
27
from os import path
26
28
import traceback
27
29
import numpy as np
28
- from scipy import signal
30
+ from scipy import signal , fft , ifft
29
31
import matplotlib .pyplot as plt
30
32
from pylab import figure , plot , subplot , show , imshow , colorbar , axis , title
31
33
import h5py as h5
38
40
39
41
config = configurations [0 ]
40
42
metric = metrics [0 ]
41
- ftype = ftypes [0 ]
43
+ ftype = ftypes [1 ]
42
44
43
- FREQ_S = 5208000.0
45
+ # FREQ_C = 5208000.0
46
+ FREQ_S = 20832000.0
44
47
45
48
# Import Settings
46
49
if config == 'simu' :
@@ -150,7 +153,8 @@ def __init__(self, name):
150
153
self .fm = 0
151
154
self .c0 = 0
152
155
self .num_chn = 0
153
- self .csm = ()
156
+ self .csm = () # cross spectral matrix
157
+ self .csm_p = {} # cross spectral matrix splited in real and imag parts
154
158
155
159
self .scan = {}
156
160
@@ -205,18 +209,31 @@ def import_data(self, file_path, file_name):
205
209
206
210
def preprocess (self ):
207
211
# Cross spectral matrix
208
- (_ , num_channels , num_samples ) = self .data ['real' ].shape
209
- self .csm = np .zeros ((num_channels , num_channels , 256 ), dtype = complex )
210
- for i in np .arange (num_channels ):
211
- for j in np .arange (num_channels ):
212
- s1 = self .data ['real' ][1 ,i ,:] + 1j * self .data ['imag' ][1 ,i ,:]
213
- s2 = self .data ['real' ][1 ,j ,:] + 1j * self .data ['imag' ][1 ,j ,:]
214
- _ , self .csm [i ,j ,:] = signal .csd (s1 , s2 , nperseg = 256 )
212
+ (num_angles , num_channels , num_samples ) = self .data ['real' ].shape
213
+ nFFT = 512
214
+ # (samples, channels, rows, cols)
215
+ self .csm = np .zeros ((num_angles , nFFT , num_channels , num_channels ), dtype = complex )
216
+ for k in np .arange (num_angles ):
217
+ for i in np .arange (num_channels ):
218
+ for j in np .arange (num_channels ):
219
+ s1 = self .data ['real' ][k ,i ,:] + 1j * self .data ['imag' ][k ,i ,:]
220
+ s2 = self .data ['real' ][k ,j ,:] + 1j * self .data ['imag' ][k ,j ,:]
221
+ _ , self .csm [k ,:,i ,j ] = signal .csd (s1 , s2 , fs = FREQ_S , nperseg = 40 , \
222
+ nfft = nFFT , scaling = 'density' )
215
223
224
+ # TODO
216
225
# Diagnal removal
217
226
# diag_ind = (np.arange(num_channels), np.arange(num_channels))
218
227
# self.csm[diag_ind, :] = 0 + 1j*0
219
228
229
+ # Lower triangle trim
230
+ # Normalize: /Gxx Gyy
231
+
232
+
233
+ print (self .csm .shape )
234
+ self .csm_p ['real' ] = self .csm .real
235
+ self .csm_p ['imag' ] = self .csm .imag
236
+
220
237
def write_data (self , filename , channel_id ):
221
238
with h5 .File (filename , 'w' ) as hf :
222
239
# DEBUG: complex value OR absolute value ??
@@ -247,47 +264,46 @@ class ANN(object):
247
264
248
265
"""Docstring for ANN. """
249
266
250
- def __init__ (self , input , output ):
251
- """TODO: to be defined. """
252
- in_real = input .data ['real' ]
253
- (i_dim_x , i_dim_y , i_dim_z ) = in_real .shape
254
- self .input_dim = i_dim_x * i_dim_y * i_dim_z
255
- self .input_data = in_real .reshape (self .input_dim , 1 )
256
- print (self .input_dim )
267
+ def __init__ (self ):
268
+ self .in_real = ()
269
+ self .in_imag = ()
270
+ # self.input_data = ()
271
+
272
+ self .out_real = ()
273
+ self .out_imag = ()
274
+ # self.output_data = ()
257
275
258
- out_real = output . data [ 'real' ]
259
- ( o_dim_x , o_dim_y , o_dim_z ) = out_real . shape
260
- self .output_dim = o_dim_x * o_dim_y * o_dim_z
261
- self .output_data = out_real . reshape ( self . output_dim , 1 )
262
- print ( self .output_dim )
276
+ def train_mlp ( self , input , output ):
277
+ self . in_real = input . data [ 'real' ]
278
+ self .in_imag = input . data [ 'imag' ]
279
+ self .out_real = output . data [ 'real' ]
280
+ self .out_imag = output . data [ 'imag' ]
263
281
264
- self .sp_in = ()
265
- self .sp_out = ()
282
+ (i_dim_x , i_dim_y , i_dim_z ) = self .in_real .shape
283
+ in_dim = i_dim_x * i_dim_y * i_dim_z
284
+ input_data = self .in_real .reshape (in_dim , 1 )
266
285
267
- def sample_data ( self ):
268
- self . sp_in = self . input_data [ 1 : 100 , :]
269
- self . sp_out = self .output_data [ 1 : 100 , :]
286
+ ( o_dim_x , o_dim_y , o_dim_z ) = self . out_real . shape
287
+ out_dim = o_dim_x * o_dim_y * o_dim_z
288
+ output_data = self .out_real . reshape ( out_dim , 1 )
270
289
271
- def train (self ):
272
290
model = Sequential ()
273
- model .add (Dense (200 , input_dim = self . input_dim , init = 'uniform' ))
291
+ model .add (Dense (200 , input_dim = in_dim , init = 'uniform' ))
274
292
model .add (Activation ('relu' ))
275
293
# model.add(Dropout(0.25))
276
294
277
295
model .add (Dense (200 ))#, init='uniform'))
278
296
model .add (Activation ('relu' ))
279
297
# model.add(Dropout(0.25))
280
298
281
- model .add (Dense (self . output_dim ))#, init='uniform'))
299
+ model .add (Dense (out_dim ))#, init='uniform'))
282
300
model .add (Activation ('softmax' ))
283
301
284
302
model .compile (loss = 'categorical_crossentropy' , optimizer = 'sgd' ,\
285
303
metrics = ['accuracy' ])
286
304
287
- # hist = model.fit(self.input_data, self.output_data, nb_epoch=50, \
288
- # batch_size=64, validation_split=0.2, shuffle=True)
289
305
early_stop = EarlyStopping (monitor = 'val_loss' , patience = 2 )
290
- hist = model .fit (self . sp_in , self . sp_out , nb_epoch = 50 , \
306
+ hist = model .fit (input_data , output_data , nb_epoch = 50 , \
291
307
batch_size = 64 , validation_split = 0.2 , \
292
308
shuffle = True , callbacks = [early_stop ])
293
309
print (hist .history )
@@ -301,6 +317,65 @@ def train(self):
301
317
open ('model_architecture.yaml' , 'w' ).write (model_to_save_yaml )
302
318
model .save_weights ('weights.h5' )
303
319
320
+ def train_cnn (self , input , output ):
321
+ self .in_real = input .csm_p ['real' ]
322
+ self .in_imag = input .csm_p ['imag' ]
323
+ self .out_real = output .data ['real' ]
324
+ self .out_imag = output .data ['imag' ]
325
+
326
+ (num_samples , num_channels , num_rows , num_cols ) = self .in_real .shape
327
+ (o_dim_x , o_dim_y , o_dim_z ) = self .out_real .shape
328
+ out_dim = o_dim_x * o_dim_y * o_dim_z
329
+ out_data_r = self .out_real .reshape (out_dim , 1 )
330
+ out_data_i = self .out_imag .reshape (out_dim , 1 )
331
+
332
+ batch_size = 32
333
+ num_epoch = 200
334
+ num_filter = 64
335
+ num_row_kernel = 3
336
+ num_col_kernel = 3
337
+ num_pool = 2
338
+ dim_order = 'th' # (samples, channels, rows, cols)
339
+ model = Sequential ()
340
+ model .add (Convolution2D (num_filter , num_row_kernel , num_col_kernel , \
341
+ border_mode = 'same' , dim_ordering = dim_order , \
342
+ input_shape = (num_channels , num_rows , num_cols )))
343
+ model .add (Activation ('relu' ))
344
+ model .add (Convolution2D (num_filter , num_row_kernel , num_col_kernel ))
345
+ model .add (Activation ('relu' ))
346
+ model .add (MaxPooling2D (pool_size = (num_pool , num_pool )))
347
+ model .add (Dropout (0.25 ))
348
+
349
+ model .add (Convolution2D (num_filter , num_row_kernel , num_col_kernel , \
350
+ border_mode = 'same' ))
351
+ model .add (Activation ('relu' ))
352
+ model .add (Convolution2D (num_filter , num_row_kernel , num_col_kernel ))
353
+ model .add (Activation ('relu' ))
354
+ model .add (MaxPooling2D (pool_size = (num_pool , num_pool )))
355
+ model .add (Dropout (0.25 ))
356
+
357
+ model .add (Flatten ())
358
+ model .add (Dense (512 ))
359
+ model .add (Activation ('relu' ))
360
+ model .add (Dropout (0.5 ))
361
+ model .add (Dense (out_dim ))
362
+ model .add (Activation ('softmax' ))
363
+
364
+ sgd = SGD (lr = 0.01 , decay = 1e-6 , momentum = 0.9 , nesterov = True )
365
+ model .compile (loss = 'categorical_crossentropy' , \
366
+ optimizer = sgd , metrics = ['accuracy' ])
367
+
368
+ early_stop = EarlyStopping (monitor = 'val_loss' , patience = 2 )
369
+ hist_r = model .fit (self .in_real , out_data_r , \
370
+ bash_size = batch_size , nb_epoch = num_epoch , verbose = 1 , \
371
+ validation_split = 0.2 , shuffle = True , callbacks = [early_stop ])
372
+ print (hist_r .history )
373
+
374
+ hist_i = model .fit (self .in_imag , out_data_i , \
375
+ bash_size = batch_size , nb_epoch = num_epoch , verbose = 1 , \
376
+ validation_split = 0.2 , shuffle = True , callbacks = [early_stop ])
377
+ print (hist_i .history )
378
+
304
379
def predict (self , X_test , Y_test ):
305
380
306
381
model = model_from_json (open ('model_architecture.json' ).read ())
@@ -338,13 +413,14 @@ def test_import():
338
413
def test_net ():
339
414
rcv_data = DataSet (config + '_' + metric + '_' + ftype + '_' + 'data' )
340
415
rcv_data .import_data (data_path , data_name )
416
+ rcv_data .preprocess ()
341
417
342
418
img_data = DataSet ('reconstructed_image' )
343
419
img_data .import_data (imag_recon_path , imag_recon_name )
344
420
345
-
346
- ann = ANN (rcv_data , img_data )
347
- ann .train ( )
421
+ ann = ANN ()
422
+ # ann.train_mlp (rcv_data, img_data)
423
+ ann .train_cnn ( rcv_data , img_data )
348
424
349
425
def beamform_imaging ():
350
426
rcv_data = DataSet (config + '_' + metric + '_' + ftype + '_' + 'data' )
@@ -397,6 +473,6 @@ def beamform_imaging():
397
473
398
474
399
475
if __name__ == '__main__' :
400
- # test_net()
401
- test_import ();
476
+ test_net ()
477
+ # test_import();
402
478
# beamform_imaging()
0 commit comments