Skip to content

Commit 3e6f555

Browse files
committed
Feat(ANN.py): Add conv net method to ANN class
1. Add conv net method to ANN class. Input: CSM (numAngle, numFFT, numCH, numCH) Output: Image (numPW*numXgrid*numYgrid, 1) Structure: (conv-relu-conv-relu-maxpool-dropout) -(conv-relu-conv-relu-maxpool-dropout) -flatten-dense-relu-dropout-dense-softmax Splitted training for real and imag parts. 2. Refactor: rewrite data interface between DataSet class and ANN class. Make the DataSet mere supplier and the ANN consumer, the ANN tailors the data in its own way for subfunctions to use. 3. Remove deprecated method: sample_data. TODO: 1. CSM diagnal removal, lower triangle trim. 2. Tune the nets.
1 parent 31b8221 commit 3e6f555

File tree

1 file changed

+116
-40
lines changed

1 file changed

+116
-40
lines changed

ANN.py

Lines changed: 116 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,15 @@
1919
# import tables
2020

2121
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
2325
from keras.callbacks import EarlyStopping
2426

2527
from os import path
2628
import traceback
2729
import numpy as np
28-
from scipy import signal
30+
from scipy import signal, fft, ifft
2931
import matplotlib.pyplot as plt
3032
from pylab import figure, plot, subplot, show, imshow, colorbar, axis, title
3133
import h5py as h5
@@ -38,9 +40,10 @@
3840

3941
config = configurations[0]
4042
metric = metrics[0]
41-
ftype = ftypes[0]
43+
ftype = ftypes[1]
4244

43-
FREQ_S = 5208000.0
45+
# FREQ_C = 5208000.0
46+
FREQ_S = 20832000.0
4447

4548
# Import Settings
4649
if config == 'simu':
@@ -150,7 +153,8 @@ def __init__(self, name):
150153
self.fm = 0
151154
self.c0 = 0
152155
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
154158

155159
self.scan = {}
156160

@@ -205,18 +209,31 @@ def import_data(self, file_path, file_name):
205209

206210
def preprocess(self):
207211
# 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')
215223

224+
# TODO
216225
# Diagnal removal
217226
# diag_ind = (np.arange(num_channels), np.arange(num_channels))
218227
# self.csm[diag_ind, :] = 0 + 1j*0
219228

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+
220237
def write_data(self, filename, channel_id):
221238
with h5.File(filename, 'w') as hf:
222239
# DEBUG: complex value OR absolute value ??
@@ -247,47 +264,46 @@ class ANN(object):
247264

248265
"""Docstring for ANN. """
249266

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 = ()
257275

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']
263281

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)
266285

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)
270289

271-
def train(self):
272290
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'))
274292
model.add(Activation('relu'))
275293
# model.add(Dropout(0.25))
276294

277295
model.add(Dense(200))#, init='uniform'))
278296
model.add(Activation('relu'))
279297
# model.add(Dropout(0.25))
280298

281-
model.add(Dense(self.output_dim))#, init='uniform'))
299+
model.add(Dense(out_dim))#, init='uniform'))
282300
model.add(Activation('softmax'))
283301

284302
model.compile(loss='categorical_crossentropy', optimizer='sgd',\
285303
metrics=['accuracy'])
286304

287-
# hist = model.fit(self.input_data, self.output_data, nb_epoch=50, \
288-
# batch_size=64, validation_split=0.2, shuffle=True)
289305
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, \
291307
batch_size=64, validation_split=0.2, \
292308
shuffle=True, callbacks=[early_stop])
293309
print(hist.history)
@@ -301,6 +317,65 @@ def train(self):
301317
open('model_architecture.yaml', 'w').write(model_to_save_yaml)
302318
model.save_weights('weights.h5')
303319

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+
304379
def predict(self, X_test, Y_test):
305380

306381
model = model_from_json(open('model_architecture.json').read())
@@ -338,13 +413,14 @@ def test_import():
338413
def test_net():
339414
rcv_data = DataSet(config+'_'+metric+'_'+ftype+'_'+'data')
340415
rcv_data.import_data(data_path, data_name)
416+
rcv_data.preprocess()
341417

342418
img_data = DataSet('reconstructed_image')
343419
img_data.import_data(imag_recon_path, imag_recon_name)
344420

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)
348424

349425
def beamform_imaging():
350426
rcv_data = DataSet(config+'_'+metric+'_'+ftype+'_'+'data')
@@ -397,6 +473,6 @@ def beamform_imaging():
397473

398474

399475
if __name__ == '__main__':
400-
# test_net()
401-
test_import();
476+
test_net()
477+
# test_import();
402478
# beamform_imaging()

0 commit comments

Comments
 (0)