forked from tnaduc/Distracted_Driver_Detect_Classify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StateFarm_2.py
143 lines (119 loc) · 5.15 KB
/
StateFarm_2.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
import math, os, sys
import pickle
from glob import glob
import numpy as np
from numpy.random import random, permutation, randn, normal
from matplotlib import pyplot as plt
#%matplotlib inline
import PIL
from PIL import Image
import bcolz
from shutil import copyfile
from shutil import move
import keras
from keras import backend as K
from keras.utils.data_utils import get_file
from keras.models import Sequential, Model
from keras.layers.core import Flatten, Dense, Dropout, Lambda
from keras.layers import Input
from keras.layers.convolutional import Conv2D, MaxPooling2D, ZeroPadding2D
from keras.optimizers import SGD, RMSprop, Adam
from keras.preprocessing import image
from keras.layers.normalization import BatchNormalization
from keras.utils.np_utils import to_categorical
from keras.metrics import categorical_crossentropy
from keras.regularizers import l2,l1
current_dir = os.getcwd()
path = current_dir + '/data/'
test_path = path +'test/'
results_path = path + 'results/'
train_path = path+ 'train/'
valid_path = path+ 'valid/'
batch_size =1;
def get_batches(dirname, gen=image.ImageDataGenerator(), shuffle=True,
batch_size=batch_size, target_size=(224,224), class_mode='categorical'):
return gen.flow_from_directory(path+dirname, target_size,
class_mode=class_mode, shuffle=shuffle, batch_size=batch_size)
def plots(ims, figsize=(12,6), rows=1, interp=False, titles=None):
if type(ims[0]) is np.ndarray:
ims = np.array(ims).astype(np.uint8)
if (ims.shape[-1] != 3):
ims = ims.transpose((0,2,3,1))
f = plt.figure(figsize=figsize)
for i in range(len(ims)):
sp = f.add_subplot(rows, len(ims)//rows, i+1)
sp.axis('Off')
if titles is not None:
sp.set_title(titles[i], fontsize=16)
plt.imshow(ims[i], interpolation=None if interp else 'none')
def get_classes(path):
batches = get_batches('train', shuffle=False, batch_size=1)
val_batches = get_batches('valid', shuffle=False, batch_size=1)
#test_batches = get_batches('test', shuffle=False, batch_size=1)
return (val_batches.classes, batches.classes,to_categorical(val_batches.classes),
to_categorical(batches.classes),val_batches.filenames, batches.filenames)
# test_batches.filenames)
def get_data(path, target_size = (224,224)):
batches = get_batches(path, shuffle=False, batch_size=1, class_mode=None, target_size=target_size)
return np.concatenate([batches.next() for i in range (len(batches.classes))])
def save_array(fname, arr):
c=bcolz.carray(arr, rootdir=fname, mode='w')
c.flush()
def load_array(fname):
return bcolz.open(fname)[:]
# Roll into pixcel matrix
#train_data = get_data('train')
#valid_data = get_data('valid')
#save_array(path+'results/train_data.dat', train_data)
#save_array(path+'results/valid_data.dat', valid_data)
# (val_classes, trn_classes, val_labels, trn_labels, val_filenames, filenames,
# test_filename) = get_classes(path)
(valid_classes, train_classes, valid_labels, train_labels, valid_filenames, train_filenames) = get_classes(path)
valid_data = load_array(path+'results/valid_data.dat')
train_data = load_array(path+'results/train_data.dat')
gen = image.ImageDataGenerator(rotation_range=15, height_shift_range=0.05,
shear_range=0.1, channel_shift_range=20, width_shift_range=0.1)
train_batches = get_batches(path+'train', gen, batch_size=batch_size)
valid_batches = get_batches(path+'valid', batch_size=batch_size*2, shuffle=False)
model = Sequential([
BatchNormalization(input_shape=(224,224,3)),
Conv2D(32,3,3, activation='relu'),
BatchNormalization(axis=1),
MaxPooling2D(),
Conv2D(64,3,3, activation='relu'),
BatchNormalization(axis=1),
MaxPooling2D(),
Conv2D(128,3,3, activation='relu'),
BatchNormalization(axis=1),
MaxPooling2D(),
Flatten(),
Dense(200, activation='relu'),
BatchNormalization(),
Dropout(0.5),
Dense(200, activation='relu'),
BatchNormalization(),
Dropout(0.5),
Dense(10, activation='softmax')
])
model.compile(Adam(lr=10e-5), loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
batch_size=32
Ex1_history = model.fit(train_data,train_labels, batch_size=batch_size, epochs=5, validation_data =(valid_data,valid_labels))
model.fit_generator(batches, len(batches.classes), epochs=2, validation_data=valid_batches,
nb_val_samples=len(valid_batches.classes))
plt.figure(1)
plt.subplot(211)
plt.plot(Ex1_history.history['acc'])
plt.plot(Ex1_history.history['val_acc'])
plt.title('accuracy')
plt.ylabel('accuracy')
plt.legend(['train', 'validation'], loc='upper left')
plt.subplot(212)
plt.plot(Ex1_history.history['loss'])
plt.plot(Ex1_history.history['val_loss'])
plt.title('loss')
plt.ylabel('loss')
plt.xlabel('epoches')
plt.legend(['train', 'validation'], loc='upper left')
plt.savefig(results_path+'/train_history/Exp2_train_history_1.png', bbox_inches='tight')
plt.show()