forked from haoyye/End2End_GAN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGAN_Rayleigh.py
217 lines (187 loc) · 9.43 KB
/
GAN_Rayleigh.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
205
206
207
208
209
210
211
212
import numpy as np
import tensorflow as tf
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = '1'
""" This file is trying to simulate the Rayleigh channel without any channel information"""
tf.set_random_seed(100)
np.random.seed(100)
def generator_conditional(z, conditioning): # need to change the structure
z_combine = tf.concat([z, conditioning], 1)
G_h1 = tf.nn.relu(tf.matmul(z_combine, G_W1) + G_b1)
G_h2 = tf.nn.relu(tf.matmul(G_h1, G_W2) + G_b2)
G_h3 = tf.nn.relu(tf.matmul(G_h2, G_W3) + G_b3)
G_logit = tf.matmul(G_h3, G_W4) + G_b4
return G_logit
def discriminator_conditional(X, conditioning): # need to change the structure
z_combine = tf.concat([X, conditioning], 1)
D_h1_real = tf.nn.relu(tf.matmul(z_combine / 4, D_W1) + D_b1)
#D_h2_real = tf.reduce_mean(tf.nn.relu(tf.matmul(D_h1_real, D_W2) + D_b2), axis=0, keep_dims=True)
D_h2_real = tf.nn.relu(tf.matmul(D_h1_real, D_W2) + D_b2)
D_h3_real = tf.nn.relu(tf.matmul(D_h2_real, D_W3) + D_b3)
D_logit = tf.matmul(D_h3_real, D_W4) + D_b4
D_prob = tf.nn.sigmoid(D_logit)
return D_prob, D_logit
def sample_Z(sample_size):
''' Sampling the generation noise Z from normal distribution '''
return np.random.normal(size=sample_size)
def xavier_init(size):
in_dim = size[0]
xavier_stddev = 1. / tf.sqrt(in_dim / 2.)
return tf.random_normal(shape=size, stddev=xavier_stddev)
number = 200
h_r = np.random.normal(scale=np.sqrt(2) / 2, size=number)
h_i = np.random.normal(scale=np.sqrt(2) / 2, size=number)
h_complex = h_r + 1j * h_i
def generate_real_samples_with_labels_Rayleigh(number=100):
h_r = np.random.normal(scale=np.sqrt(2) / 2, size=number)
h_i = np.random.normal(scale=np.sqrt(2) / 2, size=number)
h_complex = h_r + 1j * h_i
labels_index = np.random.choice(len(mean_set_QAM), number)
data = mean_set_QAM[labels_index]
received_data = h_complex * data
received_data = np.hstack(
(np.real(received_data).reshape(len(data), 1), np.imag(received_data).reshape(len(data), 1)))
gaussion_random = np.random.multivariate_normal([0, 0], [[0.01, 0], [0, 0.01]], number).astype(np.float32)
received_data = received_data + gaussion_random
conditioning = np.hstack((np.real(data).reshape(len(data), 1), np.imag(data).reshape(len(data), 1),
h_r.reshape(len(data), 1), h_i.reshape(len(data), 1))) / 3
return received_data, conditioning
""" ==== Here is the main function ==== """
mean_set_QAM = np.asarray([-3 - 3j, -3 - 1j, -3 + 1j, -3 + 3j, -1 - 3j, -1 - 1j, -1 + 1j, -1 + 3j,
1 - 3j, 1 - 1j, 1 + 1j, 1 + 3j, 3 - 3j, 3 - 1j, 3 + 1j, 3 + 3j
], dtype=np.complex64)
batch_size = 512
condition_depth = 2
condition_dim = 4
Z_dim = 16
model = 'ChannelGAN_Rayleigh_'
data_size = 10000
data, one_hot_labels = generate_real_samples_with_labels_Rayleigh(data_size)
D_W1 = tf.Variable(xavier_init([2 + condition_dim, 32]))
D_b1 = tf.Variable(tf.zeros(shape=[32]))
D_W2 = tf.Variable(xavier_init([32, 32]))
D_b2 = tf.Variable(tf.zeros(shape=[32]))
D_W3 = tf.Variable(xavier_init([32, 32]))
D_b3 = tf.Variable(tf.zeros(shape=[32]))
D_W4 = tf.Variable(xavier_init([32, 1]))
D_b4 = tf.Variable(tf.zeros(shape=[1]))
theta_D = [D_W1, D_W2, D_W3, D_b1, D_b2, D_b3, D_W4, D_b4]
G_W1 = tf.Variable(xavier_init([Z_dim + condition_dim, 128]))
G_b1 = tf.Variable(tf.zeros(shape=[128]))
G_W2 = tf.Variable(xavier_init([128, 128]))
G_b2 = tf.Variable(tf.zeros(shape=[128]))
G_W3 = tf.Variable(xavier_init([128, 128]))
G_b3 = tf.Variable(tf.zeros(shape=[128]))
G_W4 = tf.Variable(xavier_init([128, 2]))
G_b4 = tf.Variable(tf.zeros(shape=[2]))
theta_G = [G_W1, G_W2, G_W3, G_b1, G_b2, G_b3, G_W4, G_b4]
R_sample = tf.placeholder(tf.float32, shape=[None, 2])
Z = tf.placeholder(tf.float32, shape=[None, Z_dim])
Condition = tf.placeholder(tf.float32, shape=[None, condition_dim])
G_sample = generator_conditional(Z, Condition)
D_prob_real, D_logit_real = discriminator_conditional(R_sample, Condition)
D_prob_fake, D_logit_fake = discriminator_conditional(G_sample, Condition)
D_loss = tf.reduce_mean(D_logit_fake) - tf.reduce_mean(D_logit_real)
G_loss = -1 * tf.reduce_mean(D_logit_fake)
lambdda = 5
alpha = tf.random_uniform(shape=tf.shape(R_sample), minval=0., maxval=1.)
differences = G_sample - R_sample
interpolates = R_sample + (alpha * differences)
_, D_inter = discriminator_conditional(interpolates, Condition)
gradients = tf.gradients(D_inter, [interpolates])[0]
slopes = tf.sqrt(tf.reduce_sum(tf.square(gradients), reduction_indices=[1]))
gradient_penalty = tf.reduce_mean((slopes - 1.0) ** 2)
D_loss += lambdda * gradient_penalty
D_solver = tf.train.AdamOptimizer(learning_rate=1e-4, beta1=0.5, beta2=0.9).minimize(D_loss, var_list=theta_D)
G_solver = tf.train.AdamOptimizer(learning_rate=1e-4, beta1=0.5, beta2=0.9).minimize(G_loss, var_list=theta_G)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
save_fig_path = model+"images"
if not os.path.exists(save_fig_path):
os.makedirs(save_fig_path)
i = 0
plt.figure(figsize=(5, 5))
plt.plot(data[:1000, 0], data[:1000, 1], 'b.')
# axes = plt.gca()
# axes.set_xlim([-4, 4])
# axes.set_ylim([-4, 4])
# plt.title('True data distribution')
# plt.savefig(save_fig_path + '/real.png', bbox_inches='tight')
np_samples = []
plot_every = 1000
plt.figure(figsize=(5, 5))
xmax = 4
saver = tf.train.Saver()
for it in range(750000):
start_idx = it * batch_size % data_size
if start_idx + batch_size >= len(data):
continue
X_mb = data[start_idx:start_idx + batch_size, :]
one_hot_labels_mb = one_hot_labels[start_idx:start_idx + batch_size, :]
for d_idx in range(10):
_, D_loss_curr = sess.run([D_solver, D_loss],
feed_dict={R_sample: X_mb, Z: sample_Z((batch_size, Z_dim)),
Condition: one_hot_labels_mb})
# print("Inner loop Losses: D are", D_loss_curr)
# print("start_idx is", start_idx, "shape of one hot label", one_hot_labels_mb.shape, X_mb.shape )
#_, D_loss_curr = sess.run([D_solver, D_loss],
# feed_dict={R_sample: X_mb, Z: sample_Z((batch_size, Z_dim)), Condition: one_hot_labels_mb})
_, G_loss_curr = sess.run([G_solver, G_loss],
feed_dict={R_sample: X_mb, Z: sample_Z((batch_size, Z_dim)), Condition: one_hot_labels_mb})
if (it + 1) % plot_every == 0:
save_path = saver.save(sess, './Models/ChannelGAN_model_step_' + str(it) + '.ckpt')
print("Start Plotting")
colors = ['b.', 'r+', 'm.', 'c.', 'k.', 'g.', 'y.', 'm.', \
'bo', 'ro', 'mo', 'co', 'ko', 'go', 'yo', 'bo']
colors = ['b.', 'b+', 'bx', 'b^', 'b^', 'bx', 'b+', 'b.', \
'b.', 'b+', 'bx', 'b^', 'b^', 'bx', 'b+', 'b.']
plt.clf()
samples = np.array([])
for channel_idx in range(10):
plt.clf()
number = 20 #
h_r = np.random.normal(scale=np.sqrt(2) / 2)
h_i = np.random.normal(scale=np.sqrt(2) / 2)
h_r = np.tile(h_r, number)
h_i = np.tile(h_i, number)
for idx in range(len(mean_set_QAM)):
labels_index = np.tile(idx, number)
h_complex = h_r + 1j * h_i
# labels_index = np.random.choice(len(mean_set_QAM), number)
data_t = mean_set_QAM[labels_index]
transmit_data = h_complex * data_t
# print("shapes", transmit_data.shape, h_complex.shape, data_t.shape)
transmit_data = np.hstack((np.real(transmit_data).reshape(len(transmit_data), 1),
np.imag(transmit_data).reshape(len(transmit_data), 1)))
gaussion_random = np.random.multivariate_normal([0, 0], [[0.03, 0], [0, 0.03]], number).astype(
np.float32)
received_data = transmit_data + gaussion_random
conditioning = np.hstack(
(np.real(data_t).reshape(len(data_t), 1), np.imag(data_t).reshape(len(data_t), 1),
h_r.reshape(len(data_t), 1), h_i.reshape(len(data_t), 1))) /3
samples_component = sess.run(G_sample, feed_dict={Z: sample_Z((number, Z_dim)), Condition: conditioning})
plt.plot(samples_component[:, 0], samples_component[:, 1], colors[idx])
plt.plot(transmit_data[:, 0], transmit_data[:, 1], colors[idx])
#plt.plot(samples_component[:, 0], samples_component[:, 1], 'k.')
#plt.plot(transmit_data[:, 0], transmit_data[:, 1], 'b*')
axes = plt.gca()
axes.set_xlim([-4, 4])
axes.set_ylim([-4, 4])
xlabel = r'$Re\{y_n\}$'
ylabel = r'$Imag\{y_n\}$'
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.show()
plt.savefig( save_fig_path + '/' + str(channel_idx) + '_{}_noise_1.eps'.format(str(i).zfill(3)),
bbox_inches='tight')
plt.savefig(save_fig_path + '/' + str(channel_idx) + '_{}_noise_1.png'.format(str(i).zfill(3)),
bbox_inches='tight')
axes.set_xlim([-4, 4])
axes.set_ylim([-4, 4])
plt.title('Iter: {}, loss(D): {:2.2f}, loss(G):{:2.2f}'.format(it + 1, D_loss_curr, G_loss_curr))
plt.savefig(save_fig_path + '/{}.png'.format(str(i).zfill(3)), bbox_inches='tight')
i += 1