Kaggle competition: Cornell Birdcall Identification
<SOS> metric: MeanFScoreBeta Kaggle data source: cornell-birdcall-identification<import_modules>
sys.path = [
'.. /input/efficientnet-pytorch/EfficientNet-PyTorch/EfficientNet-PyTorch-master',
] + sys.path
pd.options.display.max_rows = 500
pd.options.display.max_columns = 500
ModelCheckpoint, EarlyStopping, LearningRateScheduler, ReduceLROnPlateau)
 %matplotlib inline
%config InlineBackend.figure_format = 'svg'<define_variables>
def set_seed(seed: int = 42):
random.seed(seed)
 np.random.seed(seed)
 os.environ["PYTHONHASHSEED"] = str(seed)
 torch.manual_seed(seed)
 torch.cuda.manual_seed(seed)
 @contextmanager
def timer(name: str)-> None:

 t0 = time.time()
print("[{}] start".format(name))
yield
print("[{}] done in {:.0f} s".format(name, time.time() - t0))
def seed_everything(seed):
random.seed(seed)
 os.environ['PYTHONHASHSEED'] = str(seed)
 np.random.seed(seed)
 tf.random.set_seed(seed)
 SEED = 1984
seed_everything(SEED )<load_from_csv>
set_seed(1213 )
x_develop = pd.read_csv('.. /input/lish-moa/train_features.csv')
 y_develop = pd.read_csv('.. /input/lish-moa/train_targets_scored.csv')
 x_test= pd.read_csv('.. /input/lish-moa/test_features.csv')
 sub = pd.read_csv('.. /input/lish-moa/sample_submission.csv')
 c_cols = x_develop.columns[x_develop.columns.str.startswith('c-')]
g_cols = x_develop.columns[x_develop.columns.str.startswith('g-')]
target_cols = y_develop.columns[1:]
N_TARGETS = len(target_cols)
 N_TARGETS<categorify>
ROOT = Path.cwd().parent
INPUT_ROOT = ROOT / "input"
RAW_DATA = INPUT_ROOT / "birdsong-recognition"
TRAIN_AUDIO_DIR = RAW_DATA / "train_audio"
TEST_AUDIO_DIR = RAW_DATA / "test_audio"
def preprocess_df(df):
if 'sig_id' in df.columns:
df.set_index('sig_id', inplace=True)
 df['cp_type'] =(df['cp_type'] == 'trt_cp' ).astype(int)
 df['cp_dose'] =(df['cp_dose'] == 'D2' ).astype(int)
 df = df.join(pd.get_dummies(df['cp_time'], drop_first=False, prefix='cp_time'))
df = df.drop('cp_time', axis=1)
 return df<create_dataframe>
train = pd.read_csv(RAW_DATA / "train.csv" )
x_develop = preprocess_df(x_develop)
 y_develop = y_develop.set_index('sig_id')
 x_test = preprocess_df(x_test )<load_from_csv>
if not TEST_AUDIO_DIR.exists() :
TEST_AUDIO_DIR = INPUT_ROOT / "birdcall-check" / "test_audio"
test = pd.read_csv(INPUT_ROOT / "birdcall-check" / "test.csv")
 else:
test = pd.read_csv(RAW_DATA / "test.csv" )
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
 def load_data(train_path, cols):
if isinstance(train_path, list):
df_base = pd.read_csv(train_path[0])
 for i in range(1, len(train_path)) :
df_base.append(pd.read_csv(train_path[i]))
df_base = df_base[cols]
else:
df = pd.read_csv(train_path)
 df_base = df[cols]
x = df_base.values.reshape(-1, df_base.shape[1] ).astype('float32')
 standardizer = preprocessing.StandardScaler()
x = standardizer.fit_transform(x)
 return x, standardizer
def numpyToTensor(x):
x_train = torch.from_numpy(x ).to(device)
 return x_train
class DataBuilder(Dataset):
def __init__(self, path, cols):
self.x, self.standardizer = load_data(path, cols)
 self.x = numpyToTensor(self.x)
 self.len=self.x.shape[0]
def __getitem__(self,index):
return self.x[index]
def __len__(self):
return self.len<categorify>
sub = pd.read_csv(".. /input/birdsong-recognition/sample_submission.csv")
 sub.to_csv("submission.csv", index=False )
class Autoencoder(nn.Module):
def __init__(self,D_in, H, H2, latent_dim):
super(Autoencoder,self ).__init__()
self.linear1=nn.Linear(D_in,H)
 self.lin_bn1 = nn.BatchNorm1d(num_features=H)
 self.linear2=nn.Linear(H,H2)
 self.lin_bn2 = nn.BatchNorm1d(num_features=H2)
 self.linear3=nn.Linear(H2,H2)
 self.lin_bn3 = nn.BatchNorm1d(num_features=H2)
 self.fc1 = nn.Linear(H2, latent_dim)
 self.bn1 = nn.BatchNorm1d(num_features=latent_dim)
 self.fc21 = nn.Linear(latent_dim, latent_dim)
 self.fc22 = nn.Linear(latent_dim, latent_dim)
 self.fc3 = nn.Linear(latent_dim, latent_dim)
 self.fc_bn3 = nn.BatchNorm1d(latent_dim)
 self.fc4 = nn.Linear(latent_dim, H2)
 self.fc_bn4 = nn.BatchNorm1d(H2)
 self.linear4=nn.Linear(H2,H2)
 self.lin_bn4 = nn.BatchNorm1d(num_features=H2)
 self.linear5=nn.Linear(H2,H)
 self.lin_bn5 = nn.BatchNorm1d(num_features=H)
 self.linear6=nn.Linear(H,D_in)
 self.lin_bn6 = nn.BatchNorm1d(num_features=D_in)
 self.leaky_relu = nn.LeakyReLU()
def encode(self, x):
lin1 = self.leaky_relu(self.lin_bn1(self.linear1(x)))
 lin2 = self.leaky_relu(self.lin_bn2(self.linear2(lin1)))
 lin3 = self.leaky_relu(self.lin_bn3(self.linear3(lin2)))
 fc1 = F.leaky_relu(self.bn1(self.fc1(lin3)))
 r1 = self.fc21(fc1)
 r2 = self.fc22(fc1)
 return r1, r2
def reparameterize(self, mu, logvar):
if self.training:
std = logvar.mul(0.5 ).exp_()
eps = Variable(std.data.new(std.size() ).normal_())
 return eps.mul(std ).add_(mu)
 else:
return mu
def decode(self, z):
fc3 = self.leaky_relu(self.fc_bn3(self.fc3(z)))
 fc4 = self.leaky_relu(self.fc_bn4(self.fc4(fc3)))
 lin4 = self.leaky_relu(self.lin_bn4(self.linear4(fc4)))
 lin5 = self.leaky_relu(self.lin_bn5(self.linear5(lin4)))
 return self.lin_bn6(self.linear6(lin5))
def forward(self, x):
mu, logvar = self.encode(x)
 z = self.reparameterize(mu, logvar)
 return self.decode(z), mu, logvar
class customLoss(nn.Module):
def __init__(self):
super(customLoss, self ).__init__()
self.mse_loss = nn.MSELoss(reduction="sum")
 def forward(self, x_recon, x, mu, logvar):
loss_MSE = self.mse_loss(x_recon, x)
 loss_KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2)- logvar.exp())
 return loss_MSE + loss_KLD
def weights_init_uniform_rule(m):
classname = m.__class__.__name__
if classname.find('Linear')!= -1:
n = m.in_features
y = 1.0/np.sqrt(n)
 m.weight.data.uniform_(-y, y)
 m.bias.data.fill_(0)
 def train(epoch, dataloader, model, optimizer):
loss_mse = customLoss()
model.train()
train_loss = 0
for batch_idx, data in enumerate(dataloader):
data = data.to(device)
 optimizer.zero_grad()
recon_batch, mu, logvar = model(data)
 loss = loss_mse(recon_batch, data, mu, logvar)
 loss.backward()
train_loss += loss.item()
optimizer.step()
if epoch % 100 == 0:
print('====> Epoch: {} Average loss: {:.4f}'.format(epoch, train_loss / len(dataloader.dataset)))
 def encode_features(data_loader, model, optimizer):
mu_output = []
logvar_output = []
with torch.no_grad() :
for i,(data)in enumerate(data_loader):
data = data.to(device)
 optimizer.zero_grad()
recon_batch, mu, logvar = model(data)
 mu_tensor = mu
mu_output.append(mu_tensor)
 mu_result = torch.cat(mu_output, dim=0)
 logvar_tensor = logvar
logvar_output.append(logvar_tensor)
 logvar_result = torch.cat(logvar_output, dim=0)
 return mu_result
def get_encoder_features(TRAIN_DATA_PATH, TEST_DATA_PATH, cols, latent_dim, name, train_flag=True):
print('Reading train data...')
 data_set_train=DataBuilder(TRAIN_DATA_PATH, cols)
 trainloader=DataLoader(dataset=data_set_train,batch_size=512)
 print('Reading test data...')
 data_set_test=DataBuilder(TEST_DATA_PATH, cols)
 testloader=DataLoader(dataset=data_set_test,batch_size=512)
 print('Reading data...')
 data_set = DataBuilder([TRAIN_DATA_PATH, TEST_DATA_PATH], cols)
 loader=DataLoader(dataset=data_set,batch_size=512)
 print('Prepare params...')
 D_in = data_set_train.x.shape[1]
H = D_in -(D_in - latent_dim)// 4
H2 = D_in -(D_in - latent_dim)// 2
model = Autoencoder(D_in, H, H2, latent_dim ).to(device)
 model.apply(weights_init_uniform_rule)
 optimizer = optim.Adam(model.parameters() , lr=1e-3)
 loss_mse = customLoss()
epochs = 1000
log_interval = 50
val_losses = []
train_losses = []
print("train or load model...")
 if train_flag:
print("train model...")
 for epoch in range(1, epochs + 1):
train(epoch, loader, model, optimizer)
 torch.save(model.state_dict() , name)
 else:
print("load model...")
 model.load_state_dict(torch.load(name))
model.eval()
print("extract features...")
 train_encoder = encode_features(trainloader, model, optimizer)
 test_encoder = encode_features(testloader, model, optimizer)
 return train_encoder, test_encoder<categorify>
TARGET_SR = 32000
model_config = {
"base_model_name": "RESNET",
"pretrained": False,
"num_classes": 264,
"trained_weights": ".. /input/training-birdsong-baseline-resnest50-fast/best_model.pth"
}
melspectrogram_parameters = {
"n_mels": 128,
"fmin": 20,
"fmax": 16000
}
TRAIN_DATA_PATH = '.. /input/lish-moa/train_features.csv'
TEST_DATA_PATH = '.. /input/lish-moa/test_features.csv'
gene_encode_dim = 50
cell_encode_dim = 30
GENES = g_cols.to_list()
CELLS = c_cols.to_list()
genes_model_name = f'.. /input/update-mx10-model/autoencode_genes_50_30_default'
cells_model_name = f'.. /input/update-mx10-model/autoencode_cells_50_30_default'
train_gene_encoder, test_gene_encoder = get_encoder_features(TRAIN_DATA_PATH, TEST_DATA_PATH, GENES, gene_encode_dim, genes_model_name,
train_flag=False)
 train_cell_encoder, test_cell_encoder = get_encoder_features(TRAIN_DATA_PATH, TEST_DATA_PATH, CELLS, cell_encode_dim, cells_model_name,
train_flag=False)
 train_gene_encoder_pd = pd.DataFrame(train_gene_encoder.cpu().numpy() , columns=[f'VAE_G_{i}' for i in range(gene_encode_dim)])
 test_gene_encoder_pd = pd.DataFrame(test_gene_encoder.cpu().numpy() , columns=[f'VAE_G_{i}' for i in range(gene_encode_dim)])
 train_cell_encoder_pd = pd.DataFrame(train_cell_encoder.cpu().numpy() , columns=[f'VAE_C_{i}' for i in range(cell_encode_dim)])
 test_cell_encoder_pd = pd.DataFrame(test_cell_encoder.cpu().numpy() , columns=[f'VAE_C_{i}' for i in range(cell_encode_dim)])
<merge>
BIRD_CODE = {
'aldfly': 0, 'ameavo': 1, 'amebit': 2, 'amecro': 3, 'amegfi': 4,
'amekes': 5, 'amepip': 6, 'amered': 7, 'amerob': 8, 'amewig': 9,
'amewoo': 10, 'amtspa': 11, 'annhum': 12, 'astfly': 13, 'baisan': 14,
'baleag': 15, 'balori': 16, 'banswa': 17, 'barswa': 18, 'bawwar': 19,
'belkin1': 20, 'belspa2': 21, 'bewwre': 22, 'bkbcuc': 23, 'bkbmag1': 24,
'bkbwar': 25, 'bkcchi': 26, 'bkchum': 27, 'bkhgro': 28, 'bkpwar': 29,
'bktspa': 30, 'blkpho': 31, 'blugrb1': 32, 'blujay': 33, 'bnhcow': 34,
'boboli': 35, 'bongul': 36, 'brdowl': 37, 'brebla': 38, 'brespa': 39,
'brncre': 40, 'brnthr': 41, 'brthum': 42, 'brwhaw': 43, 'btbwar': 44,
'btnwar': 45, 'btywar': 46, 'buffle': 47, 'buggna': 48, 'buhvir': 49,
'bulori': 50, 'bushti': 51, 'buwtea': 52, 'buwwar': 53, 'cacwre': 54,
'calgul': 55, 'calqua': 56, 'camwar': 57, 'cangoo': 58, 'canwar': 59,
'canwre': 60, 'carwre': 61, 'casfin': 62, 'caster1': 63, 'casvir': 64,
'cedwax': 65, 'chispa': 66, 'chiswi': 67, 'chswar': 68, 'chukar': 69,
'clanut': 70, 'cliswa': 71, 'comgol': 72, 'comgra': 73, 'comloo': 74,
'commer': 75, 'comnig': 76, 'comrav': 77, 'comred': 78, 'comter': 79,
'comyel': 80, 'coohaw': 81, 'coshum': 82, 'cowscj1': 83, 'daejun': 84,
'doccor': 85, 'dowwoo': 86, 'dusfly': 87, 'eargre': 88, 'easblu': 89,
'easkin': 90, 'easmea': 91, 'easpho': 92, 'eastow': 93, 'eawpew': 94,
'eucdov': 95, 'eursta': 96, 'evegro': 97, 'fiespa': 98, 'fiscro': 99,
'foxspa': 100, 'gadwal': 101, 'gcrfin': 102, 'gnttow': 103, 'gnwtea': 104,
'gockin': 105, 'gocspa': 106, 'goleag': 107, 'grbher3': 108, 'grcfly': 109,
'greegr': 110, 'greroa': 111, 'greyel': 112, 'grhowl': 113, 'grnher': 114,
'grtgra': 115, 'grycat': 116, 'gryfly': 117, 'haiwoo': 118, 'hamfly': 119,
'hergul': 120, 'herthr': 121, 'hoomer': 122, 'hoowar': 123, 'horgre': 124,
'horlar': 125, 'houfin': 126, 'houspa': 127, 'houwre': 128, 'indbun': 129,
'juntit1': 130, 'killde': 131, 'labwoo': 132, 'larspa': 133, 'lazbun': 134,
'leabit': 135, 'leafly': 136, 'leasan': 137, 'lecthr': 138, 'lesgol': 139,
'lesnig': 140, 'lesyel': 141, 'lewwoo': 142, 'linspa': 143, 'lobcur': 144,
'lobdow': 145, 'logshr': 146, 'lotduc': 147, 'louwat': 148, 'macwar': 149,
'magwar': 150, 'mallar3': 151, 'marwre': 152, 'merlin': 153, 'moublu': 154,
'mouchi': 155, 'moudov': 156, 'norcar': 157, 'norfli': 158, 'norhar2': 159,
'normoc': 160, 'norpar': 161, 'norpin': 162, 'norsho': 163, 'norwat': 164,
'nrwswa': 165, 'nutwoo': 166, 'olsfly': 167, 'orcwar': 168, 'osprey': 169,
'ovenbi1': 170, 'palwar': 171, 'pasfly': 172, 'pecsan': 173, 'perfal': 174,
'phaino': 175, 'pibgre': 176, 'pilwoo': 177, 'pingro': 178, 'pinjay': 179,
'pinsis': 180, 'pinwar': 181, 'plsvir': 182, 'prawar': 183, 'purfin': 184,
'pygnut': 185, 'rebmer': 186, 'rebnut': 187, 'rebsap': 188, 'rebwoo': 189,
'redcro': 190, 'redhea': 191, 'reevir1': 192, 'renpha': 193, 'reshaw': 194,
'rethaw': 195, 'rewbla': 196, 'ribgul': 197, 'rinduc': 198, 'robgro': 199,
'rocpig': 200, 'rocwre': 201, 'rthhum': 202, 'ruckin': 203, 'rudduc': 204,
'rufgro': 205, 'rufhum': 206, 'rusbla': 207, 'sagspa1': 208, 'sagthr': 209,
'savspa': 210, 'saypho': 211, 'scatan': 212, 'scoori': 213, 'semplo': 214,
'semsan': 215, 'sheowl': 216, 'shshaw': 217, 'snobun': 218, 'snogoo': 219,
'solsan': 220, 'sonspa': 221, 'sora': 222, 'sposan': 223, 'spotow': 224,
'stejay': 225, 'swahaw': 226, 'swaspa': 227, 'swathr': 228, 'treswa': 229,
'truswa': 230, 'tuftit': 231, 'tunswa': 232, 'veery': 233, 'vesspa': 234,
'vigswa': 235, 'warvir': 236, 'wesblu': 237, 'wesgre': 238, 'weskin': 239,
'wesmea': 240, 'wessan': 241, 'westan': 242, 'wewpew': 243, 'whbnut': 244,
'whcspa': 245, 'whfibi': 246, 'whtspa': 247, 'whtswi': 248, 'wilfly': 249,
'wilsni1': 250, 'wiltur': 251, 'winwre3': 252, 'wlswar': 253, 'wooduc': 254,
'wooscj2': 255, 'woothr': 256, 'y00475': 257, 'yebfly': 258, 'yebsap': 259,
'yehbla': 260, 'yelwar': 261, 'yerwar': 262, 'yetvir': 263
}
INV_BIRD_CODE = {v: k for k, v in BIRD_CODE.items() }
train_gene_encoder_pd['sig_id'] = list(x_develop.index)
 train_cell_encoder_pd['sig_id'] = list(x_develop.index)
 test_gene_encoder_pd['sig_id'] = list(x_test.index)
 test_cell_encoder_pd['sig_id'] = list(x_test.index)
 x_develop = x_develop.merge(train_gene_encoder_pd, on='sig_id')
 x_develop = x_develop.merge(train_cell_encoder_pd, on='sig_id')
 x_test = x_test.merge(test_gene_encoder_pd, on='sig_id')
 x_test = x_test.merge(test_cell_encoder_pd, on='sig_id' )<categorify>
class SplAtConv2d(Module):

 def __init__(self, in_channels, channels, kernel_size, stride=(1, 1), padding=(0, 0),
dilation=(1, 1), groups=1, bias=True,
radix=2, reduction_factor=4,
rectify=False, rectify_avg=False, norm_layer=None,
dropblock_prob=0.0, **kwargs):
super(SplAtConv2d, self ).__init__()
padding = _pair(padding)
 self.rectify = rectify and(padding[0] > 0 or padding[1] > 0)
 self.rectify_avg = rectify_avg
inter_channels = max(in_channels*radix//reduction_factor, 32)
 self.radix = radix
self.cardinality = groups
self.channels = channels
self.dropblock_prob = dropblock_prob
if self.rectify:
self.conv = RFConv2d(in_channels, channels*radix, kernel_size, stride, padding, dilation,
groups=groups*radix, bias=bias, average_mode=rectify_avg, **kwargs)
 else:
self.conv = Conv2d(in_channels, channels*radix, kernel_size, stride, padding, dilation,
groups=groups*radix, bias=bias, **kwargs)
 self.use_bn = norm_layer is not None
if self.use_bn:
self.bn0 = norm_layer(channels*radix)
 self.relu = ReLU(inplace=True)
 self.fc1 = Conv2d(channels, inter_channels, 1, groups=self.cardinality)
 if self.use_bn:
self.bn1 = norm_layer(inter_channels)
 self.fc2 = Conv2d(inter_channels, channels*radix, 1, groups=self.cardinality)
 if dropblock_prob > 0.0:
self.dropblock = DropBlock2D(dropblock_prob, 3)
 self.rsoftmax = rSoftMax(radix, groups)
 def forward(self, x):
x = self.conv(x)
 if self.use_bn:
x = self.bn0(x)
 if self.dropblock_prob > 0.0:
x = self.dropblock(x)
 x = self.relu(x)
 batch, rchannel = x.shape[:2]
if self.radix > 1:
if torch.__version__ < '1.5':
splited = torch.split(x, int(rchannel//self.radix), dim=1)
 else:
splited = torch.split(x, rchannel//self.radix, dim=1)
 gap = sum(splited)
 else:
gap = x
gap = F.adaptive_avg_pool2d(gap, 1)
 gap = self.fc1(gap)
 if self.use_bn:
gap = self.bn1(gap)
 gap = self.relu(gap)
 atten = self.fc2(gap)
 atten = self.rsoftmax(atten ).view(batch, -1, 1, 1)
 if self.radix > 1:
if torch.__version__ < '1.5':
attens = torch.split(atten, int(rchannel//self.radix), dim=1)
 else:
attens = torch.split(atten, rchannel//self.radix, dim=1)
 out = sum([att*split for(att, split)in zip(attens, splited)])
 else:
out = atten * x
return out.contiguous()
class rSoftMax(nn.Module):
def __init__(self, radix, cardinality):
super().__init__()
self.radix = radix
self.cardinality = cardinality
def forward(self, x):
batch = x.size(0)
 if self.radix > 1:
x = x.view(batch, self.cardinality, self.radix, -1 ).transpose(1, 2)
 x = F.softmax(x, dim=1)
 x = x.reshape(batch, -1)
 else:
x = torch.sigmoid(x)
 return x
n_comp = 80
transformer = load('.. /input/update-mx10-model/mx10_pca_g.joblib')
 x_develop_pca = transformer.transform(x_develop[g_cols])
 x_develop_pca = pd.DataFrame(x_develop_pca, columns=[f'pca_g-{i}' for i in range(n_comp)], index=x_develop.index)
 x_develop = pd.concat(( x_develop, x_develop_pca), axis=1)
 x_test_pca = transformer.transform(x_test[g_cols])
 x_test_pca = pd.DataFrame(x_test_pca, columns=[f'pca_g-{i}' for i in range(n_comp)], index=x_test.index)
 x_test = pd.concat(( x_test, x_test_pca), axis=1)
 n_comp = 40
transformer = load('.. /input/update-mx10-model/mx10_pca_c.joblib')
 x_develop_pca = transformer.transform(x_develop[c_cols])
 x_develop_pca = pd.DataFrame(x_develop_pca, columns=[f'pca_c-{i}' for i in range(n_comp)], index=x_develop.index)
 x_develop = pd.concat(( x_develop, x_develop_pca), axis=1)
 x_test_pca = transformer.transform(x_test[c_cols])
 x_test_pca = pd.DataFrame(x_test_pca, columns=[f'pca_c-{i}' for i in range(n_comp)], index=x_test.index)
 x_test = pd.concat(( x_test, x_test_pca), axis=1)
 n_comp = 80
transformer = load('.. /input/update-mx10-model/mx10_FastICA_g.joblib')
 x_develop_pca = transformer.transform(x_develop[g_cols])
 x_develop_pca = pd.DataFrame(x_develop_pca, columns=[f'FastICA_g-{i}' for i in range(n_comp)], index=x_develop.index)
 x_develop = pd.concat(( x_develop, x_develop_pca), axis=1)
 x_test_pca = transformer.transform(x_test[g_cols])
 x_test_pca = pd.DataFrame(x_test_pca, columns=[f'FastICA_g-{i}' for i in range(n_comp)], index=x_test.index)
 x_test = pd.concat(( x_test, x_test_pca), axis=1)
 n_comp = 40
transformer = load('.. /input/update-mx10-model/mx10_FastICA_c.joblib')
 x_develop_pca = transformer.transform(x_develop[c_cols])
 x_develop_pca = pd.DataFrame(x_develop_pca, columns=[f'FastICA_c-{i}' for i in range(n_comp)], index=x_develop.index)
 x_develop = pd.concat(( x_develop, x_develop_pca), axis=1)
 x_test_pca = transformer.transform(x_test[c_cols])
 x_test_pca = pd.DataFrame(x_test_pca, columns=[f'FastICA_c-{i}' for i in range(n_comp)], index=x_test.index)
 x_test = pd.concat(( x_test, x_test_pca), axis=1)
 n_comp = 80
transformer = load('.. /input/update-mx10-model/mx10_FactorAnalysis_g.joblib')
 x_develop_pca = transformer.transform(x_develop[g_cols])
 x_develop_pca = pd.DataFrame(x_develop_pca, columns=[f'FactorAnalysis_g-{i}' for i in range(n_comp)], index=x_develop.index)
 x_develop = pd.concat(( x_develop, x_develop_pca), axis=1)
 x_test_pca = transformer.transform(x_test[g_cols])
 x_test_pca = pd.DataFrame(x_test_pca, columns=[f'FactorAnalysis_g-{i}' for i in range(n_comp)], index=x_test.index)
 x_test = pd.concat(( x_test, x_test_pca), axis=1)
 n_comp = 40
transformer = load('.. /input/update-mx10-model/mx10_FactorAnalysis_c.joblib')
 x_develop_pca = transformer.transform(x_develop[c_cols])
 x_develop_pca = pd.DataFrame(x_develop_pca, columns=[f'FactorAnalysis_c-{i}' for i in range(n_comp)], index=x_develop.index)
 x_develop = pd.concat(( x_develop, x_develop_pca), axis=1)
 x_test_pca = transformer.transform(x_test[c_cols])
 x_test_pca = pd.DataFrame(x_test_pca, columns=[f'FactorAnalysis_c-{i}' for i in range(n_comp)], index=x_test.index)
 x_test = pd.concat(( x_test, x_test_pca), axis=1)
 n_comp = 80
transformer = load('.. /input/update-mx10-model/mx10_FeatureAgglomeration_g.joblib')
 x_develop_pca = transformer.transform(x_develop[g_cols])
 x_develop_pca = pd.DataFrame(x_develop_pca, columns=[f'FeatureAgglomeration_g-{i}' for i in range(n_comp)], index=x_develop.index)
 x_develop = pd.concat(( x_develop, x_develop_pca), axis=1)
 x_test_pca = transformer.transform(x_test[g_cols])
 x_test_pca = pd.DataFrame(x_test_pca, columns=[f'FeatureAgglomeration_g-{i}' for i in range(n_comp)], index=x_test.index)
 x_test = pd.concat(( x_test, x_test_pca), axis=1)
 n_comp = 40
transformer = load('.. /input/update-mx10-model/mx10_FeatureAgglomeration_c.joblib')
 x_develop_pca = transformer.transform(x_develop[c_cols])
 x_develop_pca = pd.DataFrame(x_develop_pca, columns=[f'FeatureAgglomeration_c-{i}' for i in range(n_comp)], index=x_develop.index)
 x_develop = pd.concat(( x_develop, x_develop_pca), axis=1)
 x_test_pca = transformer.transform(x_test[c_cols])
 x_test_pca = pd.DataFrame(x_test_pca, columns=[f'FeatureAgglomeration_c-{i}' for i in range(n_comp)], index=x_test.index)
 x_test = pd.concat(( x_test, x_test_pca), axis=1)
<feature_engineering>
class DropBlock2D(object):
def __init__(self, *args, **kwargs):
raise NotImplementedError
class GlobalAvgPool2d(nn.Module):
def __init__(self):

 super(GlobalAvgPool2d, self ).__init__()
def forward(self, inputs):
return nn.functional.adaptive_avg_pool2d(inputs, 1 ).view(inputs.size(0), -1)
 class Bottleneck(nn.Module):

 expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None,
radix=1, cardinality=1, bottleneck_width=64,
avd=False, avd_first=False, dilation=1, is_first=False,
rectified_conv=False, rectify_avg=False,
norm_layer=None, dropblock_prob=0.0, last_gamma=False):
super(Bottleneck, self ).__init__()
group_width = int(planes *(bottleneck_width / 64.))* cardinality
self.conv1 = nn.Conv2d(inplanes, group_width, kernel_size=1, bias=False)
 self.bn1 = norm_layer(group_width)
 self.dropblock_prob = dropblock_prob
self.radix = radix
self.avd = avd and(stride > 1 or is_first)
 self.avd_first = avd_first
if self.avd:
self.avd_layer = nn.AvgPool2d(3, stride, padding=1)
 stride = 1
if dropblock_prob > 0.0:
self.dropblock1 = DropBlock2D(dropblock_prob, 3)
 if radix == 1:
self.dropblock2 = DropBlock2D(dropblock_prob, 3)
 self.dropblock3 = DropBlock2D(dropblock_prob, 3)
 if radix >= 1:
self.conv2 = SplAtConv2d(
 group_width, group_width, kernel_size=3,
stride=stride, padding=dilation,
dilation=dilation, groups=cardinality, bias=False,
radix=radix, rectify=rectified_conv,
rectify_avg=rectify_avg,
norm_layer=norm_layer,
dropblock_prob=dropblock_prob)
 elif rectified_conv:
self.conv2 = RFConv2d(
 group_width, group_width, kernel_size=3, stride=stride,
padding=dilation, dilation=dilation,
groups=cardinality, bias=False,
average_mode=rectify_avg)
 self.bn2 = norm_layer(group_width)
 else:
self.conv2 = nn.Conv2d(
 group_width, group_width, kernel_size=3, stride=stride,
padding=dilation, dilation=dilation,
groups=cardinality, bias=False)
 self.bn2 = norm_layer(group_width)
 self.conv3 = nn.Conv2d(
 group_width, planes * 4, kernel_size=1, bias=False)
 self.bn3 = norm_layer(planes*4)
 if last_gamma:
zeros_(self.bn3.weight)
 self.relu = nn.ReLU(inplace=True)
 self.downsample = downsample
self.dilation = dilation
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
 out = self.bn1(out)
 if self.dropblock_prob > 0.0:
out = self.dropblock1(out)
 out = self.relu(out)
 if self.avd and self.avd_first:
out = self.avd_layer(out)
 out = self.conv2(out)
 if self.radix == 0:
out = self.bn2(out)
 if self.dropblock_prob > 0.0:
out = self.dropblock2(out)
 out = self.relu(out)
 if self.avd and not self.avd_first:
out = self.avd_layer(out)
 out = self.conv3(out)
 out = self.bn3(out)
 if self.dropblock_prob > 0.0:
out = self.dropblock3(out)
 if self.downsample is not None:
residual = self.downsample(x)
 out += residual
out = self.relu(out)
 return out
class ResNet(nn.Module):

 def __init__(self, block, layers, radix=1, groups=1, bottleneck_width=64,
num_classes=1000, dilated=False, dilation=1,
deep_stem=False, stem_width=64, avg_down=False,
rectified_conv=False, rectify_avg=False,
avd=False, avd_first=False,
final_drop=0.0, dropblock_prob=0,
last_gamma=False, norm_layer=nn.BatchNorm2d):
self.cardinality = groups
self.bottleneck_width = bottleneck_width
self.inplanes = stem_width*2 if deep_stem else 64
self.avg_down = avg_down
self.last_gamma = last_gamma
self.radix = radix
self.avd = avd
self.avd_first = avd_first
super(ResNet, self ).__init__()
self.rectified_conv = rectified_conv
self.rectify_avg = rectify_avg
if rectified_conv:
conv_layer = RFConv2d
else:
conv_layer = nn.Conv2d
conv_kwargs = {'average_mode': rectify_avg} if rectified_conv else {}
if deep_stem:
self.conv1 = nn.Sequential(
 conv_layer(3, stem_width, kernel_size=3, stride=2, padding=1, bias=False, **conv_kwargs),
norm_layer(stem_width),
nn.ReLU(inplace=True),
conv_layer(stem_width, stem_width, kernel_size=3, stride=1, padding=1, bias=False, **conv_kwargs),
norm_layer(stem_width),
nn.ReLU(inplace=True),
conv_layer(stem_width, stem_width*2, kernel_size=3, stride=1, padding=1, bias=False, **conv_kwargs), 
)
 else:
self.conv1 = conv_layer(3, 64, kernel_size=7, stride=2, padding=3,
bias=False, **conv_kwargs)
 self.bn1 = norm_layer(self.inplanes)
 self.relu = nn.ReLU(inplace=True)
 self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
 self.layer1 = self._make_layer(block, 64, layers[0], norm_layer=norm_layer, is_first=False)
 self.layer2 = self._make_layer(block, 128, layers[1], stride=2, norm_layer=norm_layer)
 if dilated or dilation == 4:
self.layer3 = self._make_layer(block, 256, layers[2], stride=1,
dilation=2, norm_layer=norm_layer,
dropblock_prob=dropblock_prob)
 self.layer4 = self._make_layer(block, 512, layers[3], stride=1,
dilation=4, norm_layer=norm_layer,
dropblock_prob=dropblock_prob)
 elif dilation==2:
self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
dilation=1, norm_layer=norm_layer,
dropblock_prob=dropblock_prob)
 self.layer4 = self._make_layer(block, 512, layers[3], stride=1,
dilation=2, norm_layer=norm_layer,
dropblock_prob=dropblock_prob)
 else:
self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
norm_layer=norm_layer,
dropblock_prob=dropblock_prob)
 self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
norm_layer=norm_layer,
dropblock_prob=dropblock_prob)
 self.avgpool = GlobalAvgPool2d()
self.drop = nn.Dropout(final_drop)if final_drop > 0.0 else None
self.fc = nn.Linear(512 * block.expansion, num_classes)
 for m in self.modules() :
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2./ n))
elif isinstance(m, norm_layer):
m.weight.data.fill_(1)
 m.bias.data.zero_()
def _make_layer(self, block, planes, blocks, stride=1, dilation=1, norm_layer=None,
dropblock_prob=0.0, is_first=True):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
down_layers = []
if self.avg_down:
if dilation == 1:
down_layers.append(nn.AvgPool2d(kernel_size=stride, stride=stride,
ceil_mode=True, count_include_pad=False))
else:
down_layers.append(nn.AvgPool2d(kernel_size=1, stride=1,
ceil_mode=True, count_include_pad=False))
down_layers.append(nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=1, bias=False))
else:
down_layers.append(nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False))
down_layers.append(norm_layer(planes * block.expansion))
downsample = nn.Sequential(*down_layers)
 layers = []
if dilation == 1 or dilation == 2:
layers.append(block(self.inplanes, planes, stride, downsample=downsample,
radix=self.radix, cardinality=self.cardinality,
bottleneck_width=self.bottleneck_width,
avd=self.avd, avd_first=self.avd_first,
dilation=1, is_first=is_first, rectified_conv=self.rectified_conv,
rectify_avg=self.rectify_avg,
norm_layer=norm_layer, dropblock_prob=dropblock_prob,
last_gamma=self.last_gamma))
elif dilation == 4:
layers.append(block(self.inplanes, planes, stride, downsample=downsample,
radix=self.radix, cardinality=self.cardinality,
bottleneck_width=self.bottleneck_width,
avd=self.avd, avd_first=self.avd_first,
dilation=2, is_first=is_first, rectified_conv=self.rectified_conv,
rectify_avg=self.rectify_avg,
norm_layer=norm_layer, dropblock_prob=dropblock_prob,
last_gamma=self.last_gamma))
else:
raise RuntimeError("=> unknown dilation size: {}".format(dilation))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes,
radix=self.radix, cardinality=self.cardinality,
bottleneck_width=self.bottleneck_width,
avd=self.avd, avd_first=self.avd_first,
dilation=dilation, rectified_conv=self.rectified_conv,
rectify_avg=self.rectify_avg,
norm_layer=norm_layer, dropblock_prob=dropblock_prob,
last_gamma=self.last_gamma))
return nn.Sequential(*layers)
 def forward(self, x):
x = self.conv1(x)
 x = self.bn1(x)
 x = self.relu(x)
 x = self.maxpool(x)
 x = self.layer1(x)
 x = self.layer2(x)
 x = self.layer3(x)
 x = self.layer4(x)
 x = self.avgpool(x)
 x = torch.flatten(x, 1)
 if self.drop:
x = self.drop(x)
 x = self.fc(x)
 return x
def stat_feat(df, features_g, features_c):
df['g_sum'] = df[features_g].sum(axis = 1)
 df['g_mean'] = df[features_g].mean(axis = 1)
 df['g_std'] = df[features_g].std(axis = 1)
 df['g_kurt'] = df[features_g].kurtosis(axis = 1)
 df['g_skew'] = df[features_g].skew(axis = 1)
 df['c_sum'] = df[features_c].sum(axis = 1)
 df['c_mean'] = df[features_c].mean(axis = 1)
 df['c_std'] = df[features_c].std(axis = 1)
 df['c_kurt'] = df[features_c].kurtosis(axis = 1)
 df['c_skew'] = df[features_c].skew(axis = 1)
 df['gc_sum'] = df[features_g + features_c].sum(axis = 1)
 df['gc_mean'] = df[features_g + features_c].mean(axis = 1)
 df['gc_std'] = df[features_g + features_c].std(axis = 1)
 df['gc_kurt'] = df[features_g + features_c].kurtosis(axis = 1)
 df['gc_skew'] = df[features_g + features_c].skew(axis = 1)
 return df, ['g_sum', 'g_mean', 'g_std', 'g_kurt', 'g_skew',
'c_sum', 'c_mean', 'c_std', 'c_kurt', 'c_skew',
'gc_sum', 'gc_mean', 'gc_std', 'gc_kurt', 'gc_skew']
x_develop, new_feat = stat_feat(x_develop, g_cols.to_list() , c_cols.to_list())
 x_test, new_feat = stat_feat(x_test, g_cols.to_list() , c_cols.to_list())
 cont_cols += new_feat<categorify>
pretrained_model = {
'efficientnet-b2': '.. /input/efficientnet-pytorch/efficientnet-b2-27687264.pth'
}
enet_type = 'efficientnet-b4'
device = torch.device('cuda' )
class VarianceThreshold:
def __init__(self, threshold):
self.threshold = threshold
def fit(self, df, cont_cols):
self.cont_cols = cont_cols
self.var = df[cont_cols].var()
good_cols = self.var[self.var > self.threshold]
self.index = good_cols.index.to_list()
self.dropcols = [x for x in cont_cols if x not in self.var[self.var > self.threshold].index.to_list() ]
self.validcols = [x for x in cont_cols if x in self.var[self.var > self.threshold].index.to_list() ]
def transform(self, df):
return df.drop(self.dropcols, axis=1)
 def fit_transform(self, df, cont_cols):
self.fit(df, cont_cols)
 return self.transform(df), self.validcols<define_variables>
class enetv2(nn.Module):
def __init__(self, backbone):
super(enetv2, self ).__init__()
self.enet = enet.EfficientNet.from_name(backbone)
 self.myfc = nn.Sequential(
 nn.Linear(self.enet._fc.in_features,1024), nn.ReLU() , nn.Dropout(p=0.2),
nn.Linear(1024, 264))
self.enet._fc = nn.Identity()
def extract(self, x):
return self.enet(x)
 def forward(self, x):
x = self.extract(x)
 x = self.myfc(x)
 return x
cont_cols = [col for col in x_develop.columns.to_list() if col not in ['sig_id','cp_type','cp_time','cp_dose']]<normalization>
def get_model_enet() :
model =enetv2(enet_type)
 model.load_state_dict(torch.load(".. /input/bird-enet-model/fold3.pth"))
model = model.to(device)
 model.eval()
return model
threshold = 0.2
print('Variance Threshold:', threshold)
 VarThres = VarianceThreshold(threshold)
 x_develop, cont_cols = VarThres.fit_transform(x_develop, cont_cols)
 x_test = VarThres.transform(x_test )<categorify>
def get_model(args: tp.Dict):
model = ResNet(
 Bottleneck, [3, 4, 6, 3],
radix=1, groups=1, bottleneck_width=64,
deep_stem=True, stem_width=32, avg_down=True,
avd=True, avd_first=True)
 del model.fc
model.fc = nn.Sequential(
 nn.Linear(2048, 1024), nn.ReLU() , nn.Dropout(p=0.2),
nn.Linear(1024, 1024), nn.ReLU() , nn.Dropout(p=0.2),
nn.Linear(1024, args["num_classes"]))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 model = model.to(device)
 model.eval()
return model
qt = load('.. /input/update-mx10-model/mx10_qt.joblib')
 x_develop[cont_cols] = qt.fit_transform(x_develop[cont_cols])
 x_test[cont_cols] = qt.transform(x_test[cont_cols] )<feature_engineering>
def prediction_for_clip(test_df: pd.DataFrame,
clip: np.ndarray,
model:ResNet,
model_enet : enetv2,
mel_params: dict,
threshold=0.5,
maxpreds=3, 
):
dataset = TestDataset(df=test_df,
clip=clip,
img_size=224,
melspectrogram_parameters=mel_params)
 loader = data.DataLoader(dataset, batch_size=1, shuffle=False)
 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 model.eval()
model_enet.eval()
prediction_dict = {}
for image, row_id, site in progress_bar(loader):
site = site[0]
row_id = row_id[0]
if site in {"site_1", "site_2"}:
image = image.to(device)
 with torch.no_grad() :
prediction_1 = F.sigmoid(model(image))
prediction_2 = F.sigmoid(model_enet(image))
proba =(prediction_1.detach().cpu().numpy().reshape(-1)+ prediction_2.detach().cpu().numpy().reshape(-1)) /2
events = proba >= threshold
labels = np.argsort(-proba)[:events.sum() ].tolist()
else:
image = image.squeeze(0)
 batch_size = 16
whole_size = image.size(0)
 if whole_size % batch_size == 0:
n_iter = whole_size // batch_size
else:
n_iter = whole_size // batch_size + 1
all_events = set()
probas = []
for batch_i in range(n_iter):
batch = image[batch_i * batch_size:(batch_i + 1)* batch_size]
if batch.ndim == 3:
batch = batch.unsqueeze(0)
 batch = batch.to(device)
 with torch.no_grad() :
prediction_1 = F.sigmoid(model(batch))
prediction_2 = F.sigmoid(model_enet(batch))
proba =(prediction_1.detach().cpu().numpy() + prediction_2.detach().cpu().numpy())/2
probas.append(proba)
 probas = np.vstack(probas)
 probas = probas.max(0)
 events =(probas>=threshold)
 labels = np.argsort(-probas)[:events.sum() ].tolist()
if len(labels)== 0:
prediction_dict[row_id] = "nocall"
else:
labels_str_list = list(map(lambda x: INV_BIRD_CODE[x], labels))
label_string = " ".join(labels_str_list[:maxpreds])
 prediction_dict[row_id] = label_string
return prediction_dict
def create_folds(df, fold_no, fold_type='mls_kfold', save=False):

 if fold_type == 'kfold':
kf = KFold(n_splits=fold_no, shuffle=True, random_state=SEED)
 elif fold_type == 'mls_kfold':
kf = MultilabelStratifiedKFold(n_splits=fold_no, random_state=SEED)
 df['Fold'] = -1
df.reset_index(inplace=True)
 for fold,(t, v)in enumerate(kf.split(df, df)) :
df.loc[v, 'Fold'] = fold
df.set_index('sig_id', inplace=True)
 if save:
pass<load_pretrained>
def prediction(test_df: pd.DataFrame,
test_audio: Path,
model_config: dict,
mel_params: dict,
target_sr: int,
threshold=0.5,
maxpreds = 3, 
):
model = get_model(model_config)
 model_enet = get_model_enet()
unique_audio_id = test_df.audio_id.unique()
warnings.filterwarnings("ignore")
 prediction_dfs = []
for audio_id in unique_audio_id:
with timer(f"Loading {audio_id}"):
clip, _ = librosa.load(test_audio /(audio_id + ".mp3"),
sr=target_sr,
mono=True,
res_type="kaiser_fast")
 test_df_for_audio_id = test_df.query(
 f"audio_id == '{audio_id}'" ).reset_index(drop=True)
 with timer(f"Prediction on {audio_id}"):
prediction_dict = prediction_for_clip(test_df_for_audio_id,
clip=clip,
model=model,
model_enet = model_enet,
mel_params=mel_params,
threshold=threshold,
maxpreds = maxpreds, 
)
 row_id = list(prediction_dict.keys())
 birds = list(prediction_dict.values())
 prediction_df = pd.DataFrame({
"row_id": row_id,
"birds": birds
})
 prediction_dfs.append(prediction_df)
 prediction_df = pd.concat(prediction_dfs, axis=0, sort=False ).reset_index(drop=True)
 return prediction_df
<choose_model_class><EOS> 
submission = prediction(test_df=test,
test_audio=TEST_AUDIO_DIR,
model_config=model_config,
mel_params=melspectrogram_parameters,
target_sr=TARGET_SR,
threshold=0.56,
maxpreds=2, 
)
 submission.to_csv("submission.csv", index=False )