Kaggle competition: iMet Collection 2019 - FGVC6
<SOS> metric: MeanFScoreBeta Kaggle data source: imet-2019-fgvc6<feature_engineering>
fastai.__version__
BATCH = 72
SIZE = 320
path = Path('.. /input/imet-2019-fgvc6/')
 Path('models' ).mkdir(exist_ok=True)
 !cp '.. /input/resnet50/resnet50.pth' 'models/'
def load_url(*args, **kwargs):
model_dir = Path('models')
 filename = 'resnet50.pth'
if not(model_dir/filename ).is_file() : raise FileNotFoundError
return torch.load(model_dir/filename)
 model_zoo.load_url = load_url
train_df = pd.read_csv(path/'train.csv')
 train_df.head()
labels_df = pd.read_csv(path/'labels.csv')
 labels_df.head()
test_df = pd.read_csv(path/'sample_submission.csv')
 test_df.head()
tfms = get_transforms(do_flip=True, flip_vert=False, max_rotate=0.10, max_zoom=1.5, max_warp=0.2, max_lighting=0.2,
xtra_tfms=[(symmetric_warp(magnitude=(-0,0), p=0)) ,])
 train, test = [ImageList.from_df(df, path=path, cols='id', folder=folder, suffix='.png')
 for df, folder in zip([train_df, test_df], ['train', 'test'])]
class FocalLoss(nn.Module):
def __init__(self, gamma=2):
super().__init__()
self.gamma = gamma
def forward(self, logit, target):
target = target.float()
max_val =(-logit ).clamp(min=0)
 loss = logit - logit * target + max_val + \ 
(( -max_val ).exp() +(-logit - max_val ).exp() ).log()
invprobs = F.logsigmoid(-logit *(target * 2.0 - 1.0))
loss =(invprobs * self.gamma ).exp() * loss
if len(loss.size())==2:
loss = loss.sum(dim=1)
 return loss.mean()
def add_date_features(df):
df["transaction_year"] = df["transactiondate"].dt.year
df["transaction_month"] = df["transactiondate"].dt.month
df["transaction_day"] = df["transactiondate"].dt.day
df["transaction_quarter"] = df["transactiondate"].dt.quarter
df.drop(["transactiondate"], inplace=True, axis=1)
 return df<merge>
kf = KFold(n_splits=15, random_state=43, shuffle=True)
 kf
n = 0
for train_index, test_index in kf.split(train):
print("TRAIN:", train_index, "TEST:", test_index)
 if n == 0:
break
n+=1
X_train, X_test = train[train_index], train[test_index]
train2016 = add_date_features(train2016)
 train2017 = add_date_features(train2017)
 sample_submission['parcelid'] = sample_submission['ParcelId']
print('Merge Train & Test with Properties...')
 train2016 = pd.merge(train2016, properties2016, how='left', on='parcelid')
 train2017 = pd.merge(train2017, properties2017, how='left', on='parcelid')
 test_df = pd.merge(sample_submission, properties2016, how='left', on='parcelid')
 print('Concat Train 2016 & 2017...')
 train_df = pd.concat([train2016, train2017], axis=0)
 del properties2016, properties2017, train2016, train2017
gc.collect() ;
print("Train: ", train_df.shape)
 print("Test: ", test_df.shape )<count_missing_values>
data =(train.split_by_list(X_train,X_test)
.label_from_df(cols='attribute_ids', label_delim=' ')
.add_test(test)
.transform(tfms, size=SIZE, resize_method=ResizeMethod.PAD, padding_mode='border',)
.databunch(path=Path('.'), bs=BATCH ).normalize(imagenet_stats)
)
 print('Data loaded')
 learn = cnn_learner(data, base_arch=models.resnet50, loss_func=FocalLoss() , metrics=fbeta,pretrained=True)
 learn.unfreeze()
learn.fit_one_cycle(1, slice(1e-5,1e-2))
learn.freeze()
learn.save('resnet50-0-v4-1', return_path=True)
missing_perc_thresh = 0.98
exclude_missing = []
num_rows = train_df.shape[0]
for c in train_df.columns:
num_missing = train_df[c].isnull().sum()
if num_missing == 0:
continue
missing_frac = num_missing / float(num_rows)
 if missing_frac > missing_perc_thresh:
exclude_missing.append(c)
 print("We exclude: %s" % exclude_missing)
 print(len(exclude_missing))<count_unique_values>
Incepres_BATCH = 36
Incepres_SIZE = 320
path = Path('.. /input/imet-2019-fgvc6/' )
exclude_unique = []
for c in train_df.columns:
num_uniques = len(train_df[c].unique())
 if train_df[c].isnull().sum() != 0:
num_uniques -= 1
if num_uniques == 1:
exclude_unique.append(c)
 print("We exclude: %s" % exclude_unique)
 print(len(exclude_unique))<define_variables>
Res_BATCH = 36
Res_SIZE = 320
exclude_other = ['parcelid', 'logerror','propertyzoningdesc']
train_features = []
for c in train_df.columns:
if c not in exclude_missing \
and c not in exclude_other and c not in exclude_unique:
train_features.append(c)
 print("We use these for training: %s" % train_features)
 print(len(train_features))<count_unique_values>
from fastai.vision import learner
cat_feature_inds = []
cat_unique_thresh = 1000
for i, c in enumerate(train_features):
num_uniques = len(train_df[c].unique())
 if num_uniques < cat_unique_thresh \
and not 'sqft' in c \
and not 'cnt' in c \
and not 'nbr' in c \
and not 'number' in c:
cat_feature_inds.append(i)
 print("Cat features are: %s" % [train_features[ind] for ind in cat_feature_inds] )<train_model>
__all__ = ['InceptionResNetV2', 'inceptionresnetv2']
pretrained_settings = {
'inceptionresnetv2': {
'imagenet': {
'url': 'http://data.lip6.fr/cadene/pretrainedmodels/inceptionresnetv2-520b38e4.pth',
'input_space': 'RGB',
'input_size': [3, 299, 299],
'input_range': [0, 1],
'mean': [0.5, 0.5, 0.5],
'std': [0.5, 0.5, 0.5],
'num_classes': 1000
},
'imagenet+background': {
'url': 'http://data.lip6.fr/cadene/pretrainedmodels/inceptionresnetv2-520b38e4.pth',
'input_space': 'RGB',
'input_size': [3, 299, 299],
'input_range': [0, 1],
'mean': [0.5, 0.5, 0.5],
'std': [0.5, 0.5, 0.5],
'num_classes': 1001
}
}
}
class BasicConv2d(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride, padding=0):
super(BasicConv2d, self ).__init__()
self.conv = nn.Conv2d(in_planes, out_planes,
kernel_size=kernel_size, stride=stride,
padding=padding, bias=False)
 self.bn = nn.BatchNorm2d(out_planes,
eps=0.001,
momentum=0.1,
affine=True)
 self.relu = nn.ReLU(inplace=False)
 def forward(self, x):
x = self.conv(x)
 x = self.bn(x)
 x = self.relu(x)
 return x
class Mixed_5b(nn.Module):
def __init__(self):
super(Mixed_5b, self ).__init__()
self.branch0 = BasicConv2d(192, 96, kernel_size=1, stride=1)
 self.branch1 = nn.Sequential(
 BasicConv2d(192, 48, kernel_size=1, stride=1),
BasicConv2d(48, 64, kernel_size=5, stride=1, padding=2)
)
 self.branch2 = nn.Sequential(
 BasicConv2d(192, 64, kernel_size=1, stride=1),
BasicConv2d(64, 96, kernel_size=3, stride=1, padding=1),
BasicConv2d(96, 96, kernel_size=3, stride=1, padding=1)
)
 self.branch3 = nn.Sequential(
 nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False),
BasicConv2d(192, 64, kernel_size=1, stride=1)
)
 def forward(self, x):
x0 = self.branch0(x)
 x1 = self.branch1(x)
 x2 = self.branch2(x)
 x3 = self.branch3(x)
 out = torch.cat(( x0, x1, x2, x3), 1)
 return out
class Block35(nn.Module):
def __init__(self, scale=1.0):
super(Block35, self ).__init__()
self.scale = scale
self.branch0 = BasicConv2d(320, 32, kernel_size=1, stride=1)
 self.branch1 = nn.Sequential(
 BasicConv2d(320, 32, kernel_size=1, stride=1),
BasicConv2d(32, 32, kernel_size=3, stride=1, padding=1)
)
 self.branch2 = nn.Sequential(
 BasicConv2d(320, 32, kernel_size=1, stride=1),
BasicConv2d(32, 48, kernel_size=3, stride=1, padding=1),
BasicConv2d(48, 64, kernel_size=3, stride=1, padding=1)
)
 self.conv2d = nn.Conv2d(128, 320, kernel_size=1, stride=1)
 self.relu = nn.ReLU(inplace=False)
 def forward(self, x):
x0 = self.branch0(x)
 x1 = self.branch1(x)
 x2 = self.branch2(x)
 out = torch.cat(( x0, x1, x2), 1)
 out = self.conv2d(out)
 out = out * self.scale + x
out = self.relu(out)
 return out
class Mixed_6a(nn.Module):
def __init__(self):
super(Mixed_6a, self ).__init__()
self.branch0 = BasicConv2d(320, 384, kernel_size=3, stride=2)
 self.branch1 = nn.Sequential(
 BasicConv2d(320, 256, kernel_size=1, stride=1),
BasicConv2d(256, 256, kernel_size=3, stride=1, padding=1),
BasicConv2d(256, 384, kernel_size=3, stride=2)
)
 self.branch2 = nn.MaxPool2d(3, stride=2)
 def forward(self, x):
x0 = self.branch0(x)
 x1 = self.branch1(x)
 x2 = self.branch2(x)
 out = torch.cat(( x0, x1, x2), 1)
 return out
class Block17(nn.Module):
def __init__(self, scale=1.0):
super(Block17, self ).__init__()
self.scale = scale
self.branch0 = BasicConv2d(1088, 192, kernel_size=1, stride=1)
 self.branch1 = nn.Sequential(
 BasicConv2d(1088, 128, kernel_size=1, stride=1),
BasicConv2d(128, 160, kernel_size=(1,7), stride=1, padding=(0,3)) ,
BasicConv2d(160, 192, kernel_size=(7,1), stride=1, padding=(3,0)) 
)
 self.conv2d = nn.Conv2d(384, 1088, kernel_size=1, stride=1)
 self.relu = nn.ReLU(inplace=False)
 def forward(self, x):
x0 = self.branch0(x)
 x1 = self.branch1(x)
 out = torch.cat(( x0, x1), 1)
 out = self.conv2d(out)
 out = out * self.scale + x
out = self.relu(out)
 return out
class Mixed_7a(nn.Module):
def __init__(self):
super(Mixed_7a, self ).__init__()
self.branch0 = nn.Sequential(
 BasicConv2d(1088, 256, kernel_size=1, stride=1),
BasicConv2d(256, 384, kernel_size=3, stride=2)
)
 self.branch1 = nn.Sequential(
 BasicConv2d(1088, 256, kernel_size=1, stride=1),
BasicConv2d(256, 288, kernel_size=3, stride=2)
)
 self.branch2 = nn.Sequential(
 BasicConv2d(1088, 256, kernel_size=1, stride=1),
BasicConv2d(256, 288, kernel_size=3, stride=1, padding=1),
BasicConv2d(288, 320, kernel_size=3, stride=2)
)
 self.branch3 = nn.MaxPool2d(3, stride=2)
 def forward(self, x):
x0 = self.branch0(x)
 x1 = self.branch1(x)
 x2 = self.branch2(x)
 x3 = self.branch3(x)
 out = torch.cat(( x0, x1, x2, x3), 1)
 return out
class Block8(nn.Module):
def __init__(self, scale=1.0, noReLU=False):
super(Block8, self ).__init__()
self.scale = scale
self.noReLU = noReLU
self.branch0 = BasicConv2d(2080, 192, kernel_size=1, stride=1)
 self.branch1 = nn.Sequential(
 BasicConv2d(2080, 192, kernel_size=1, stride=1),
BasicConv2d(192, 224, kernel_size=(1,3), stride=1, padding=(0,1)) ,
BasicConv2d(224, 256, kernel_size=(3,1), stride=1, padding=(1,0)) 
)
 self.conv2d = nn.Conv2d(448, 2080, kernel_size=1, stride=1)
 if not self.noReLU:
self.relu = nn.ReLU(inplace=False)
 def forward(self, x):
x0 = self.branch0(x)
 x1 = self.branch1(x)
 out = torch.cat(( x0, x1), 1)
 out = self.conv2d(out)
 out = out * self.scale + x
if not self.noReLU:
out = self.relu(out)
 return out
class InceptionResNetV2(nn.Module):
def __init__(self, num_classes=1001):
super(InceptionResNetV2, self ).__init__()
self.input_space = None
self.input_size =(299, 299, 3)
 self.mean = None
self.std = None
self.conv2d_1a = BasicConv2d(3, 32, kernel_size=3, stride=2)
 self.conv2d_2a = BasicConv2d(32, 32, kernel_size=3, stride=1)
 self.conv2d_2b = BasicConv2d(32, 64, kernel_size=3, stride=1, padding=1)
 self.maxpool_3a = nn.MaxPool2d(3, stride=2)
 self.conv2d_3b = BasicConv2d(64, 80, kernel_size=1, stride=1)
 self.conv2d_4a = BasicConv2d(80, 192, kernel_size=3, stride=1)
 self.maxpool_5a = nn.MaxPool2d(3, stride=2)
 self.mixed_5b = Mixed_5b()
self.repeat = nn.Sequential(
 Block35(scale=0.17),
Block35(scale=0.17),
Block35(scale=0.17),
Block35(scale=0.17),
Block35(scale=0.17),
Block35(scale=0.17),
Block35(scale=0.17),
Block35(scale=0.17),
Block35(scale=0.17),
Block35(scale=0.17)
)
 self.mixed_6a = Mixed_6a()
self.repeat_1 = nn.Sequential(
 Block17(scale=0.10),
Block17(scale=0.10),
Block17(scale=0.10),
Block17(scale=0.10),
Block17(scale=0.10),
Block17(scale=0.10),
Block17(scale=0.10),
Block17(scale=0.10),
Block17(scale=0.10),
Block17(scale=0.10),
Block17(scale=0.10),
Block17(scale=0.10),
Block17(scale=0.10),
Block17(scale=0.10),
Block17(scale=0.10),
Block17(scale=0.10),
Block17(scale=0.10),
Block17(scale=0.10),
Block17(scale=0.10),
Block17(scale=0.10)
)
 self.mixed_7a = Mixed_7a()
self.repeat_2 = nn.Sequential(
 Block8(scale=0.20),
Block8(scale=0.20),
Block8(scale=0.20),
Block8(scale=0.20),
Block8(scale=0.20),
Block8(scale=0.20),
Block8(scale=0.20),
Block8(scale=0.20),
Block8(scale=0.20)
)
 self.block8 = Block8(noReLU=True)
 self.conv2d_7b = BasicConv2d(2080, 1536, kernel_size=1, stride=1)
 self.avgpool_1a = nn.AvgPool2d(8, count_include_pad=False)
 self.last_linear = nn.Linear(1536, num_classes)
 def features(self, input):
x = self.conv2d_1a(input)
 x = self.conv2d_2a(x)
 x = self.conv2d_2b(x)
 x = self.maxpool_3a(x)
 x = self.conv2d_3b(x)
 x = self.conv2d_4a(x)
 x = self.maxpool_5a(x)
 x = self.mixed_5b(x)
 x = self.repeat(x)
 x = self.mixed_6a(x)
 x = self.repeat_1(x)
 x = self.mixed_7a(x)
 x = self.repeat_2(x)
 x = self.block8(x)
 x = self.conv2d_7b(x)
 return x
def logits(self, features):
x = self.avgpool_1a(features)
 x = x.view(x.size(0), -1)
 x = self.last_linear(x)
 return x
def forward(self, input):
x = self.features(input)
 x = self.logits(x)
 return x
def inceptionresnetv2(num_classes=1000, pretrained='imagenet'):
r
if pretrained:
settings = pretrained_settings['inceptionresnetv2'][pretrained]
assert num_classes == settings['num_classes'],"num_classes should be {}, but is {}".format(settings['num_classes'], num_classes)
 model = InceptionResNetV2(num_classes=1001)
 model.load_state_dict(model_zoo.load_url(settings['url']))
if pretrained == 'imagenet':
new_last_linear = nn.Linear(1536, 1000)
 new_last_linear.weight.data = model.last_linear.weight.data[1:]
new_last_linear.bias.data = model.last_linear.bias.data[1:]
model.last_linear = new_last_linear
model.input_space = settings['input_space']
model.input_size = settings['input_size']
model.input_range = settings['input_range']
model.mean = settings['mean']
model.std = settings['std']
else:
model = InceptionResNetV2(num_classes=num_classes)
 return model
print("Replacing NaN values by -999 !!")
 train_df.fillna(-999, inplace=True)
 test_df.fillna(-999, inplace=True )<split>
def get_incepres_model(model_name:str, pretrained:bool, seq:bool=False, pname:str='imagenet', **kwargs):
pretrained = pname if pretrained else None
model = inceptionresnetv2(pretrained=pretrained, **kwargs)
 return nn.Sequential(*model.children())if seq else model
X_train, X_test, y_train, y_test = train_test_split(train_df[train_features], train_df.logerror, test_size=0.2, random_state=99)
 print(X_train.shape, y_train.shape)
 print(X_test.shape, y_test.shape)
 all_pool = Pool(train_df[train_features], train_df.logerror, cat_feature_inds)
 train_pool = Pool(X_train, y_train, cat_feature_inds)
 test_pool = Pool(X_test, y_test, cat_feature_inds )<init_hyperparams>
def myinceptionresnetv2(pretrained:bool=False):
return get_incepres_model('inceptionresnetv2', pretrained, seq=True)
 learner.model_meta[myinceptionresnetv2] = {'cut': -2, 'split': lambda m:(m[0][9], m[1])}
catboost_parameters = {
'iterations': 400,
'learning_rate': 0.035,
'depth': 7,
'verbose': 20,
'task_type': 'GPU',
'loss_function': 'MAE',
'eval_metric': 'MAE',
'random_seed': 0,
}<train_model>
!cp.. /input/incepres15fold320/inceptionres-0-v4-52.pth./models/
Incepres_learn0 = cnn_learner(Incepres_data, base_arch=myinceptionresnetv2, loss_func=FocalLoss() , metrics=fbeta,pretrained=False)
 Incepres_learn0.load('inceptionres-0-v4-52')
 Incepres_test_preds0 = Incepres_learn0.get_preds(ds_type=DatasetType.Test)
 Incepres_test_preds0
model = CatBoostRegressor(**catboost_parameters)
 model.fit(train_pool, eval_set=test_pool )<compute_test_metric>
!cp.. /input/incepres15fold320/inceptionres-1-v4-54.pth./models/
Incepres_learn1 = cnn_learner(Incepres_data, base_arch=myinceptionresnetv2, loss_func=FocalLoss() , metrics=fbeta,pretrained=False)
 Incepres_learn1.load('inceptionres-1-v4-54')
 Incepres_test_preds1 = Incepres_learn1.get_preds(ds_type=DatasetType.Test)
 Incepres_test_preds1
print_feature_importance(model, train_pool, X_train )<feature_engineering>
!cp.. /input/incepres15fold320/inceptionres-2-v4-52.pth./models/
Incepres_learn2 = cnn_learner(Incepres_data, base_arch=myinceptionresnetv2, loss_func=FocalLoss() , metrics=fbeta,pretrained=False)
 Incepres_learn2.load('inceptionres-2-v4-52')
 Incepres_test_preds2 = Incepres_learn2.get_preds(ds_type=DatasetType.Test)
 Incepres_test_preds2
<train_model>
!cp.. /input/incepres15fold320/inceptionres-8-v4-60.pth./models/
Incepres_learn8 = cnn_learner(Incepres_data, base_arch=myinceptionresnetv2, loss_func=FocalLoss() , metrics=fbeta,pretrained=False)
 Incepres_learn8.load('inceptionres-8-v4-60')
 Incepres_test_preds8 = Incepres_learn8.get_preds(ds_type=DatasetType.Test)
 Incepres_test_preds8
num_ensembles = 5
models = [None] * num_ensembles
for i in range(num_ensembles):
print("
Training(ensemble): %d..." %(i))
catboost_parameters['random_seed'] = i
models[i] = CatBoostRegressor(**catboost_parameters)
 models[i].fit(train_pool, eval_set=test_pool)
 print('-- Feature Importance --')
 print_feature_importance(models[i], train_pool, X_train )<feature_engineering>
!cp.. /input/incepres15fold320/inceptionres-3-v4-49-n.pth./models/
Incepres_learn3 = cnn_learner(Incepres_data, base_arch=myinceptionresnetv2, loss_func=FocalLoss() , metrics=fbeta,pretrained=False)
 Incepres_learn3.load('inceptionres-3-v4-49-n')
 Incepres_test_preds3 = Incepres_learn3.get_preds(ds_type=DatasetType.Test)
 Incepres_test_preds3
submission = pd.DataFrame({
'ParcelId': test_df['parcelid'],
})
 test_dates = {
'201610': pd.Timestamp('2016-09-30'),
'201611': pd.Timestamp('2016-10-31'),
'201612': pd.Timestamp('2016-11-30'),
'201710': pd.Timestamp('2017-09-30'),
'201711': pd.Timestamp('2017-10-31'),
'201712': pd.Timestamp('2017-11-30')
 }
for label, test_date in test_dates.items() :
print("Predicting for: %s..." %(label))
test_df['transactiondate'] = test_date
test_df = add_date_features(test_df)
 y_pred = 0.0
for i in range(num_ensembles):
print("Ensemble:", i)
 y_pred += models[i].predict(test_df[train_features])
 y_pred /= num_ensembles
submission[label] = y_pred
submission_major = 2
print("Creating submission: submission_%03d.csv..." %(submission_major))
submission.to_csv(
 'submission_%03d.csv' %(submission_major),
float_format='%.4f',
index=False)
 print("Finished." )<set_options>
!cp.. /input/incepres15fold320/inceptionres-7-v4-60-n.pth./models/
Incepres_learn7 = cnn_learner(Incepres_data, base_arch=myinceptionresnetv2, loss_func=FocalLoss() , metrics=fbeta,pretrained=False)
 Incepres_learn7.load('inceptionres-7-v4-60-n')
 Incepres_test_preds7 = Incepres_learn7.get_preds(ds_type=DatasetType.Test)
 Incepres_test_preds7
sys.path.append('.. /input/pytorch-images-seresnet')
 warnings.filterwarnings('ignore')
 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu' )<define_variables>
!cp.. /input/incepres15fold320/inceptionres-10-v4-48.pth./models/
Incepres_learn10 = cnn_learner(Incepres_data, base_arch=myinceptionresnetv2, loss_func=FocalLoss() , metrics=fbeta,pretrained=False)
 Incepres_learn10.load('inceptionres-10-v4-48')
 Incepres_test_preds10 = Incepres_learn10.get_preds(ds_type=DatasetType.Test)
 Incepres_test_preds10
IMAGE_SIZE = 640
BATCH_SIZE = 128
TEST_PATH = '.. /input/ranzcr-clip-catheter-line-classification/test'
MODEL_PATH = '.. /input/resnet200d-public/resnet200d_320_CV9632.pth'<load_from_csv>
!cp.. /input/resnet50imet15fold320/resnet50-0-v4-597.pth./models/
Res_learn0 = cnn_learner(Res_data, base_arch=models.resnet50, loss_func=FocalLoss() , metrics=fbeta,pretrained=False)
 Res_learn0.load('resnet50-0-v4-597')
 Res_test_preds0 = Res_learn0.get_preds(ds_type=DatasetType.Test)
 Res_test_preds0
test = pd.read_csv('.. /input/ranzcr-clip-catheter-line-classification/sample_submission.csv' )<categorify>
!cp.. /input/resnet50imet15fold320/resnet50-1-v4-603.pth./models/
Res_learn1 = cnn_learner(Res_data, base_arch=models.resnet50, loss_func=FocalLoss() , metrics=fbeta,pretrained=False)
 Res_learn1.load('resnet50-1-v4-603')
 Res_test_preds1 = Res_learn1.get_preds(ds_type=DatasetType.Test)
 Res_test_preds1
def get_transforms() :
return Compose([
Resize(IMAGE_SIZE, IMAGE_SIZE),
Normalize(
),
ToTensorV2() ,
] )<choose_model_class>
!cp.. /input/resnet50imet15fold320/resnet50-2-v4-597.pth./models/
Res_learn2 = cnn_learner(Res_data, base_arch=models.resnet50, loss_func=FocalLoss() , metrics=fbeta,pretrained=False)
 Res_learn2.load('resnet50-2-v4-597')
 Res_test_preds2 = Res_learn2.get_preds(ds_type=DatasetType.Test)
 Res_test_preds2
class ResNet200D(nn.Module):
def __init__(self, model_name='resnet200d_320'):
super().__init__()
self.model = timm.create_model(model_name, pretrained=False)
 n_features = self.model.fc.in_features
self.model.global_pool = nn.Identity()
self.model.fc = nn.Identity()
self.pooling = nn.AdaptiveAvgPool2d(1)
 self.fc = nn.Linear(n_features, 11)
 def forward(self, x):
bs = x.size(0)
 features = self.model(x)
 pooled_features = self.pooling(features ).view(bs, -1)
 output = self.fc(pooled_features)
 return output<categorify>
!cp.. /input/resnet50imet15fold320/resnet50-3-v4-597.pth./models/
Res_learn3 = cnn_learner(Res_data, base_arch=models.resnet50, loss_func=FocalLoss() , metrics=fbeta,pretrained=False)
 Res_learn3.load('resnet50-3-v4-597')
 Res_test_preds3 = Res_learn3.get_preds(ds_type=DatasetType.Test)
 Res_test_preds3
def inference(models, test_loader, device):
tk0 = tqdm(enumerate(test_loader), total=len(test_loader))
probs = []
for i,(images)in tk0:
images = images.to(device)
 avg_preds = []
for model in models:
with torch.no_grad() :
y_preds1 = model(images)
 y_preds2 = model(images.flip(-1))
y_preds =(y_preds1.sigmoid().to('cpu' ).numpy() + y_preds2.sigmoid().to('cpu' ).numpy())/ 2
avg_preds.append(y_preds)
 avg_preds = np.mean(avg_preds, axis=0)
 probs.append(avg_preds)
 probs = np.concatenate(probs)
 return probs<choose_model_class>
!cp.. /input/resnet50imet15fold320/resnet50-7-v4-597.pth./models/
Res_learn7 = cnn_learner(Res_data, base_arch=models.resnet50, loss_func=FocalLoss() , metrics=fbeta,pretrained=False)
 Res_learn7.load('resnet50-7-v4-597')
 Res_test_preds7 = Res_learn7.get_preds(ds_type=DatasetType.Test)
 Res_test_preds7
model = ResNet200D()
model.load_state_dict(torch.load(MODEL_PATH)['model'])
 model.eval()
models = [model.to(device)]<load_pretrained>
!cp.. /input/resnet50imet15fold320/resnet50-8-v4-603.pth./models/
Res_learn8 = cnn_learner(Res_data, base_arch=models.resnet50, loss_func=FocalLoss() , metrics=fbeta,pretrained=False)
 Res_learn8.load('resnet50-8-v4-603')
 Res_test_preds8 = Res_learn8.get_preds(ds_type=DatasetType.Test)
 Res_test_preds8
test_dataset = TestDataset(test, transform=get_transforms())
 test_loader = DataLoader(test_dataset, batch_size=BATCH_SIZE, shuffle=False,
num_workers=4 , pin_memory=True)
 predictions = inference(models, test_loader, device )<save_to_csv>
!cp.. /input/resnet50imet15fold320/resnet50-10-v4-599.pth./models/
Res_learn10 = cnn_learner(Res_data, base_arch=models.resnet50, loss_func=FocalLoss() , metrics=fbeta,pretrained=False)
 Res_learn10.load('resnet50-10-v4-599')
 Res_test_preds10 = Res_learn10.get_preds(ds_type=DatasetType.Test)
 Res_test_preds10
target_cols = test.iloc[:, 1:12].columns.tolist()
test[target_cols] = predictions
test[['StudyInstanceUID'] + target_cols].to_csv('submission.csv', index=False)
 test.head()<define_variables>
test_preds =(( Incepres_test_preds0[0]*1+Incepres_test_preds1[0]*1.1
+Incepres_test_preds2[0]*0.9+Incepres_test_preds3[0]*0.9
+Incepres_test_preds7[0]*0.9+Incepres_test_preds8[0]*1.1
+Incepres_test_preds10[0]*1.1)/14+(Res_test_preds0[0]*1+Res_test_preds1[0]*1
+Res_test_preds2[0]*1+Res_test_preds3[0]*1
+Res_test_preds7[0]*1+Res_test_preds8[0]*1
+Res_test_preds10[0]*1)/14,Incepres_test_preds1[1])
batch_size = 1
image_size = 512
tta = True
submit = True
enet_type = ['resnet200d'] * 5
model_path = ['.. /input/resnet200d-baseline-benchmark-public/resnet200d_fold0_cv953.pth',
'.. /input/resnet200d-baseline-benchmark-public/resnet200d_fold1_cv955.pth',
'.. /input/resnet200d-baseline-benchmark-public/resnet200d_fold2_cv955.pth',
'.. /input/resnet200d-baseline-benchmark-public/resnet200d_fold3_cv957.pth',
'.. /input/resnet200d-baseline-benchmark-public/resnet200d_fold4_cv954.pth']
fast_sub = False
fast_sub_path = '.. /input/xxxxxx/your_submission.csv'<set_options>
i2c = np.array([[i, c] for c, i in Incepres_learn0.data.train_ds.y.c2i.items() ] ).astype(int)
 def join_preds(preds, thr):
return [' '.join(i2c[np.where(t==1)[0],1].astype(str)) for t in(preds[0].sigmoid() >thr ).long() ]
sys.path.append('.. /input/pytorch-image-models/pytorch-image-models-master')
 sys.path.append('.. /input/timm-pytorch-image-models/pytorch-image-models-master')
 DEBUG = False
%matplotlib inline
device = torch.device('cuda')if not DEBUG else torch.device('cpu' )<choose_model_class>
test_df.attribute_ids = join_preds(test_preds, 0.260)
 test_df.head()
class RANZCRResNet200D(nn.Module):
def __init__(self, model_name='resnet200d', out_dim=11, pretrained=False):
super().__init__()
self.model = timm.create_model(model_name, pretrained=False)
 n_features = self.model.fc.in_features
self.model.global_pool = nn.Identity()
self.model.fc = nn.Identity()
self.pooling = nn.AdaptiveAvgPool2d(1)
 self.fc = nn.Linear(n_features, out_dim)
 def forward(self, x):
bs = x.size(0)
 features = self.model(x)
 pooled_features = self.pooling(features ).view(bs, -1)
 output = self.fc(pooled_features)
 return output<concatenate>
test_df.to_csv('submission.csv', index=False )