Kaggle competition: Open Images 2019 - Object Detection
<SOS> metric: OpenImagesObjectDetectionAP Kaggle data source: open-images-2019-object-detection<predict_on_test>
import os
from pprint import pprint
from six import BytesIO
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
import tensorflow_hub as hub
from PIL import Image, ImageColor, ImageDraw, ImageFont, ImageOps
from tqdm import tqdm
test_data_loader = torch.utils.data.DataLoader(test_dataset, batch_size=32, shuffle=False, num_workers=4)
 test_preds3 = np.zeros(( len(test_dataset), 1))
tk0 = tqdm(test_data_loader)
 for i, x_batch in enumerate(tk0):
x_batch = x_batch["image"]
pred = model(x_batch.to(device))
test_preds3[i * 32:(i + 1)* 32] = pred.detach().cpu().squeeze().numpy().ravel().reshape(-1, 1 )<predict_on_test>
def format_prediction_string(image_id, result):
prediction_strings = []
for i in range(len(result['detection_scores'])) :
class_name = result['detection_class_names'][i].decode("utf-8")
 YMin,XMin,YMax,XMax = result['detection_boxes'][i]
score = result['detection_scores'][i]
prediction_strings.append(
 f"{class_name} {score} {XMin} {YMin} {XMax} {YMax}" 
)
 prediction_string = " ".join(prediction_strings)
 return {
"ImageID": image_id,
"PredictionString": prediction_string
}
test_data_loader = torch.utils.data.DataLoader(test_dataset, batch_size=32, shuffle=False, num_workers=4)
 test_preds4 = np.zeros(( len(test_dataset), 1))
tk0 = tqdm(test_data_loader)
 for i, x_batch in enumerate(tk0):
x_batch = x_batch["image"]
pred = model(x_batch.to(device))
test_preds4[i * 32:(i + 1)* 32] = pred.detach().cpu().squeeze().numpy().ravel().reshape(-1, 1 )<predict_on_test>
sample_image_path = ".. /input/test/6beb79b52308112d.jpg"
with tf.Graph().as_default() :
image_string_placeholder = tf.placeholder(tf.string)
 decoded_image = tf.image.decode_jpeg(image_string_placeholder)
 decoded_image_float = tf.image.convert_image_dtype(
 image=decoded_image, dtype=tf.float32 
)
 image_tensor = tf.expand_dims(decoded_image_float, 0)
 model_url = "https://tfhub.dev/google/openimages_v4/ssd/mobilenet_v2/1"
detector = hub.Module(model_url)
 detector_output = detector(image_tensor, as_dict=True)
 init_ops = [tf.global_variables_initializer() , tf.tables_initializer() ]
sess = tf.Session()
sess.run(init_ops)
 with tf.gfile.Open(sample_image_path, "rb")as binfile:
image_string = binfile.read()
result_out, image_out = sess.run(
 [detector_output, decoded_image],
feed_dict={image_string_placeholder: image_string}
)
test_data_loader = torch.utils.data.DataLoader(test_dataset, batch_size=32, shuffle=False, num_workers=4)
 test_preds5 = np.zeros(( len(test_dataset), 1))
tk0 = tqdm(test_data_loader)
 for i, x_batch in enumerate(tk0):
x_batch = x_batch["image"]
pred = model(x_batch.to(device))
test_preds5[i * 32:(i + 1)* 32] = pred.detach().cpu().squeeze().numpy().ravel().reshape(-1, 1 )<predict_on_test>
print(image_string_placeholder)
 print(decoded_image)
 print(decoded_image_float)
 print(image_tensor )
test_data_loader = torch.utils.data.DataLoader(test_dataset, batch_size=32, shuffle=False, num_workers=4)
 test_preds6 = np.zeros(( len(test_dataset), 1))
tk0 = tqdm(test_data_loader)
 for i, x_batch in enumerate(tk0):
x_batch = x_batch["image"]
pred = model(x_batch.to(device))
test_preds6[i * 32:(i + 1)* 32] = pred.detach().cpu().squeeze().numpy().ravel().reshape(-1, 1 )<predict_on_test>
sample_submission_df = pd.read_csv('.. /input/sample_submission.csv')
 image_ids = sample_submission_df['ImageId']
predictions = []
for image_id in tqdm(image_ids):
image_path = f'.. /input/test/{image_id}.jpg'
with tf.gfile.Open(image_path, "rb")as binfile:
image_string = binfile.read()
result_out = sess.run(
 detector_output,
feed_dict={image_string_placeholder: image_string} 
)
 predictions.append(format_prediction_string(image_id, result_out))
sess.close()
test_data_loader = torch.utils.data.DataLoader(test_dataset, batch_size=32, shuffle=False, num_workers=4)
 test_preds7 = np.zeros(( len(test_dataset), 1))
tk0 = tqdm(test_data_loader)
 for i, x_batch in enumerate(tk0):
x_batch = x_batch["image"]
pred = model(x_batch.to(device))
test_preds7[i * 32:(i + 1)* 32] = pred.detach().cpu().squeeze().numpy().ravel().reshape(-1, 1 )<predict_on_test>
pred_df = pd.DataFrame(predictions)
 pred_df.head()
<predict_on_test><EOS> 
pred_df.to_csv('submission.csv', index=False )