-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
141 lines (117 loc) · 5.18 KB
/
main.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
# Import all the things we need ---
# by setting env variables before Keras import you can set up which backend and which GPU it uses
import os,random
os.environ["KERAS_BACKEND"] = "tensorflow"
# os.environ["THEANO_FLAGS"] = "device=gpu%d"%(0)
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import numpy as np
import matplotlib
matplotlib.use('Tkagg')
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
#from matplotlib import pyplot as plt
import pickle, random, sys
import keras
import keras.backend as K
from keras.callbacks import LearningRateScheduler,TensorBoard
from keras.optimizers import adam
import csv
import mltools,rmldataset2016
import rmlmodels.CNN2Model as cnn2
#set Keras data format as channels_first
K.set_image_data_format('channels_last')
print(K.image_data_format())
(mods,snrs,lbl),(X_train,Y_train),(X_val,Y_val),(X_test,Y_test),(train_idx,val_idx,test_idx) = \
rmldataset2016.load_data()
in_shp = list(X_train.shape[1:])
print(X_train.shape, in_shp)
classes = mods
print(classes)
# Set up some params
nb_epoch = 10000 # number of epochs to train on
batch_size = 400 # training batch size
model = cnn2.CNN2Model(None, input_shape=in_shp,classes=len(classes))
model.compile(loss='categorical_crossentropy',metrics=['accuracy'],optimizer='adam')
model.summary()
filepath = 'weights/weights.h5'
history = model.fit(X_train,
Y_train,
batch_size=batch_size,
epochs=nb_epoch,
verbose=2,
validation_data=[X_val,Y_val],
callbacks = [
keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='auto'),
keras.callbacks.ReduceLROnPlateau(monitor='val_loss',factor=0.5,verbose=1,patince=5,min_lr=0.000001),
keras.callbacks.EarlyStopping(monitor='val_loss', patience=50, verbose=1, mode='auto')
#keras.callbacks.TensorBoard(log_dir='./logs/',histogram_freq=1,write_graph=False,write_grads=1,write_images=False,update_freq='epoch')
]
)
mltools.show_history(history)
#Show simple version of performance
score = model.evaluate(X_test, Y_test, verbose=1, batch_size=batch_size)
print(score)
def predict(model):
# Plot confusion matrix
model.load_weights(filepath)
test_Y_hat = model.predict(X_test, batch_size=batch_size)
confnorm,_,_ = mltools.calculate_confusion_matrix(Y_test,test_Y_hat,classes)
mltools.plot_confusion_matrix(confnorm, labels=['8PSK','AM-DSB','AM-SSB','BPSK','CPFSK','GFSK','4-PAM','16-QAM','64-QAM','QPSK','WBFM'],save_filename='figure/cnn2_total_confusion')
# Plot confusion matrix
acc = {}
acc_mod_snr = np.zeros( (len(classes),len(snrs)) )
i = 0
for snr in snrs:
# extract classes @ SNR
# test_SNRs = map(lambda x: lbl[x][1], test_idx)
test_SNRs = [lbl[x][1] for x in test_idx]
test_X_i = X_test[np.where(np.array(test_SNRs) == snr)]
test_Y_i = Y_test[np.where(np.array(test_SNRs) == snr)]
# estimate classes
test_Y_i_hat = model.predict(test_X_i)
confnorm_i,cor,ncor = mltools.calculate_confusion_matrix(test_Y_i,test_Y_i_hat,classes)
acc[snr] = 1.0 * cor / (cor + ncor)
result = cor / (cor + ncor)
with open('acc111.csv', 'a', newline='') as f0:
write0 = csv.writer(f0)
write0.writerow([result])
mltools.plot_confusion_matrix(confnorm_i, labels=['8PSK','AM-DSB','AM-SSB','BPSK','CPFSK','GFSK','4-PAM','16-QAM','64-QAM','QPSK','WBFM'], title="Confusion Matrix",save_filename="figure/Confusion(SNR=%d)(ACC=%2f).png" % (snr,100.0*acc[snr]))
acc_mod_snr[:,i] = np.round(np.diag(confnorm_i)/np.sum(confnorm_i,axis=1),3)
i = i +1
#plot acc of each mod in one picture
dis_num=11
for g in range(int(np.ceil(acc_mod_snr.shape[0]/dis_num))):
assert (0 <= dis_num <= acc_mod_snr.shape[0])
beg_index = g*dis_num
end_index = np.min([(g+1)*dis_num,acc_mod_snr.shape[0]])
plt.figure(figsize=(12, 10))
plt.xlabel("Signal to Noise Ratio")
plt.ylabel("Classification Accuracy")
plt.title("Classification Accuracy for Each Mod")
for i in range(beg_index,end_index):
plt.plot(snrs, acc_mod_snr[i], label=classes[i])
# 设置数字标签
for x, y in zip(snrs, acc_mod_snr[i]):
plt.text(x, y, y, ha='center', va='bottom', fontsize=8)
plt.legend()
plt.grid()
plt.savefig('figure/acc_with_mod_{}.png'.format(g+1))
plt.close()
#save acc for mod per SNR
fd = open('predictresult/acc_for_mod_on_cnn2.dat', 'wb')
pickle.dump(('128','cnn2', acc_mod_snr), fd)
fd.close()
# Save results to a pickle file for plotting later
print(acc)
fd = open('predictresult/cnn2_d0.5.dat','wb')
pickle.dump( ("CNN2", 0.5, acc) , fd )
# Plot accuracy curve
plt.plot(snrs, list(map(lambda x: acc[x], snrs)))
plt.xlabel("Signal to Noise Ratio")
plt.ylabel("Classification Accuracy")
plt.title("Classification Accuracy on RadioML 2016.10 Alpha")
plt.tight_layout()
plt.savefig('figure/each_acc.png')
plt.close()
predict(model)