Kaggle competition: State Farm Distracted Driver Detection
<SOS> metric: MulticlassLoss Kaggle data source: state-farm-distracted-driver-detection<compute_train_metric>
os.environ['KERAS_BACKEND'] = 'tensorflow'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
warnings.filterwarnings('ignore')
def run_wbf(predictions, image_index, image_size=1024, iou_thr=0.5, skip_box_thr=0.43, weights=None):
boxes = [(prediction[image_index]['boxes']/(image_size-1)).tolist() for prediction in predictions]
scores = [prediction[image_index]['scores'].tolist() for prediction in predictions]
labels = [np.ones(prediction[image_index]['scores'].shape[0] ).astype(int ).tolist() for prediction in predictions]
boxes, scores, labels = ensemble_boxes.ensemble_boxes_wbf.weighted_boxes_fusion(boxes, scores, labels, weights=None, iou_thr=iou_thr, skip_box_thr=skip_box_thr)
 boxes = boxes*(image_size-1)
 return boxes, scores, labels<predict_on_test>
dataset = pd.read_csv('.. /input/driver_imgs_list.csv')
 dataset.head(5 )
results = []
for images, image_ids in test_data_loader:
predictions = make_tta_predictions(images)
 for i, image in enumerate(images):
boxes, scores, labels = run_wbf(predictions, image_index=i)
 boxes = boxes.round().astype(np.int32 ).clip(min=0, max=1023)
 image_id = image_ids[i]
boxes[:, 2] = boxes[:, 2] - boxes[:, 0]
boxes[:, 3] = boxes[:, 3] - boxes[:, 1]
result = {
'image_id': image_id,
'PredictionString': format_prediction_string(boxes, scores)
 }
results.append(result )<prepare_output>
activity_map = {'c0': 'Safe driving',
'c1': 'Texting - right',
'c2': 'Talking on the phone - right',
'c3': 'Texting - left',
'c4': 'Talking on the phone - left',
'c5': 'Operating the radio',
'c6': 'Drinking',
'c7': 'Reaching behind',
'c8': 'Hair and makeup',
'c9': 'Talking to passenger'}
plt.figure(figsize =(12, 20))
image_count = 1
BASE_URL = '.. /input/train/'
for directory in os.listdir(BASE_URL):
if directory[0] != '.':
for i, file in enumerate(os.listdir(BASE_URL + directory)) :
if i == 1:
break
else:
fig = plt.subplot(5, 2, image_count)
 image_count += 1
image = mpimg.imread(BASE_URL + directory + '/' + file)
 plt.imshow(image)
 plt.title(activity_map[directory] )
test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])
 test_df.head()<save_to_csv>
classifier = Sequential()
classifier.add(Conv2D(filters = 128, kernel_size =(3, 3), activation = 'relu', input_shape =(240, 240, 3), data_format = 'channels_last'))
classifier.add(MaxPooling2D(pool_size =(2, 2)))
 classifier.add(Conv2D(filters = 64, kernel_size =(3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size =(2, 2)))
 classifier.add(Conv2D(filters = 32, kernel_size =(3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size =(2, 2)))
 classifier.add(Flatten())
 classifier.add(Dense(units = 1024, activation = 'relu'))
classifier.add(Dense(units = 256, activation = 'relu'))
classifier.add(Dense(units = 10, activation = 'sigmoid'))
classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])
 classifier.summary()
test_df.to_csv('submission.csv', index=False )<import_modules>
train_datagen = ImageDataGenerator(rescale = 1.0/255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True,
validation_split = 0.2)
 training_set = train_datagen.flow_from_directory('.. /input/train',
target_size =(240, 240),
batch_size = 32,
subset = 'training')
 validation_set = train_datagen.flow_from_directory('.. /input/train',
target_size =(240, 240),
batch_size = 32,
subset = 'validation' )
sys.path.insert(0, "/kaggle/input/weightedboxesfusion")
<define_variables>
classifier.fit_generator(training_set,
steps_per_epoch = 17943/32,
epochs = 10,
validation_data = validation_set,
validation_steps = 4481/32 )
DATA_DIR = "/kaggle/input/global-wheat-detection"
MODELS_IN_DIR = "/kaggle/input/frcnnfoldthree"<load_from_csv>
test_file = pd.read_csv('.. /input/sample_submission.csv')
 test_file.head(5 )
test_df = pd.read_csv(os.path.join(DATA_DIR, "sample_submission.csv"))
test_df.shape<feature_engineering>
for i, file in enumerate(test_file['img']):
image = get_data('.. /input/test/' + file)
 image = np.reshape(image,(1, image.shape[0], image.shape[1], image.shape[2]))
result = classifier.predict(image)
 test_file.iloc[i, 1:] = result[0]
<choose_model_class><EOS> 
test_file.to_csv('results.csv', index = False )