Kaggle competition: Open Images 2019 - Object Detection
<SOS> metric: OpenImagesObjectDetectionAP Kaggle data source: open-images-2019-object-detection<predict_on_test>
import pandas as pd
import tensorflow as tf
import tensorflow_hub as hub
from tqdm import tqdm
test_data_loader = torch.utils.data.DataLoader(test_dataset, batch_size=32, shuffle=False, num_workers=4)
 test_preds10 = 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_preds10[i * 32:(i + 1)* 32] = pred.detach().cpu().squeeze().numpy().ravel().reshape(-1, 1 )<compute_test_metric>
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")
 corrected_coordinates = [result['detection_boxes'][i][1], result['detection_boxes'][i][0], result['detection_boxes'][i][3], result['detection_boxes'][i][2]]
boxes = corrected_coordinates
score = result['detection_scores'][i]
prediction_strings.append(
 f"{class_name} {score} " + " ".join(map(str, boxes)) 
)
 prediction_string = " ".join(prediction_strings)
 return {
"ImageID": image_id,
"PredictionString": prediction_string
}
<save_to_csv><EOS> 
sample_submission_df = pd.read_csv('.. /input/sample_submission.csv')
 image_ids = sample_submission_df['ImageId']
predictions = []
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)
 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()
pred_df = pd.DataFrame(predictions)
 pred_df.to_csv('submission.csv', index=False )