-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathSpeFCN.py
187 lines (137 loc) · 6.14 KB
/
SpeFCN.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
# -*- coding: utf-8 -*-
"""
@author: Sonic
"""
import time
import sys
import os
from HyperFunctions import *
import tensorflow as tf
resultpath = './SpectralFCN/'
if not os.path.isdir(resultpath):
os.makedirs(resultpath)
def weight_variable(shape,name=None):
initial = tf.random_uniform(shape,minval=0.01, maxval=0.02)
return tf.Variable(initial,name)
def bias_variable(shape,name=None):
initial = tf.constant(0., shape=shape)
return tf.Variable(initial,name=None)
def conv2d(x, W, p=0):
if p==1:
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
else:
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='VALID')
def max_pool(x,W,p=0):
if p==1:
return tf.nn.max_pool(x, ksize=[1, W, W, 1],
strides=[1, W, W, 1], padding='SAME')
else:
return tf.nn.max_pool(x, ksize=[1, W, W, 1],
strides=[1, W, W, 1], padding='VALID')
def max_pool_padding(x,W):
return tf.nn.max_pool(x, ksize=[1, W, W, 1],
strides=[1, 1, 1, 1], padding='SAME')
def avg_pool_padding(x,W):
return tf.nn.avg_pool(x, ksize=[1, W, W, 1],
strides=[1, 1, 1, 1], padding='SAME')
def one_hot3d(Y):
num_class = np.max(Y)
row,col = Y.shape
y = np.zeros((row,col,num_class),'uint8')
for i in range(1,num_class+1):
index = np.where(Y==i)
y[index[0],index[1],i-1] = 1
return y
x = tf.placeholder(tf.float32, shape=[1,610,340,103])
y_ = tf.placeholder(tf.float32, shape=[1,610,340,9])
idx1 = tf.placeholder(tf.int32, shape=None)
idx2 = tf.placeholder(tf.int32, shape=None)
idx3 = tf.placeholder(tf.int32, shape=None)
W_spectral_conv1 = weight_variable([1,1, 103, 64],'W_spectral_conv1')
b_spectral_conv1 = bias_variable([64],'b_spectral_conv1')
h_spectral_conv1 = tf.nn.relu(conv2d(x, W_spectral_conv1,1) + b_spectral_conv1)
W_spectral_conv2 = weight_variable([1,1, 64, 64],'W_spectral_conv2')
b_spectral_conv2 = bias_variable([64],'b_spectral_conv2')
h_spectral_conv2 = tf.nn.relu(conv2d(h_spectral_conv1, W_spectral_conv2,1) + b_spectral_conv2)
W_spectral_conv3 = weight_variable([1,1,64,64],'W_spectral_conv3')
b_spectral_conv3 = bias_variable([64],'b_spectral_conv3')
h_spectral_conv3 = tf.nn.relu(conv2d(h_spectral_conv2, W_spectral_conv3,1) + b_spectral_conv3)
h_spectral = h_spectral_conv1 + h_spectral_conv2 + h_spectral_conv3
W_conv5 = weight_variable([1,1, 64, 9],'W_conv5')
b_conv5 = bias_variable([9],'b_conv5')
y_conv = tf.nn.relu(conv2d(h_spectral, W_conv5,1) + b_conv5)
y_prob = tf.nn.softmax(y_conv)
y_label = tf.argmax(y_prob,-1)
indices = tf.stack([idx3,idx1,idx2], axis=1)
y_conv_mask = tf.gather_nd(y_conv, indices)
y_mask = tf.gather_nd(y_, indices)
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y_conv_mask, labels=y_mask))
train_step = tf.train.AdamOptimizer(5e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv_mask,-1), tf.argmax(y_mask,-1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
X = sio.loadmat('./DataSets/PaviaU.mat')['paviaU'].astype('float32')
Y = sio.loadmat('./DataSets/PaviaU_gt.mat')['paviaU_gt']
row,col,n_band = X.shape
X = np.reshape(featureNormalize(np.reshape(X,-1),2),(row,col,n_band))
g = Y
img=DrawResult(np.reshape(g,-1),1)
num_class = np.max(Y)
Y_train = np.zeros(Y.shape).astype('int')
n_sample_train = 0
n_sample_test = 0
FCN_spectral = np.zeros((num_class+3,))
gpu_options = tf.GPUOptions(allow_growth=True)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
init = tf.global_variables_initializer()
sess.run(init)
for i in range(1,num_class+1):
index = np.where(Y==i)
n_sample = len(index[0])
array = np.random.permutation(n_sample)
n_per = 150
if i==1:
array1_train = index[0][array[:n_per]]
array2_train = index[1][array[:n_per]]
array1_test = index[0][array[n_per:]]
array2_test = index[1][array[n_per:]]
else:
array1_train = np.concatenate((array1_train,index[0][array[:n_per]]))
array2_train = np.concatenate((array2_train,index[1][array[:n_per]]))
array1_test = np.concatenate((array1_test,index[0][array[n_per:]]))
array2_test = np.concatenate((array2_test,index[1][array[n_per:]]))
Y_train[index[0][array[:n_per]],index[1][array[:n_per]]] = i
n_sample_train += n_per
n_sample_test += n_sample-n_per
array3 = np.zeros(array1_train.shape)
y_train = one_hot3d(Y_train)
y_train = np.reshape(y_train,(1,row,col,num_class))
X_train = np.reshape(X,(1,row,col,n_band))
mask_train = np.zeros(y_train.shape)
for i in range(num_class):
mask_train[:,:,:,i] = np.sum(y_train,-1)
time1 = time.time()
num_epoch = 5000
histloss = np.zeros((num_epoch,2))
for i in range(num_epoch):
train_accuracy = 0
train_loss = 0
sess.run(train_step,feed_dict={x:X_train,y_:y_train,idx1:array1_train,idx2:array2_train,idx3:array3})
if (i+1)%100==0:
train_accuracy,train_loss = sess.run([accuracy,cross_entropy],feed_dict={x:X_train,y_:y_train,idx1:array1_train,idx2:array2_train,idx3:array3})
histloss[i,:] = train_accuracy,train_loss
print("epoch %d, train_accuracy %g, train_loss %g"%(i+1, histloss[i,0],histloss[i,1]))
label = np.squeeze(sess.run(y_label,feed_dict={x:X_train,y_: y_train,idx1:array1_train,idx2:array2_train,idx3:array3}))
prob = np.squeeze(sess.run(y_prob,feed_dict={x:X_train,y_: y_train,idx1:array1_train,idx2:array2_train,idx3:array3}))
y_test = Y[array1_test,array2_test]-1
y_pred = label[array1_test,array2_test]
OA,kappa,ProducerA = CalAccuracy(y_pred,y_test)
FCN_spectral[:num_class] = ProducerA
FCN_spectral[-3] = OA
FCN_spectral[-2] = kappa
time2 = time.time()
FCN_spectral[-1] = time2 - time1
print("Running time: %g"%(FCN_spectral[-1]))
img = DrawResult(np.reshape(label+1,-1),1)
plt.imsave(resultpath+'FCNSpectral'+'_'+repr(int(OA*10000))+'.png',img)
FCN_spectral[:-1] = FCN_spectral[:-1]*100
sio.savemat(resultpath+'FCN_spectral.mat', {'FCN_spectral': FCN_spectral})