Kaggle competition: Peking University/Baidu - Autonomous Driving
<SOS> metric: PKUAutoDrivingAP Kaggle data source: peking-university/baidu-autonomous-driving<train_model>
PATH = '.. /input/pku-autonomous-driving/'
os.listdir(PATH )
lr = 2e-2
reduceLR = callbacks.ReduceLROnPlateauCallback(learn=learn, monitor = 'valid_loss', mode = 'auto', patience = 2, factor = 0.2, min_delta = 0)
 learn.fit_one_cycle(10, lr, callbacks=[reduceLR] )<compute_test_metric>
SWITCH_LOSS_EPOCH = 5
print(torch.__version__ )
print(f'Weighted normalized absolute error(Train): {weighted_nae(yt,yt_truth)[-1]}')
 for i, dv in enumerate(DEP_VAR):
print(f'NAE {dv}(Train): {weighted_nae(yt,yt_truth)[i]}')
 plot_diff(yt, yt_truth )<split>
train = pd.read_csv(PATH + 'train.csv')
 test = pd.read_csv(PATH + 'sample_submission.csv')
 bad_list = ['ID_1a5a10365',
'ID_1db0533c7',
'ID_53c3fe91a',
'ID_408f58e9f',
'ID_4445ae041',
'ID_bb1d991f6',
'ID_c44983aeb',
'ID_f30ebe4d4']
train = train.loc[~train['ImageId'].isin(bad_list)]
camera_matrix = np.array([[2304.5479, 0, 1686.2379],
[0, 2305.8757, 1354.9849],
[0, 0, 1]], dtype=np.float32)
 camera_matrix_inv = np.linalg.inv(camera_matrix)
 train.head()
LOSS_WEIGHTS = [.3,.175,.175,.175,.175]
kf_split = 7
kf = StratifiedKFold(n_splits=kf_split, shuffle=True, random_state=2020)
 y_oof = None
y_truth_oof = None
y_oof_g = None
y_truth_oof_g = None
val_ids = []
for i,(train_id, val_id)in enumerate(kf.split(train_df,y_data['bin_age_7'].values)) :
print('Fold
data = prep_data(BS, val_id.tolist())
 learn = prep_learn(data, loss_base = 'MSE')
 lr = 4e-2
reduceLR = callbacks.ReduceLROnPlateauCallback(learn=learn, monitor = 'valid_loss', mode = 'auto', patience = 2, factor = 0.2, min_delta = 0)
 learn.fit_one_cycle(10, lr, callbacks=[reduceLR])
 val_ids = val_ids+val_id.tolist()
yv, yv_truth= learn.get_preds(ds_type=DatasetType.Valid)
 if y_oof == None:
y_oof = yv
y_truth_oof = yv_truth
else:
y_oof=torch.cat(( y_oof,yv),0)
 y_truth_oof=torch.cat(( y_truth_oof,yv_truth),0)
 print(f'
print(f'Weighted normalized absolute error(Valid): {weighted_nae(y_oof,y_truth_oof)[-1]}')
 for i, dv in enumerate(DEP_VAR):
print(f'NAE {dv}(Valid): {weighted_nae(y_oof,y_truth_oof)[i]}')
 plot_diff(y_oof, y_truth_oof )<compute_test_metric>
def str2coords(s, names=['id', 'yaw', 'pitch', 'roll', 'x', 'y', 'z']):

 coords = []
for l in np.array(s.split() ).reshape([-1, 7]):
coords.append(dict(zip(names, l.astype('float'))))
if 'id' in coords[-1]:
coords[-1]['id'] = int(coords[-1]['id'])
 return coords
offset=torch.tensor([.3,.3,.8,.8,.8])
 print(f'
print(f'Weighted normalized absolute error(Valid): {weighted_nae(y_oof+offset,y_truth_oof)[-1]}')
 for i, dv in enumerate(DEP_VAR):
print(f'NAE {dv}(Valid): {weighted_nae(y_oof+offset,y_truth_oof)[i]}')
 plot_diff(y_oof+offset, y_truth_oof )<prepare_output>
inp = train['PredictionString'][0]
print('Example input:
', inp)
 print()
print('Output:
', str2coords(inp))
def gather_preds(learn, ignore_vars=[], offset = torch.ones(5)) :
preds = learn.get_preds(ds_type=DatasetType.Test)[0]
preds = preds + offset
submission=None
rec_flatt = pd.DataFrame(idx_test)
 rec_flatt.columns=['Id']
for t, tcol in enumerate(DEP_VAR):
if tcol not in ignore_vars:
rec = pd.DataFrame(idx_test)
 rec['Id'] = rec['Id'].astype(str)+'_'+tcol
rec['Predicted'] = preds[:,t]
if isinstance(submission, pd.DataFrame):
submission = submission.append(rec)
 else:
submission = rec
rec_flatt[tcol] = preds[:,t]
return submission, rec_flatt
def make_submission(gathered_preds, filename = ''):
submission = gathered_preds.groupby('Id' ).mean().sort_values('Id' ).reset_index(drop=False)
 print('Shape of submission:', submission.shape)
 display(submission.head(10))
submission.to_csv(filename, index=False )<train_model>
def get_img_coords(s):

 coords = str2coords(s)
 xs = [c['x'] for c in coords]
ys = [c['y'] for c in coords]
zs = [c['z'] for c in coords]
P = np.array(list(zip(xs, ys, zs)) ).T
img_p = np.dot(camera_matrix, P ).T
img_p[:, 0] /= img_p[:, 2]
img_p[:, 1] /= img_p[:, 2]
img_xs = img_p[:, 0]
img_ys = img_p[:, 1]
img_zs = img_p[:, 2]
return img_xs, img_ys
plt.figure(figsize=(14,14))
plt.imshow(imread(PATH + 'train_images/' + train['ImageId'][2217] + '.jpg'))
plt.scatter(*get_img_coords(train['PredictionString'][2217]), color='red', s=100);
data = prep_data(BS, valid_idx = None)
 learn = prep_learn(data)
 lr = 4e-2
learn.fit_one_cycle(10, lr )<save_to_csv>
def euler_to_Rot(yaw, pitch, roll):
Y = np.array([[cos(yaw), 0, sin(yaw)],
[0, 1, 0],
[-sin(yaw), 0, cos(yaw)]])
 P = np.array([[1, 0, 0],
[0, cos(pitch), -sin(pitch)],
[0, sin(pitch), cos(pitch)]])
 R = np.array([[cos(roll), -sin(roll), 0],
[sin(roll), cos(roll), 0],
[0, 0, 1]])
 return np.dot(Y, np.dot(P, R))
gath_pred_no_split, _ = gather_preds(learn)
 make_submission(gath_pred_no_split, filename = 'submission_wo_split.csv' )<split>
IMG_WIDTH = 1600
IMG_HEIGHT = 700
MODEL_SCALE = 8
def _regr_preprocess(regr_dict):
for name in ['x', 'y', 'z']:
regr_dict[name] = regr_dict[name] / 100
regr_dict['roll'] = rotate(regr_dict['roll'], np.pi)
 regr_dict['pitch_sin'] = sin(regr_dict['pitch'])
 regr_dict['pitch_cos'] = cos(regr_dict['pitch'])
 regr_dict.pop('pitch')
 regr_dict.pop('id')
 return regr_dict
def _regr_back(regr_dict):
for name in ['x', 'y', 'z']:
regr_dict[name] = regr_dict[name] * 100
regr_dict['roll'] = rotate(regr_dict['roll'], -np.pi)
 pitch_sin = regr_dict['pitch_sin'] / np.sqrt(regr_dict['pitch_sin']**2 + regr_dict['pitch_cos']**2)
 pitch_cos = regr_dict['pitch_cos'] / np.sqrt(regr_dict['pitch_sin']**2 + regr_dict['pitch_cos']**2)
 regr_dict['pitch'] = np.arccos(pitch_cos)* np.sign(pitch_sin)
 return regr_dict
def preprocess_image(img):
img = img[img.shape[0] // 2:]
bg = np.ones_like(img)* img.mean(1, keepdims=True ).astype(img.dtype)
 bg = bg[:, :img.shape[1] // 4]
img = np.concatenate([bg, img, bg], 1)
 img = cv2.resize(img,(IMG_WIDTH, IMG_HEIGHT))
return(img / 255 ).astype('float32')
 def get_mask_and_regr(img, labels):
mask = np.zeros([IMG_HEIGHT // MODEL_SCALE, IMG_WIDTH // MODEL_SCALE], dtype='float32')
 regr_names = ['x', 'y', 'z', 'yaw', 'pitch', 'roll']
regr = np.zeros([IMG_HEIGHT // MODEL_SCALE, IMG_WIDTH // MODEL_SCALE, 7], dtype='float32')
 coords = str2coords(labels)
 xs, ys = get_img_coords(labels)
 for x, y, regr_dict in zip(xs, ys, coords):
x, y = y, x
x =(x - img.shape[0] // 2)* IMG_HEIGHT /(img.shape[0] // 2)/ MODEL_SCALE
x = np.round(x ).astype('int')
 y =(y + img.shape[1] // 4)* IMG_WIDTH /(img.shape[1] * 1.5)/ MODEL_SCALE
y = np.round(y ).astype('int')
 if x >= 0 and x < IMG_HEIGHT // MODEL_SCALE and y >= 0 and y < IMG_WIDTH // MODEL_SCALE:
mask[x, y] = 1
regr_dict = _regr_preprocess(regr_dict)
 regr[x, y] = [regr_dict[n] for n in sorted(regr_dict)]
return mask, regr
LOSS_WEIGHTS = [.3,.175,.175,.175,.175]
kf_split = 10
kf = StratifiedKFold(n_splits=kf_split, shuffle=True, random_state=2020)
 y_oof = None
y_truth_oof = None
val_ids = []
gathered_preds = None
gathered_preds_flat = None
for i,(train_id, val_id)in enumerate(kf.split(train_df,y_data['bin_age_7'].values)) :
print('Fold
data = prep_data(BS, val_id.tolist())
 learn = prep_learn(data, loss_base = 'MIX')
 lr = 4e-2
reduceLR = callbacks.ReduceLROnPlateauCallback(learn=learn, monitor = 'valid_loss', mode = 'auto', patience = 2, factor = 0.2, min_delta = 0)
 learn.fit_one_cycle(10, lr, callbacks=[reduceLR])
 val_ids = val_ids+val_id.tolist()
yv, yv_truth= learn.get_preds(ds_type=DatasetType.Valid)
 if y_oof == None:
y_oof = yv
y_truth_oof = yv_truth
else:
y_oof=torch.cat(( y_oof,yv),0)
 y_truth_oof=torch.cat(( y_truth_oof,yv_truth),0)
 g_preds, g_preds_flat = gather_preds(learn)
 if isinstance(gathered_preds, pd.DataFrame):
gathered_preds = gathered_preds.append(g_preds)
 gathered_preds_flat = gathered_preds_flat.append(g_preds_flat)
 else:
gathered_preds = g_preds
gathered_preds_flat = g_preds_flat
y_oof_1 = y_oof
y_truth_oof_1 = y_oof
val_ids_1 = val_ids
print(f'K-Fold:',kf_split)
 print(f'Weighted normalized absolute error(Valid): {weighted_nae(y_oof,y_truth_oof)[-1]}')
 for i, dv in enumerate(DEP_VAR):
print(f'NAE {dv}(Valid): {weighted_nae(y_oof,y_truth_oof)[i]}')
 plot_diff(y_oof, y_truth_oof)
 gathered_preds_1 = gathered_preds
gathered_preds_flat_1 = gathered_preds_flat
make_submission(gathered_preds_1.sort_values('Id' ).reset_index(drop=True), filename = 'submission_10fold_MIX.csv')
 make_submission(gathered_preds_flat_1.sort_values('Id' ).reset_index(drop=True), filename = 'mix_test_preds_out.csv' )<save_to_csv>
class CarDataset(Dataset):

 def __init__(self, dataframe, root_dir, training=True, transform=None):
self.df = dataframe
self.root_dir = root_dir
self.transform = transform
self.training = training
def __len__(self):
return len(self.df)
 def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
idx, labels = self.df.values[idx]
img_name = self.root_dir.format(idx)
 img0 = imread(img_name, True)
 img = preprocess_image(img0)
 img = np.rollaxis(img, 2, 0)
 if self.training:
mask, regr = get_mask_and_regr(img0, labels)
 regr = np.rollaxis(regr, 2, 0)
 else:
mask, regr = 0, 0
return [img, mask, regr]
train_preds_out = pd.DataFrame(y_oof_1.numpy() , index=val_ids_1 ).sort_index()
train_preds_out.columns = DEP_VAR
train_preds_out['Id'] = idx_train
train_preds_out.to_csv('mix_train_preds_out.csv', index = False)
 train_preds_out1 = train_preds_out.copy()
train_preds_out1<split>
train_images_dir = PATH + 'train_images/{}.jpg'
test_images_dir = PATH + 'test_images/{}.jpg'
df_train, df_dev = train_test_split(train, test_size=0.1, random_state=63)
 df_test = test
train_dataset = CarDataset(df_train, train_images_dir)
 dev_dataset = CarDataset(df_dev, train_images_dir)
 test_dataset = CarDataset(df_test, test_images_dir )
LOSS_WEIGHTS = [.3,.175,.175,.175,.175]
offset=torch.tensor([.3,.3,.8,.8,.8])
 kf_split = 10
kf = StratifiedKFold(n_splits=kf_split, shuffle=True, random_state=2020)
 y_oof = None
y_truth_oof = None
val_ids = []
gathered_preds = None
gathered_preds_flat = None
for i,(train_id, val_id)in enumerate(kf.split(train_df,y_data['bin_age_7'].values)) :
print('Fold
data = prep_data(BS, val_id.tolist())
 learn = prep_learn(data, loss_base = 'MSE')
 lr = 4e-2
reduceLR = callbacks.ReduceLROnPlateauCallback(learn=learn, monitor = 'valid_loss', mode = 'auto', patience = 2, factor = 0.2, min_delta = 0)
 learn.fit_one_cycle(10, lr, callbacks=[reduceLR])
 val_ids = val_ids+val_id.tolist()
yv, yv_truth= learn.get_preds(ds_type=DatasetType.Valid)
 if y_oof == None:
y_oof = yv
y_truth_oof = yv_truth
else:
y_oof=torch.cat(( y_oof,yv),0)
 y_truth_oof=torch.cat(( y_truth_oof,yv_truth),0)
 g_preds, g_preds_flat = gather_preds(learn, offset = offset)
 if isinstance(gathered_preds, pd.DataFrame):
gathered_preds_flat = gathered_preds_flat.append(g_preds_flat)
 gathered_preds = gathered_preds.append(g_preds)
 else:
gathered_preds = g_preds
gathered_preds_flat = g_preds_flat
y_oof_2 = y_oof
y_truth_oof_2 = y_oof
val_ids_2 = val_ids
print(f'K-Fold with offset:',kf_split)
 print(f'Weighted normalized absolute error(Valid): {weighted_nae(y_oof,y_truth_oof)[-1]}')
 for i, dv in enumerate(DEP_VAR):
print(f'NAE {dv}(Valid): {weighted_nae(y_oof,y_truth_oof)[i]}')
 plot_diff(y_oof, y_truth_oof)
 gathered_preds_2 = gathered_preds
gathered_preds_flat_2 = gathered_preds_flat
make_submission(gathered_preds_2.sort_values('Id' ).reset_index(drop=True), filename = 'submission_10fold_MSE_offset.csv')
 make_submission(gathered_preds_flat_2.sort_values('Id' ).reset_index(drop=True), filename = 'mse_test_preds_out.csv' )<save_to_csv>
BATCH_SIZE = 1
train_loader = DataLoader(dataset=train_dataset, batch_size=BATCH_SIZE, shuffle=True, num_workers=0)
 dev_loader = DataLoader(dataset=dev_dataset, batch_size=BATCH_SIZE, shuffle=False, num_workers=0)
 test_loader = DataLoader(dataset=test_dataset, batch_size=BATCH_SIZE, shuffle=False, num_workers=4 )
train_preds_out = pd.DataFrame(y_oof_2.numpy() , index=val_ids_2 ).sort_index()
train_preds_out.columns = DEP_VAR
train_preds_out['Id'] = idx_train
train_preds_out.to_csv('mse_train_preds_out.csv', index = False)
 train_preds_out2 = train_preds_out.copy()
train_preds_out2<import_modules>
class double_conv(nn.Module):

 def __init__(self, in_ch, out_ch):
super(double_conv, self ).__init__()
self.conv = nn.Sequential(
 nn.Conv2d(in_ch, out_ch, 3, padding=1),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True),
nn.Conv2d(out_ch, out_ch, 3, padding=1),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True)
)
 def forward(self, x):
x = self.conv(x)
 return x
class up(nn.Module):
def __init__(self, in_ch, out_ch, bilinear=True):
super(up, self ).__init__()
if bilinear:
self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
 else:
self.up = nn.ConvTranspose2d(in_ch//2, in_ch//2, 2, stride=2)
 self.conv = double_conv(in_ch, out_ch)
 def forward(self, x1, x2=None):
x1 = self.up(x1)
 diffY = x2.size() [2] - x1.size() [2]
diffX = x2.size() [3] - x1.size() [3]
x1 = F.pad(x1,(diffX // 2, diffX - diffX//2,
diffY // 2, diffY - diffY//2))
if x2 is not None:
x = torch.cat([x2, x1], dim=1)
 else:
x = x1
x = self.conv(x)
 return x
def get_mesh(batch_size, shape_x, shape_y):
mg_x, mg_y = np.meshgrid(np.linspace(0, 1, shape_y), np.linspace(0, 1, shape_x))
mg_x = np.tile(mg_x[None, None, :, :], [batch_size, 1, 1, 1] ).astype('float32')
 mg_y = np.tile(mg_y[None, None, :, :], [batch_size, 1, 1, 1] ).astype('float32')
 mesh = torch.cat([torch.tensor(mg_x ).to(device), torch.tensor(mg_y ).to(device)], 1)
 return mesh
import numpy as np
import pandas as pd
import os
from tqdm import tqdm<load_from_csv>
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
'densenet201': 'https://download.pytorch.org/models/densenet201-c1103571.pth',
'inceptionresnetv2': 'http://data.lip6.fr/cadene/pretrainedmodels/inceptionresnetv2-520b38e4.pth',
}
def conv3x3(in_planes, out_planes, stride=1):

 return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
 def conv1x1(in_planes, out_planes, stride=1):

 return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
 class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1):
super(BasicBlock, self ).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
 self.bn1 = nn.GroupNorm(16, planes)
 self.conv2 = conv3x3(planes, planes)
 self.bn2 = nn.GroupNorm(16, planes)
 if stride != 1 or inplanes != planes:
self.downsample = nn.Sequential(
 conv1x1(inplanes, planes, stride), nn.GroupNorm(16, planes))
else:
self.downsample = None
def forward(self, x):
identity = x
out = F.relu(self.bn1(self.conv1(x)) , inplace=True)
 out = self.bn2(self.conv2(out))
if self.downsample is not None:
identity = self.downsample(x)
 out += identity
out = F.relu(out, inplace=True)
 return out
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1):
super(Bottleneck, self ).__init__()
self.conv1 = conv1x1(inplanes, planes)
 self.bn1 = nn.GroupNorm(16, planes)
 self.conv2 = conv3x3(planes, planes, stride)
 self.bn2 = nn.GroupNorm(16, planes)
 self.conv3 = conv1x1(planes, planes * self.expansion)
 self.bn3 = nn.GroupNorm(16, planes * self.expansion)
 if stride != 1 or inplanes != planes * self.expansion:
self.downsample = nn.Sequential(
 conv1x1(inplanes, planes * self.expansion, stride),
nn.GroupNorm(16, planes * self.expansion))
else:
self.downsample = None
def forward(self, x):
identity = x
out = F.relu(self.bn1(self.conv1(x)) , inplace=True)
 out = F.relu(self.bn2(self.conv2(out)) , inplace=True)
 out = self.bn3(self.conv3(out))
if self.downsample is not None:
identity = self.downsample(x)
 out += identity
out = F.relu(out)
 return out
class ResNetFeatures(nn.Module):
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False):
super(ResNetFeatures, self ).__init__()
self.inplanes = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
 self.bn1 = nn.GroupNorm(16, 64)
 self.layer1 = self._make_layer(block, 64, layers[0])
 self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
 self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
 self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
 for m in self.modules() :
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
 elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
 nn.init.constant_(m.bias, 0)
 if zero_init_residual:
for m in self.modules() :
if isinstance(m, Bottleneck):
nn.init.constant_(m.bn3.weight, 0)
 elif isinstance(m, BasicBlock):
nn.init.constant_(m.bn2.weight, 0)
 def _make_layer(self, block, planes, blocks, stride=1):
layers = []
layers.append(block(self.inplanes, planes, stride))
self.inplanes = planes * block.expansion
for _ in range(1, blocks):
layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
 def forward(self, x):
conv1 = F.relu(self.bn1(self.conv1(x)) , inplace=True)
 conv1 = F.max_pool2d(conv1, 3, stride=2, padding=1)
 feats4 = self.layer1(conv1)
 feats8 = self.layer2(feats4)
 feats16 = self.layer3(feats8)
 feats32 = self.layer4(feats16)
 return feats8, feats16, feats32
def resnet18(pretrained=False, **kwargs):

 model = ResNetFeatures(BasicBlock, [2, 2, 2, 2], **kwargs)
 if pretrained:
_load_pretrained(model, model_zoo.load_url(model_urls['resnet18']))
return model
def resnext50(pretrained=False, **kwargs):

 model = ResNetFeatures(BasicBlock, [2, 2, 2, 2], **kwargs)
 if pretrained:
_load_pretrained(model, model_zoo.load_url(model_urls['resnext50_32x4d']))
return model
def resnet34(pretrained=False, **kwargs):

 model = ResNetFeatures(BasicBlock, [3, 4, 6, 3], **kwargs)
 if pretrained:
_load_pretrained(model, model_zoo.load_url(model_urls['resnet34']))
return model
def inceptionresnetv2(pretrained=False, **kwargs):

 model = ResNetFeatures(BasicBlock, [3, 4, 6, 3], **kwargs)
 if pretrained:
_load_pretrained(model, model_zoo.load_url(model_urls['inceptionresnetv2']))
return model
def densenet201(pretrained=False, **kwargs):

 model = ResNetFeatures(BasicBlock, [3, 4, 6, 3], **kwargs)
 if pretrained:
_load_pretrained(model, model_zoo.load_url(model_urls['densenet201']))
return model
def _load_pretrained(model, pretrained):
model_dict = model.state_dict()
pretrained = {k : v for k, v in pretrained.items() if k in model_dict}
model_dict.update(pretrained)
 model.load_state_dict(model_dict )
svr = pd.read_csv('/kaggle/input/rapids-svm-on-trends-neuroimaging/submission.csv')
 svr<load_from_csv>
base_model = resnext50(pretrained=False)
 base_model
nn = pd.read_csv('/kaggle/input/trends-augmented-tabular/submission_10fold.csv')
 nn<groupby>
class CentResnet(nn.Module):

 def __init__(self, n_classes):
super(CentResnet, self ).__init__()
self.base_model = base_model
self.lat8 = nn.Conv2d(128, 256, 1)
 self.lat16 = nn.Conv2d(256, 256, 1)
 self.lat32 = nn.Conv2d(512, 256, 1)
 self.bn8 = nn.GroupNorm(16, 256)
 self.bn16 = nn.GroupNorm(16, 256)
 self.bn32 = nn.GroupNorm(16, 256)
 self.conv0 = double_conv(5, 64)
 self.conv1 = double_conv(64, 128)
 self.conv2 = double_conv(128, 512)
 self.conv3 = double_conv(512, 1024)
 self.mp = nn.MaxPool2d(2)
 self.up1 = up(1282 , 512)
 self.up2 = up(512 + 512, 256)
 self.outc = nn.Conv2d(256, n_classes, 1)
 def forward(self, x):
batch_size = x.shape[0]
mesh1 = get_mesh(batch_size, x.shape[2], x.shape[3])
 x0 = torch.cat([x, mesh1], 1)
 x1 = self.mp(self.conv0(x0))
x2 = self.mp(self.conv1(x1))
x3 = self.mp(self.conv2(x2))
x4 = self.mp(self.conv3(x3))
feats8, feats16, feats32 = self.base_model(x)
 lat8 = F.relu(self.bn8(self.lat8(feats8)))
 lat16 = F.relu(self.bn16(self.lat16(feats16)))
 lat32 = F.relu(self.bn32(self.lat32(feats32)))
 mesh2 = get_mesh(batch_size, lat32.shape[2], lat32.shape[3])
 feats = torch.cat([lat32, mesh2], 1)
 x = self.up1(feats, x4)
 x = self.up2(x, x3)
 x = self.outc(x)
 return x
submission = nn.append(svr ).groupby('Id' ).mean().reset_index()
submission<prepare_output>
class RAdam(Optimizer):
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0):
defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay)
 self.buffer = [[None, None, None] for ind in range(10)]
super(RAdam, self ).__init__(params, defaults)
 def __setstate__(self, state):
super(RAdam, self ).__setstate__(state)
 def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
for p in group['params']:
if p.grad is None:
continue
grad = p.grad.data.float()
if grad.is_sparse:
raise RuntimeError('RAdam does not support sparse gradients')
 p_data_fp32 = p.data.float()
state = self.state[p]
if len(state)== 0:
state['step'] = 0
state['exp_avg'] = torch.zeros_like(p_data_fp32)
 state['exp_avg_sq'] = torch.zeros_like(p_data_fp32)
 else:
state['exp_avg'] = state['exp_avg'].type_as(p_data_fp32)
 state['exp_avg_sq'] = state['exp_avg_sq'].type_as(p_data_fp32)
 exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']
beta1, beta2 = group['betas']
exp_avg_sq.mul_(beta2 ).addcmul_(1 - beta2, grad, grad)
 exp_avg.mul_(beta1 ).add_(1 - beta1, grad)
 state['step'] += 1
buffered = self.buffer[int(state['step'] % 10)]
if state['step'] == buffered[0]:
N_sma, step_size = buffered[1], buffered[2]
else:
buffered[0] = state['step']
beta2_t = beta2 ** state['step']
N_sma_max = 2 /(1 - beta2)- 1
N_sma = N_sma_max - 2 * state['step'] * beta2_t /(1 - beta2_t)
 buffered[1] = N_sma
if N_sma >= 5:
step_size = group['lr'] * math.sqrt(( 1 - beta2_t)*(N_sma - 4)/(N_sma_max - 4)*(N_sma - 2)/ N_sma * N_sma_max /(N_sma_max - 2)) /(1 - beta1 ** state['step'])
 else:
step_size = group['lr'] /(1 - beta1 ** state['step'])
 buffered[2] = step_size
if group['weight_decay'] != 0:
p_data_fp32.add_(-group['weight_decay'] * group['lr'], p_data_fp32)
 if N_sma >= 5:
denom = exp_avg_sq.sqrt().add_(group['eps'])
 p_data_fp32.addcdiv_(-step_size, exp_avg, denom)
 else:
p_data_fp32.add_(-step_size, exp_avg)
 p.data.copy_(p_data_fp32)
 return loss
submission = submission.set_index('Id')
 submission<load_from_csv>
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 print(device)
 n_epochs = 2
model = CentResnet(8 ).to(device)
 optimizer = optim.AdamW(model.parameters() , lr=0.001)
 exp_lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=max(n_epochs, 10)* len(train_loader)// 3, gamma=0.1 )
df_1590 = pd.read_csv("/kaggle/input/fork-of-fork-of-kernel19ee18bcfe/submission.csv" ).set_index('Id' )<load_from_csv>
img_batch = torch.randn(( 1,3,700,1600))
df_1587 = pd.read_csv("/kaggle/input/trends-ensemble/submission_svr_nn.csv" ).set_index('Id')
 df_pri_1588 = pd.read_csv(".. /input/trends-priyanshu-meta/submission.csv" ).set_index('Id' )<define_variables>
test = model(img_batch.to(device))
submission =.5*submission +.5*df_1590
submission<define_variables>
def criterion(prediction, mask, regr,weight=0.4, size_average=True):
pred_mask = torch.sigmoid(prediction[:, 0])
 mask_loss = mask * torch.log(pred_mask + 1e-12)+(1 - mask)* torch.log(1 - pred_mask + 1e-12)
 mask_loss = -mask_loss.mean(0 ).sum()
pred_regr = prediction[:, 1:]
regr_loss =(torch.abs(pred_regr - regr ).sum(1)* mask ).sum(1 ).sum(1)/ mask.sum(1 ).sum(1)
 regr_loss = regr_loss.mean(0)
 loss = mask_loss +regr_loss
if not size_average:
loss *= prediction.shape[0]
return loss ,mask_loss , regr_loss
submission =.4*submission +.6*df_1587
submission =.6*submission +.4*df_pri_1588
submission<feature_engineering>
def train(epoch, history=None):
model.train()
t = tqdm(train_loader)
 for batch_idx,(img_batch, mask_batch, regr_batch)in enumerate(t):
img_batch = img_batch.to(device)
 mask_batch = mask_batch.to(device)
 regr_batch = regr_batch.to(device)
 optimizer.zero_grad()
output = model(img_batch)
 if epoch < SWITCH_LOSS_EPOCH :
loss,mask_loss, regr_loss = criterion(output, mask_batch, regr_batch,1)
 else:
loss,mask_loss, regr_loss = criterion(output, mask_batch, regr_batch,0.5)
 t.set_description(f'train_loss(l={loss:.3f} )(m={mask_loss:.2f} )(r={regr_loss:.4f}')
 if history is not None:
history.loc[epoch + batch_idx / len(train_loader), 'train_loss'] = loss.data.cpu().numpy()
loss.backward()
optimizer.step()
exp_lr_scheduler.step()
print('Train Epoch: {} \tLR: {:.6f}\tLoss: {:.6f}\tMaskLoss: {:.6f}\tRegLoss: {:.6f}'.format(
 epoch,
optimizer.state_dict() ['param_groups'][0]['lr'],
loss.data,
mask_loss.data,
regr_loss.data))
def evaluate(epoch, history=None):
model.eval()
loss = 0
valid_loss = 0
valid_mask_loss = 0
valid_regr_loss = 0
with torch.no_grad() :
for img_batch, mask_batch, regr_batch in dev_loader:
img_batch = img_batch.to(device)
 mask_batch = mask_batch.to(device)
 regr_batch = regr_batch.to(device)
 output = model(img_batch)
 if epoch < SWITCH_LOSS_EPOCH :
loss,mask_loss, regr_loss= criterion(output, mask_batch, regr_batch,1, size_average=False)
 valid_loss += loss.data
valid_mask_loss += mask_loss.data
valid_regr_loss += regr_loss.data
else :
loss,mask_loss, regr_loss = criterion(output, mask_batch, regr_batch,0.5, size_average=False)
 valid_loss += loss.data
valid_mask_loss += mask_loss.data
valid_regr_loss += regr_loss.data
valid_loss /= len(dev_loader.dataset)
 valid_mask_loss /= len(dev_loader.dataset)
 valid_regr_loss /= len(dev_loader.dataset)
 if history is not None:
history.loc[epoch, 'dev_loss'] = valid_loss.cpu().numpy()
history.loc[epoch, 'mask_loss'] = valid_mask_loss.cpu().numpy()
history.loc[epoch, 'regr_loss'] = valid_regr_loss.cpu().numpy()
print('Dev loss: {:.4f}'.format(valid_loss))
submission['temp'] = submission.index
age = [ val for val in submission.temp.values if 'age' in val]
counter = 0
for index, row in tqdm(submission.iterrows() , total = submission.shape[0]):
counter +=1
if index in age:
submission.loc[submission.temp == row.temp, 'Predicted'] = row.Predicted * 1.01 
<drop_column>
torch.save(model.state_dict() , './resnext50.pth' )
submission = submission.drop(['temp'], axis=1)
 submission.head()<save_to_csv>
act = torch.nn.Sigmoid()
logtens = torch.from_numpy(logits)
 probs = act(logtens)
 probs = probs[probs>0]
print(probs )
submission.to_csv("submission_svr_nn.csv" )<import_modules>
DISTANCE_THRESH_CLEAR = 2
def convert_3d_to_2d(x, y, z, fx = 2304.5479, fy = 2305.8757, cx = 1686.2379, cy = 1354.9849):
return x * fx / z + cx, y * fy / z + cy
def optimize_xy(r, c, x0, y0, z0):
def distance_fn(xyz):
x, y, z = xyz
x, y = convert_3d_to_2d(x, y, z0)
 y, x = x, y
x =(x - IMG_SHAPE[0] // 2)* IMG_HEIGHT /(IMG_SHAPE[0] // 2)/ MODEL_SCALE
x = np.round(x ).astype('int')
 y =(y + IMG_SHAPE[1] // 4)* IMG_WIDTH /(IMG_SHAPE[1] * 1.5)/ MODEL_SCALE
y = np.round(y ).astype('int')
 return(x-r)**2 +(y-c)**2
res = minimize(distance_fn, [x0, y0, z0], method='Powell')
 x_new, y_new, z_new = res.x
return x_new, y_new, z0
def clear_duplicates(coords):
for c1 in coords:
xyz1 = np.array([c1['x'], c1['y'], c1['z']])
 for c2 in coords:
xyz2 = np.array([c2['x'], c2['y'], c2['z']])
 distance = np.sqrt(((xyz1 - xyz2)**2 ).sum())
 if distance < DISTANCE_THRESH_CLEAR:
if c1['confidence'] < c2['confidence']:
c1['confidence'] = -1
return [c for c in coords if c['confidence'] > 0]
def extract_coords(prediction):
logits = prediction[0]
regr_output = prediction[1:]
points = np.argwhere(logits > 0)
 col_names = sorted(['x', 'y', 'z', 'yaw', 'pitch_sin', 'pitch_cos', 'roll'])
 coords = []
for r, c in points:
regr_dict = dict(zip(col_names, regr_output[:, r, c]))
coords.append(_regr_back(regr_dict))
coords[-1]['confidence'] = 1 /(1 + np.exp(-logits[r, c]))
coords[-1]['x'], coords[-1]['y'], coords[-1]['z'] = optimize_xy(r, c, coords[-1]['x'], coords[-1]['y'], coords[-1]['z'])
 coords = clear_duplicates(coords)
 return coords
def coords2str(coords, names=['yaw', 'pitch', 'roll', 'x', 'y', 'z', 'confidence']):
s = []
for c in coords:
for n in names:
s.append(str(c.get(n, 0)))
 return ' '.join(s )
import numpy as np
import pandas as pd
from sklearn.svm import SVR
from sklearn.multioutput import MultiOutputRegressor, RegressorChain
from sklearn.linear_model import BayesianRidge
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import KFold<define_variables>
val_preds = []
dev_loader = DataLoader(dataset=dev_dataset, batch_size=4, shuffle=False, num_workers=4)
 model.eval()
for img, _, _ in tqdm(dev_loader):
with torch.no_grad() :
output = model(img.to(device))
output = output.data.cpu().numpy()
for out in output:
coords = extract_coords(out)
 s = coords2str(coords)
 val_preds.append(s )
DATA_PATH = '/kaggle/input/trends-assessment-prediction/'<load_from_csv>
df_dev['PredictionString'] = val_preds
df_dev.head()
df_dev.to_csv('val_predictions.csv', index=False )
loading = pd.read_csv(DATA_PATH + 'loading.csv')
 loading.head()<load_from_csv>
predictions = []
test_loader = DataLoader(dataset=test_dataset, batch_size=2, shuffle=False, num_workers=4)
 model.eval()
for img, _, _ in tqdm(test_loader):
with torch.no_grad() :
output = model(img.to(device))
output = output.data.cpu().numpy()
for out in output:
coords = extract_coords(out)
 s = coords2str(coords)
 predictions.append(s )
fnc = pd.read_csv(DATA_PATH + 'fnc.csv')
 fnc[fnc.columns[1:]] /= 600
fnc.head()<merge>
test = pd.read_csv(PATH + 'sample_submission.csv')
 test['PredictionString'] = predictions
test.to_csv('predictions.csv', index=False)
 test.head()
dataset = loading.merge(fnc, on='Id')
 dataset.head()<load_from_csv>
def expand_df(df, PredictionStringCols):
df = df.dropna().copy()
df['NumCars'] = [int(( x.count(' ')+1)/7)for x in df['PredictionString']]
image_id_expanded = [item for item, count in zip(df['ImageId'], df['NumCars'])for i in range(count)]
prediction_strings_expanded = df['PredictionString'].str.split(' ',expand = True ).values.reshape(-1,7 ).astype(float)
 prediction_strings_expanded = prediction_strings_expanded[~np.isnan(prediction_strings_expanded ).all(axis=1)]
df = pd.DataFrame(
 {
'ImageId': image_id_expanded,
PredictionStringCols[0]:prediction_strings_expanded[:,0],
PredictionStringCols[1]:prediction_strings_expanded[:,1],
PredictionStringCols[2]:prediction_strings_expanded[:,2],
PredictionStringCols[3]:prediction_strings_expanded[:,3],
PredictionStringCols[4]:prediction_strings_expanded[:,4],
PredictionStringCols[5]:prediction_strings_expanded[:,5],
PredictionStringCols[6]:prediction_strings_expanded[:,6]
})
 return df
def str2coords(s, names):
coords = []
for l in np.array(s.split() ).reshape([-1, 7]):
coords.append(dict(zip(names, l.astype('float'))))
return coords
def TranslationDistance(p,g, abs_dist = False):
dx = p['x'] - g['x']
dy = p['y'] - g['y']
dz = p['z'] - g['z']
diff0 =(g['x']**2 + g['y']**2 + g['z']**2)**0.5
diff1 =(dx**2 + dy**2 + dz**2)**0.5
if abs_dist:
diff = diff1
else:
diff = diff1/diff0
return diff
def RotationDistance(p, g):
true=[ g['pitch'] ,g['yaw'] ,g['roll'] ]
pred=[ p['pitch'] ,p['yaw'] ,p['roll'] ]
q1 = R.from_euler('xyz', true)
 q2 = R.from_euler('xyz', pred)
 diff = R.inv(q2)* q1
W = np.clip(diff.as_quat() [-1], -1., 1.)
W =(acos(W)*360)/pi
if W > 180:
W = 360 - W
return W
y_train = pd.read_csv(DATA_PATH + 'train_scores.csv')
 print('Number of training samples: {}'.format(len(y_train)))
 y_train.head()<categorify>
thres_tr_list = [0.1, 0.09, 0.08, 0.07, 0.06, 0.05, 0.04, 0.03, 0.02, 0.01]
thres_ro_list = [50, 45, 40, 35, 30, 25, 20, 15, 10, 5]
def check_match(idx):
keep_gt=False
thre_tr_dist = thres_tr_list[idx]
thre_ro_dist = thres_ro_list[idx]
train_dict = {imgID:str2coords(s, names=['carid_or_score', 'pitch', 'yaw', 'roll', 'x', 'y', 'z'])for imgID,s in zip(train_df['ImageId'],train_df['PredictionString'])}
valid_dict = {imgID:str2coords(s, names=['pitch', 'yaw', 'roll', 'x', 'y', 'z', 'carid_or_score'])for imgID,s in zip(valid_df['ImageId'],valid_df['PredictionString'])}
result_flg = []
scores = []
MAX_VAL = 10**10
for img_id in valid_dict:
for pcar in sorted(valid_dict[img_id], key=lambda x: -x['carid_or_score']):
min_tr_dist = MAX_VAL
min_idx = -1
for idx, gcar in enumerate(train_dict[img_id]):
tr_dist = TranslationDistance(pcar,gcar)
 if tr_dist < min_tr_dist:
min_tr_dist = tr_dist
min_ro_dist = RotationDistance(pcar,gcar)
 min_idx = idx
if min_tr_dist < thre_tr_dist and min_ro_dist < thre_ro_dist:
if not keep_gt:
train_dict[img_id].pop(min_idx)
 result_flg.append(1)
 else:
result_flg.append(0)
 scores.append(pcar['carid_or_score'])
 return result_flg, scores
<filter><EOS> 
valid_df = pd.read_csv('val_predictions.csv')
 expanded_valid_df = expand_df(valid_df, ['pitch','yaw','roll','x','y','z','Score'])
 valid_df = valid_df.fillna('')
 train_df = pd.read_csv('.. /input/pku-autonomous-driving/train.csv')
 train_df = train_df[train_df.ImageId.isin(valid_df.ImageId.unique())]
expanded_train_df = expand_df(train_df, ['model_type','pitch','yaw','roll','x','y','z'])
 max_workers = 10
n_gt = len(expanded_train_df)
 ap_list = []
p = Pool(processes=max_workers)
 for result_flg, scores in p.imap(check_match, range(10)) :
if np.sum(result_flg)> 0:
n_tp = np.sum(result_flg)
 recall = n_tp/n_gt
ap = average_precision_score(result_flg, scores)*recall
else:
ap = 0
ap_list.append(ap)
 map = np.mean(ap_list)
 print('map:', map )