Kaggle competition: Costa Rican Household Poverty Level Prediction
labels_df = pd.read_csv(path/'labels.csv')
 labels_df.head()<load_from_csv>
df = pd.read_csv('/kaggle/input/costa-rican-household-poverty-prediction/train.csv')
 test = pd.read_csv('/kaggle/input/costa-rican-household-poverty-prediction/test.csv')
 df.shape, test.shape
test_df = pd.read_csv(path/'sample_submission.csv')
 test_df.head()<normalization>
df_all = df.append(test)
 df_all.shape
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)) ,] )<compute_test_metric>
df.Target.value_counts() /100
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()<choose_model_class>
df_all['edjefa'].value_counts()
learn = cnn_learner(data, base_arch=models.resnet50, loss_func=FocalLoss() , metrics=fbeta )<load_pretrained>
mapeamento = {'yes': 1, 'no': 0}
df_all['edjefa'] = df_all['edjefa'].replace(mapeamento ).astype(int)
 df_all['edjefe'] = df_all['edjefe'].replace(mapeamento ).astype(int )
learn.load('stage-1' )<predict_on_test>
df_all['dependency'].value_counts()
valid_preds = learn.get_preds(DatasetType.Valid)
 best_thr = find_best_fixed_threshold(*valid_preds )<find_best_params>
df_all['dependency'] = df_all['dependency'].replace(mapeamento ).astype(float )
learn.lr_find()
learn.recorder.plot()<train_model>
df_all.isnull().sum().sort_values()
learn.unfreeze()
learn.fit_one_cycle(16, slice(1e-4,1e-3))
learn.freeze()
learn.save('stage-2', return_path=True )<predict_on_test>
data_na = df_all.isnull().sum().values / df_all.shape[0] *100
df_na = pd.DataFrame(data_na, index=df_all.columns, columns=['Count'])
 df_na = df_na.sort_values(by=['Count'], ascending=False)
 missing_value_count = df_na[df_na['Count']>0].shape[0]
print(f'We got {missing_value_count} rows which have missing value in train set ')
 df_na.head(6)
valid_preds = learn.get_preds(DatasetType.Valid)
 best_thr = find_best_fixed_threshold(*valid_preds )<categorify>
df_all[df_all['parentesco1'] == 1]['v2a1'].isnull().sum()
test_preds = learn.TTA(ds_type=DatasetType.Test)
 test_df.attribute_ids = join_preds(test_preds, best_thr)
 test_df.head()<save_to_csv>
df_all['v18q'].value_counts()
test_df.to_csv('submission.csv', index=False )<find_best_params>
df_all['v2a1'].fillna(0, inplace=True)
 df_all['v18q1'].fillna(0, inplace=True)
 df_all['rez_esc'].fillna(0, inplace=True)
learn.lr_find()
learn.recorder.plot()<load_pretrained>
df_all['meaneduc'].fillna(df_all['meaneduc'].median() , inplace=True)
 df_all['SQBmeaned'].fillna(df_all['SQBmeaned'].median() , inplace=True)
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()<split>
df_all.isnull().sum().sort_values()
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]<train_model>
df_all.fillna(-1, inplace=True)
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)
<define_variables>
df_all['hsize-pc'] = df_all['hhsize'] / df_all['tamviv']
df_all['phone-pc'] = df_all['qmobilephone'] / df_all['tamviv']
df_all['tablets-pc'] = df_all['v18q1'] / df_all['tamviv']
df_all['rooms-pc'] = df_all['rooms'] / df_all['tamviv']
df_all['rent-pc'] = df_all['v2a1'] / df_all['tamviv']
Incepres_BATCH = 36
Incepres_SIZE = 320
path = Path('.. /input/imet-2019-fgvc6/' )<define_variables>
feats = [c for c in df_all.columns if c not in ['Id', 'idhogar', 'Target']]
Res_BATCH = 36
Res_SIZE = 320<import_modules>
train, test = df_all[df_all['Target'] != -1], df_all[df_all['Target'] == -1]
from fastai.vision import learner 
<define_variables>
heads = train[train['parentesco1'] == 1]
__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

<choose_model_class>
clf = lgb.LGBMClassifier(max_depth=-1, learning_rate=0.1, objective='multiclass',
random_state=None, silent=True, metric='None',
n_jobs=4, n_estimators=700, class_weight='balanced',
colsample_bytree = 0.93, min_child_samples = 95, num_leaves = 14, subsample = 0.96)
 clf.fit(heads[feats], heads['Target'])
 accuracy_score(heads['Target'], clf.predict(heads[feats]))
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<normalization>
test['Target'] = clf.predict(test[feats] ).astype(int)
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])}<choose_model_class>
test['Target'].value_counts(normalize=True )
!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<choose_model_class>
cbc = CatBoostClassifier(random_state=42)
 cbc.fit(heads[feats], heads['Target'])
 accuracy_score(test['Target'], cbc.predict(test[feats]))
!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<choose_model_class>
test['Target'] = cbc.predict(test[feats] ).astype(int)
 test['Target'].value_counts(normalize=True)
!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<choose_model_class>
rf = RandomForestClassifier(max_depth=None, random_state=42, n_jobs=4, n_estimators=700,
min_impurity_decrease=1e-3, min_samples_leaf=2,
verbose=0, class_weight='balanced')
!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<choose_model_class>
rf.fit(heads[feats], heads['Target'] )
!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<choose_model_class>
test['Target'] = rf.predict(test[feats] ).astype(int )
!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<choose_model_class>
test['Target'].value_counts(normalize=True)
!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<choose_model_class>
accuracy_score(heads['Target'], rf.predict(heads[feats]))
!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<choose_model_class>
test[['Id', 'Target']].to_csv('submission.csv', index=False)