forked from developmentseed/label-maker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresnet.py
88 lines (70 loc) · 2.59 KB
/
resnet.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
"""Demonstrate ResNet50 training on label-maker prepared data"""
from __future__ import print_function
import numpy as np
import keras
from keras.applications.resnet50 import ResNet50
from keras.preprocessing.image import ImageDataGenerator
from keras import backend as K
batch_size = 16
num_classes = 2
epochs = 50
# input image dimensions
img_rows, img_cols = 256, 256
# the data, shuffled and split between train and test sets
npz = np.load('data.npz')
x_train = npz['x_train']
y_train = npz['y_train']
x_test = npz['x_test']
y_test = npz['y_test']
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 3, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 3, img_rows, img_cols)
input_shape = (3, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 3)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 3)
input_shape = (img_rows, img_cols, 3)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
# weight classes to account for differences in class frequencies
non_background = np.sum(y_train, axis=0)[1]
class_weight = {
0: 1,
1: (y_train.shape[0] - non_background) / non_background
}
x_train /= 255
x_test /= 255
# normalize the images
img_mean = np.mean(x_train, axis=(0, 1, 2))
img_std = np.std(x_train, axis=(0, 1, 2))
x_train -= img_mean
x_train /= img_std
x_test -= img_mean
x_test /= img_std
print('class_weight', class_weight)
model = ResNet50(weights=None,
input_shape=input_shape,
classes=num_classes)
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.SGD(lr=0.01, momentum=0.0, decay=0.0, nesterov=False),
metrics=['accuracy'])
datagen = ImageDataGenerator(
rotation_range=180, # randomly rotate images in the range (degrees, 0 to 180)
horizontal_flip=True, # randomly flip images
vertical_flip=False
)
# Fit the model on the batches generated by datagen.flow().
model.fit_generator(datagen.flow(x_train, y_train, batch_size=batch_size),
steps_per_epoch=int(x_train.shape[0] / batch_size),
epochs=epochs,
validation_data=(x_test, y_test),
verbose=1,
class_weight=class_weight,
workers=4)
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
model.save('model.h5')