forked from sydney222/Python_CsiNet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CS-CsiNet_train.py
202 lines (171 loc) · 7.19 KB
/
CS-CsiNet_train.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
import tensorflow as tf
from keras.layers import Input, Dense, BatchNormalization, Reshape, Conv2D, add, LeakyReLU
from keras.models import Model
from keras.callbacks import TensorBoard, Callback
import scipy.io as sio
import numpy as np
import math
import time
tf.reset_default_graph()
envir = 'indoor' #'indoor' or 'outdoor'
# image params
img_height = 32
img_width = 32
img_channels = 2
img_total = img_height*img_width*img_channels
# network params
residual_num = 2
encoded_dim = 512 #compress rate=1/4->dim.=512, compress rate=1/16->dim.=128, compress rate=1/32->dim.=64, compress rate=1/64->dim.=32
# Bulid the decoder model of CS-CsiNet
def residual_network(encoded, residual_num, encoded_dim):
def add_common_layers(y):
y = BatchNormalization()(y)
y = LeakyReLU()(y)
return y
def residual_block_decoded(y):
shortcut = y
y = Conv2D(8, kernel_size=(3, 3), padding='same', data_format='channels_first')(y)
y = add_common_layers(y)
y = Conv2D(16, kernel_size=(3, 3), padding='same', data_format='channels_first')(y)
y = add_common_layers(y)
y = Conv2D(2, kernel_size=(3, 3), padding='same', data_format='channels_first')(y)
y = BatchNormalization()(y)
y = add([shortcut, y])
y = LeakyReLU()(y)
return y
decoded = Dense(img_total, activation='linear')(encoded)
decoded = Reshape((img_channels, img_height, img_width,))(decoded)
for i in range(residual_num):
decoded = residual_block_decoded(decoded)
decoded = Conv2D(2, (3, 3), activation='sigmoid', padding='same', data_format="channels_first")(decoded)
return decoded
image_tensor = Input(shape=(encoded_dim, ))
network_output = residual_network(image_tensor, residual_num, encoded_dim)
decoder = Model(inputs=[image_tensor], outputs=[network_output])
decoder.compile(optimizer='adam', loss='mse')
print(decoder.summary())
# Data loading
if envir == 'indoor':
mat = sio.loadmat('data/DATA_Htrainin.mat')
x_train = mat['HT'] # array
mat = sio.loadmat('data/DATA_Hvalin.mat')
x_val = mat['HT'] # array
mat = sio.loadmat('data/DATA_Htestin.mat')
x_test = mat['HT'] # array
elif envir == 'outdoor':
mat = sio.loadmat('data/DATA_Htrainout.mat')
x_train = mat['HT'] # array
mat = sio.loadmat('data/DATA_Hvalout.mat')
x_val = mat['HT'] # array
mat = sio.loadmat('data/DATA_Htestout.mat')
x_test = mat['HT'] # array
x_train = x_train.astype('float32')
x_val = x_val.astype('float32')
x_test = x_test.astype('float32')
# encoder with random projection
#A = np.random.uniform(low=-0.5, high=0.5, size = (x_train.shape[1], encoded_dim))
mat = sio.loadmat('data/A%d.mat'%(encoded_dim))
A = mat['A'] # array
y_train = np.dot(x_train, A.T)
y_val = np.dot(x_val, A.T)
y_test = np.dot(x_test, A.T)
x_train = np.reshape(x_train, (len(x_train), img_channels, img_height, img_width)) # adapt this if using `channels_first` image data format
x_val = np.reshape(x_val, (len(x_val), img_channels, img_height, img_width)) # adapt this if using `channels_first` image data format
x_test = np.reshape(x_test, (len(x_test), img_channels, img_height, img_width)) # adapt this if using `channels_first` image data format
class LossHistory(Callback):
def on_train_begin(self, logs={}):
self.losses_train = []
self.losses_val = []
def on_batch_end(self, batch, logs={}):
self.losses_train.append(logs.get('loss'))
def on_epoch_end(self, epoch, logs={}):
self.losses_val.append(logs.get('val_loss'))
history = LossHistory()
file = 'CS-CsiNet_'+(envir)+'_dim'+str(encoded_dim)+time.strftime('_%m_%d')
path = 'result/TensorBoard_%s' %file
decoder.fit(y_train, x_train,
epochs=1000,
batch_size=200,
shuffle=True,
validation_data=(y_val, x_val),
callbacks=[history,
TensorBoard(log_dir = path)])
filename = 'result/trainloss_%s.csv'%file
loss_history = np.array(history.losses_train)
np.savetxt(filename, loss_history, delimiter=",")
filename = 'result/valloss_%s.csv'%file
loss_history = np.array(history.losses_val)
np.savetxt(filename, loss_history, delimiter=",")
tStart = time.time()
x_hat = decoder.predict(y_test)
tEnd = time.time()
print ("It cost %f sec" % ((tEnd - tStart)/x_test.shape[0]))
# Calcaulating the NMSE and rho
if envir == 'indoor':
mat = sio.loadmat('data/DATA_HtestFin_all.mat')
X_test = mat['HF_all']# array
elif envir == 'outdoor':
mat = sio.loadmat('data/DATA_HtestFout_all.mat')
X_test = mat['HF_all']# array
X_test = np.reshape(X_test, (len(X_test), img_height, 125))
x_test_real = np.reshape(x_test[:, 0, :, :], (len(x_test), -1))
x_test_imag = np.reshape(x_test[:, 1, :, :], (len(x_test), -1))
x_test_C = x_test_real-0.5 + 1j*(x_test_imag-0.5)
x_hat_real = np.reshape(x_hat[:, 0, :, :], (len(x_hat), -1))
x_hat_imag = np.reshape(x_hat[:, 1, :, :], (len(x_hat), -1))
x_hat_C = x_hat_real-0.5 + 1j*(x_hat_imag-0.5)
x_hat_F = np.reshape(x_hat_C, (len(x_hat_C), img_height, img_width))
X_hat = np.fft.fft(np.concatenate((x_hat_F, np.zeros((len(x_hat_C), img_height, 257-img_width))), axis=2), axis=2)
X_hat = X_hat[:, :, 0:125]
n1 = np.sqrt(np.sum(np.conj(X_test)*X_test, axis=1))
n1 = n1.astype('float64')
n2 = np.sqrt(np.sum(np.conj(X_hat)*X_hat, axis=1))
n2 = n2.astype('float64')
aa = abs(np.sum(np.conj(X_test)*X_hat, axis=1))
rho = np.mean(aa/(n1*n2), axis=1)
X_hat = np.reshape(X_hat, (len(X_hat), -1))
X_test = np.reshape(X_test, (len(X_test), -1))
power = np.sum(abs(x_test_C)**2, axis=1)
power_d = np.sum(abs(X_hat)**2, axis=1)
mse = np.sum(abs(x_test_C-x_hat_C)**2, axis=1)
print("In "+envir+" environment")
print("When dimension is", encoded_dim)
print("NMSE is ", 10*math.log10(np.mean(mse/power)))
print("Correlation is ", np.mean(rho))
filename = "result/decoded_%s.csv"%file
x_hat1 = np.reshape(x_hat, (len(x_hat), -1))
np.savetxt(filename, x_hat1, delimiter=",")
filename = "result/rho_%s.csv"%file
np.savetxt(filename, rho, delimiter=",")
import matplotlib.pyplot as plt
'''abs'''
n = 10
plt.figure(figsize=(20, 4))
for i in range(n):
# display origoutal
ax = plt.subplot(2, n, i + 1 )
x_testplo = abs(x_test[i, 0, :, :]-0.5 + 1j*(x_test[i, 1, :, :]-0.5))
plt.imshow(np.max(np.max(x_testplo))-x_testplo.T)
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax.invert_yaxis()
# display reconstruction
ax = plt.subplot(2, n, i + 1 + n)
decoded_imgsplo = abs(x_hat[i, 0, :, :]-0.5
+ 1j*(x_hat[i, 1, :, :]-0.5))
plt.imshow(np.max(np.max(decoded_imgsplo))-decoded_imgsplo.T)
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax.invert_yaxis()
plt.show()
# save
# serialize model to JSON
model_json = decoder.to_json()
outfile = "result/model_%s.json"%file
with open(outfile, "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
outfile = "result/model_%s.h5"%file
decoder.save_weights(outfile)