Kaggle competition: Global Wheat Detection
model = Sequential()
model.add(Conv2D(filters=16, kernel_size=5, padding='same', activation='relu', input_shape=(28, 28, 1)))
 model.add(Conv2D(filters=16, kernel_size=5, padding='same', activation='relu'))
model.add(BatchNormalization())
 model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.4))
model.add(Conv2D(filters=32, kernel_size=5, padding='same', activation='relu'))
model.add(Conv2D(filters=32, kernel_size=5, padding='same', activation='relu'))
model.add(BatchNormalization())
 model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.4))
model.add(Conv2D(filters=64, kernel_size=5, padding='same', activation='relu'))
model.add(Conv2D(filters=64, kernel_size=5, padding='same', activation='relu'))
model.add(BatchNormalization())
 model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.4))
model.add(Flatten())
 model.add(Dense(512, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1024, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'] )<train_model>
%matplotlib inline
sns.set()
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
 WEIGHTS_FILE = 'weights.base.hdf5'
epochs = 100
checkpointer = ModelCheckpoint(filepath='WEIGHTS_FILE',
verbose=1, save_best_only=True)
 history = model.fit(X_train,
y_train,
validation_data=(X_test, y_test),
epochs=epochs,
batch_size=200,
callbacks=[checkpointer],
verbose=1 )<predict_on_test>
def detect(save_img=False):
weights, imgsz = opt.weights,opt.img_size
source = '/kaggle/input/global-wheat-detection/test'
device = torch_utils.select_device(opt.device)
 half = device.type != 'cpu'
model = torch.load(weights, map_location=device)['model'].to(device ).eval()
if half:
model.half()
dataset = LoadImages(source, img_size=1024)
 t0 = time.time()
img = torch.zeros(( 1, 3, imgsz, imgsz), device=device)
 results=[]
_ = model(img.half() if half else img)if device.type != 'cpu' else None
for path, img, im0s, vid_cap in dataset:
print(im0s.shape)
 im0s = cv2.cvtColor(im0s, cv2.COLOR_BGR2RGB)
 image_id = path.split("/")[-1].split(".")[0]
img = torch.from_numpy(img ).to(device)
 img = img.half() if half else img.float()
img /= 255.0
if img.ndimension() == 3:
img = img.unsqueeze(0)
 t1 = torch_utils.time_synchronized()
if True:
pred = model(img, augment=opt.augment)[0]
pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=None, merge=opt.merge)
 t2 = torch_utils.time_synchronized()
box_scores = []
for i, det in enumerate(pred):
p, s, im0 = path, '', im0s
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]
if det is not None and len(det):
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape ).round()
for c in det[:, -1].unique() :
n =(det[:, -1] == c ).sum()
for *xyxy, conf, cls in det:
if True:
xywh =(xyxy2xywh(torch.tensor(xyxy ).view(1, 4)) / gn ).view(-1 ).tolist()
c1, c2 =(int(xyxy[0]), int(xyxy[1])) ,(int(xyxy[2])- int(xyxy[0]), int(xyxy[3])- int(xyxy[1]))
box_scores.append(f"{round(conf.item() ,2)} {c1[0]} {c1[1]} {c2[0]} {c2[1]}")
 cv2.putText(im0s, '{:.2}'.format(conf.item()),(c1[0],c1[1]-10), cv2.FONT_HERSHEY_SIMPLEX ,1,(255,255,255), 2, cv2.LINE_AA)
 cv2.rectangle(im0s, c1,(c2[0]+c1[0], c2[1]+c1[1]),(255,255,255),2)
 result={'image_id': image_id, "PredictionString": " ".join(box_scores)}
fig = plt.figure(figsize=(50, 50))
a = fig.add_subplot(1, 4, 1)
 imgplot = plt.imshow(im0s)
 results.append(result)
 return results
print(features_test.shape)
 predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0)))for tensor in features_test]
print(np.array(predictions))<set_options>
class opt:
weights = ".. /input/20200704-1-yolov5-ricardo/20200704_1.pt"
img_size = 1024
conf_thres = 0.45
iou_thres = 0.45
augment = True
merge = True
device = '0'
classes=None
agnostic_nms = True
opt.img_size = check_img_size(opt.img_size)
 print(opt)
 with torch.no_grad() :
res = detect()
!rm weights.base.hdf5<save_to_csv>
test_df = pd.DataFrame(res, columns=['image_id', 'PredictionString'])
 print(test_df )
print(np.array(predictions))
predictions_df = pd.DataFrame(np.array(predictions), columns = ['Label'])
 predictions_df.reset_index(level=0, inplace=True)
 predictions_df.columns = ['id', 'label']
predictions_df.index += 1
predictions_df.to_csv('predictions.csv', index = False)
 predictions_df.head()<set_options>
test_df.to_csv("/kaggle/working/submission.csv",index=False )
<load_from_csv><EOS> 
!cat submission.csv