-
Notifications
You must be signed in to change notification settings - Fork 0
/
cl1_chNet.py
130 lines (108 loc) · 4.66 KB
/
cl1_chNet.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
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
# Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory
from subprocess import check_output
#print(check_output(["ls", "../input"]).decode("utf8"))
import os
import numpy as np
from tempfile import TemporaryFile
import pandas as pd
import matplotlib.pyplot as plt
import cv2
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
from sklearn import model_selection
import keras
from keras.callbacks import TensorBoard, ModelCheckpoint
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.layers.normalization import BatchNormalization
from keras.preprocessing.image import ImageDataGenerator
from keras.regularizers import l1
#from quiver_engine import server
path = '/home/sepideh/MultiSpectralImages/'
Labels = pd.read_csv(path+'Labels.csv')
wrong_FileName = []
X_ = []
input_size = 28
input_channels = 1
num_chanel = 10
for i in range(len(Labels.iloc[:,0])):
try:
Xi = pd.read_csv(path+str(Labels.iloc[i,1]))
for chanel in range(num_chanel):
img = (np.array(Xi.iloc[:,2:12])[:,chanel]).reshape(350,350)[100:-100,100:-100]
cv2.imwrite(path+str(Labels.iloc[i,1])[:-4]+'_chanel_'+str(chanel)+'.png' ,img)
a = cv2.resize(cv2.imread(path+ str(Labels.iloc[i,1])[:-4]+'_chanel_'+'{}.png'.format(chanel)),
(input_size, input_size), interpolation = cv2.INTER_AREA)
cv2.imwrite(path+str(Labels.iloc[i,1])[:-4]+'_chanel_'+str(chanel)+'res.png',a)
x = np.array(cv2.imread(path+str(Labels.iloc[i,1])[:-4]+'_chanel_'+str(chanel)+'res.png',
cv2.IMREAD_GRAYSCALE))
X_.append(x)
except IOError:
wrong_FileName += [i]
number_of_img = len(Labels.iloc[:,0])-len(wrong_FileName)
X_nparray = np.array(X_) / 255
X = X_nparray.reshape((number_of_img, num_chanel, input_size , input_size ))
Labels_tru = Labels[Labels.loc[:,'FileName'] != str(Labels.iloc[wrong_FileName,1].values)[2:-2]]
class_le = LabelEncoder()
y = class_le.fit_transform(Labels_tru.iloc[:,0].values)
ohe = OneHotEncoder()
Y = ohe.fit_transform(y.reshape(-1,1)).toarray()
outX = TemporaryFile()
outY = TemporaryFile()
np.save(outX, X)
np.save(outY, Y)
train_data, test_data, train_labels, test_labels = model_selection.train_test_split(X, Y,
test_size = 0.2, random_state = 0)
batch_size = 120
num_classes = 20
epochs = 400
input_shape = (num_chanel, input_size, input_size)
l1_lambda = 0.00003
"""
datagen = ImageDataGenerator(
width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)
height_shift_range=0.1, # randomly shift images vertically (fraction of total height)
channel_shift_range = 4)
datagen.fit(train_data)
"""
model = Sequential()
model.add(BatchNormalization(input_shape=input_shape))
model.add(Conv2D(32, kernel_size=(5, 5), strides=(1, 1),
activation='relu',
input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Conv2D(64, (2, 2), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(1000, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
model.summary()
opt = keras.optimizers.Adam()
model.compile(loss='categorical_crossentropy',
optimizer=opt, metrics=['accuracy'])
tensorboard = TensorBoard(log_dir='./logs', write_graph=True)
checkpoint = ModelCheckpoint(filepath=os.path.join(path, "model-{epoch:02d}.h5"))
"""
model.fit_generator(datagen.flow(train_data, train_labels,
batch_size=batch_size),
epochs=epochs,
verbose=1,
validation_data=(test_data, test_labels),
callbacks=[tensorboard])
"""
model.fit(train_data, train_labels,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(test_data, test_labels),
callbacks=[tensorboard, checkpoint])
score = model.evaluate(test_data, test_labels, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# Any results you write to the current directory are saved as output.