Kaggle competition: Freesound Audio Tagging 2019
<SOS> metric: weightedlabelrankingaverageprecision Kaggle data source: freesound-audio-tagging-2019<predict_on_test>
import gc
import os
import pickle
import random
import time
from collections import Counter, defaultdict
from functools import partial
from pathlib import Path
from psutil import cpu_count
import librosa
import numpy as np
import pandas as pd
from PIL import Image
from sklearn.model_selection import train_test_split
import torch
import torch.nn as nn
import torch.nn.functional as F
from fastprogress import master_bar, progress_bar
from torch.optim import Adam
from torch.optim.lr_scheduler import CosineAnnealingLR
from torch.utils.data import Dataset, DataLoader
from torchvision.transforms import transforms
xgb_preds = xgb_model.predict(X_test)
 lgbm_preds = lgbm_model.predict(X_test)
 final_preds =(xgb_preds + lgbm_preds)/ 2
final_preds = final_preds.clip(0,20)
 final_preds<save_to_csv>
torch.cuda.is_available()
submission = pd.DataFrame({"item_cnt_month": final_preds})
 submission.index.name="ID"
submission
submission.to_csv("submission.csv" )<set_options>
def seed_everything(seed):
random.seed(seed)
 os.environ['PYTHONHASHSEED'] = str(seed)
 np.random.seed(seed)
 torch.manual_seed(seed)
 torch.cuda.manual_seed(seed)
 torch.backends.cudnn.deterministic = True
SEED = 520
seed_everything(SEED )
%matplotlib inline
sns.set(style="darkgrid")
 warnings.filterwarnings("ignore")
 pd.set_option('display.max_rows', 500)
 pd.set_option('display.max_columns', 100)
 pd.set_option('display.float_format', lambda x: '%.2f' % x)
 sys.version_info<load_from_csv>
N_JOBS = cpu_count()
os.environ['MKL_NUM_THREADS'] = str(N_JOBS)
 os.environ['OMP_NUM_THREADS'] = str(N_JOBS)
 DataLoader = partial(DataLoader, num_workers=N_JOBS )
DATA_FOLDER = '.. /input/competitive-data-science-predict-future-sales/'
train = pd.read_csv(os.path.join(DATA_FOLDER, 'sales_train.csv'))
items = pd.read_csv(os.path.join(DATA_FOLDER, 'items.csv'))
items = items.drop('item_name', axis=1)
 test = pd.read_csv(os.path.join(DATA_FOLDER, 'test.csv')).set_index('ID')
 test['date_block_num'] = 34 
<categorify>
def _one_sample_positive_class_precisions(scores, truth):

 num_classes = scores.shape[0]
pos_class_indices = np.flatnonzero(truth > 0)
 if not len(pos_class_indices):
return pos_class_indices, np.zeros(0)
 retrieved_classes = np.argsort(scores)[::-1]
class_rankings = np.zeros(num_classes, dtype=np.int)
 class_rankings[retrieved_classes] = range(num_classes)
 retrieved_class_true = np.zeros(num_classes, dtype=np.bool)
 retrieved_class_true[class_rankings[pos_class_indices]] = True
retrieved_cumulative_hits = np.cumsum(retrieved_class_true)
 precision_at_hits =(
 retrieved_cumulative_hits[class_rankings[pos_class_indices]] / 
(1 + class_rankings[pos_class_indices].astype(np.float)))
 return pos_class_indices, precision_at_hits
def calculate_per_class_lwlrap(truth, scores):

 assert truth.shape == scores.shape
num_samples, num_classes = scores.shape
precisions_for_samples_by_classes = np.zeros(( num_samples, num_classes))
for sample_num in range(num_samples):
pos_class_indices, precision_at_hits =(
 _one_sample_positive_class_precisions(scores[sample_num, :],
truth[sample_num, :]))
precisions_for_samples_by_classes[sample_num, pos_class_indices] =(
 precision_at_hits)
 labels_per_class = np.sum(truth > 0, axis=0)
 weight_per_class = labels_per_class / float(np.sum(labels_per_class))
per_class_lwlrap =(np.sum(precisions_for_samples_by_classes, axis=0)/
np.maximum(1, labels_per_class))
return per_class_lwlrap, weight_per_class
def compress_columns(df,columns,keyword,search_type,datatype):
if search_type=='in':
valid_features = [x for x in columns if keyword in x]
elif search_type=='start':
valid_features = [x for x in columns if x.startswith(keyword)]
if len(valid_features):
for f in valid_features:
df[f] = df[f].round().astype(datatype)
 return df
def data_compression(df):
features = df.columns.values
if 'date_block_num' in features:
df['date_block_num'] = df['date_block_num'].astype(np.int8)
 if 'shop_id' in features:
df['shop_id'] = df['shop_id'].astype(np.int8)
 if 'item_category_id' in features:
df['item_category_id'] = df['item_category_id'].astype(np.int8)
 if 'item_id' in features:
df['item_id'] = df['item_id'].astype(np.int16)
 if 'item_price' in features:
df['item_price'] = df['item_price'].astype(np.float32)
 if 'item_id_avg_item_price' in features:
df['item_id_avg_item_price'] = df['item_id_avg_item_price'].astype(np.float32)
 df = compress_columns(df,features,'item_id_sum_item_cnt_day','in',np.int16)
 df = compress_columns(df,features,'item_id_avg_item_cnt_day','in',np.float16)
 df = compress_columns(df,features,'shop_id_avg_item_price','in',np.float16)
 df = compress_columns(df,features,'shop_id_sum_item_cnt_day','in',np.int16)
 df = compress_columns(df,features,'shop_id_avg_item_cnt_day','in',np.float16)
 df = compress_columns(df,features,'item_category_id_avg_item_price','in',np.float16)
 df = compress_columns(df,features,'item_category_id_sum_item_cnt_day','in',np.int32)
 df = compress_columns(df,features,'item_category_id_avg_item_cnt_day','in',np.float16)
 df = compress_columns(df,features,'item_cnt_day','start',np.int16)
 return df<categorify>
dataset_dir = Path('.. /input/freesound-audio-tagging-2019')
 preprocessed_dir = Path('.. /input/fat2019_prep_mels1' )
train = data_compression(train)
 items = data_compression(items)
 test = data_compression(test )<merge>
csvs = {
'train_curated': dataset_dir / 'train_curated.csv',
'train_noisy': preprocessed_dir / 'trn_noisy_best50s.csv',
'sample_submission': dataset_dir / 'sample_submission.csv',
}
dataset = {
'train_curated': dataset_dir / 'train_curated',
'train_noisy': dataset_dir / 'train_noisy',
'test': dataset_dir / 'test',
}
mels = {
'train_curated': preprocessed_dir / 'mels_train_curated.pkl',
'train_noisy': preprocessed_dir / 'mels_trn_noisy_best50s.pkl',
'test': preprocessed_dir / 'mels_test.pkl',
}
train = pd.merge(train,items,on='item_id',how='left')
 test = pd.merge(test,items, on='item_id', how='left' )<feature_engineering>
train_curated = pd.read_csv(csvs['train_curated'])
 train_noisy = pd.read_csv(csvs['train_noisy'])
 train_df = pd.concat([train_curated, train_noisy], sort=True, ignore_index=True)
 train_df.head()
train.loc[train.shop_id == 0, 'shop_id'] = 57
test.loc[test.shop_id == 0, 'shop_id'] = 57
train.loc[train.shop_id == 1, 'shop_id'] = 58
test.loc[test.shop_id == 1, 'shop_id'] = 58
train.loc[train.shop_id == 10, 'shop_id'] = 11
test.loc[test.shop_id == 10, 'shop_id'] = 11<merge>
test_df = pd.read_csv(csvs['sample_submission'])
 test_df.head()
train_m = train.groupby(['date_block_num','shop_id','item_id'] ).agg({'item_cnt_day':'sum','item_price':np.mean} ).reset_index()
train_m = pd.merge(grid,train_m,on=['date_block_num','shop_id','item_id'],how='left' ).fillna(0)
 train_m = pd.merge(train_m,items,on='item_id',how='left')
 train_m = data_compression(train_m )<merge>
labels = test_df.columns[1:].tolist()
labels
for type_id in ['item_id', 'shop_id', 'item_category_id']:
for column_id, aggregator, aggtype in [('item_price',np.mean,'avg'),('item_cnt_day',np.sum,'sum'),('item_cnt_day',np.mean,'avg')]:
mean_df = train.groupby([type_id,'date_block_num'] ).aggregate(aggregator ).reset_index() [[column_id,type_id,'date_block_num']]
mean_df.columns = [type_id+'_'+aggtype+'_'+column_id,type_id,'date_block_num']
train_m = pd.merge(train_m, mean_df, on=['date_block_num',type_id], how='left')
 del mean_df
gc.collect()<set_options>
num_classes = len(labels)
 num_classes
del train
gc.collect()<categorify>
y_train = np.zeros(( len(train_df), num_classes)).astype(int)
 for i, row in enumerate(train_df['labels'].str.split(',')) :
for label in row:
idx = labels.index(label)
 y_train[i, idx] = 1
y_train.shape
for f in train_m.columns:
if 'item_cnt' in f:
train_m[f] = train_m[f].fillna(0)
 elif 'item_price' in f:
train_m[f] = train_m[f].fillna(train_m[f].median())
 train_m = data_compression(train_m)
 train_m.info(verbose=False )<define_variables>
with open(mels['train_curated'], 'rb')as curated, open(mels['train_noisy'], 'rb')as noisy:
x_train = pickle.load(curated)
 x_train.extend(pickle.load(noisy))
with open(mels['test'], 'rb')as test:
x_test = pickle.load(test)
 len(x_train), len(x_test )
lag_features = list(train_m.columns[6:])+['item_cnt_day']
lags = [1,2,3,6]<merge>
class FATTestDataset(Dataset):
def __init__(self, fnames, mels, transforms, tta=5):
super().__init__()
self.fnames = fnames
self.mels = mels
self.transforms = transforms
self.tta = tta
def __len__(self):
return len(self.fnames)* self.tta
def __getitem__(self, idx):
new_idx = idx % len(self.fnames)
 image = Image.fromarray(self.mels[new_idx], mode='RGB')
 time_dim, base_dim = image.size
crop = random.randint(0, time_dim - base_dim)
 image = image.crop([crop, 0, crop + base_dim, base_dim])
 image = self.transforms(image ).div_(255)
 fname = self.fnames[new_idx]
return image, fname
for lag in lags:
train_new_df = train_m.copy()
train_new_df['date_block_num'] += lag
train_new_df = train_new_df[['date_block_num','shop_id','item_id']+lag_features]
train_new_df.columns = ['date_block_num','shop_id','item_id'] + [x+'_lag_'+str(lag)for x in lag_features]
train_m = pd.merge(train_m,train_new_df,on=['date_block_num','shop_id','item_id'],how='left')
 del train_new_df
gc.collect()
print('lag %s processed' %lag )<categorify>
transforms_dict = {
'train': transforms.Compose([
transforms.RandomHorizontalFlip(0.5),
transforms.ToTensor() ,
]),
'test': transforms.Compose([
transforms.RandomHorizontalFlip(0.5),
transforms.ToTensor() ,
]),
}
for f in train_m.columns:
if 'item_cnt' in f:
train_m[f] = train_m[f].fillna(0)
 elif 'item_price' in f:
train_m[f] = train_m[f].fillna(train_m[f].median())
 train_m = data_compression(train_m)
 train_m.info(verbose=False )<data_type_conversions>
class ConvBlock(nn.Module):
def __init__(self, in_channels, out_channels, downsample = None):
super().__init__()
self.downsample = downsample
self.conv1 = nn.Sequential(
 nn.Conv2d(in_channels, out_channels, 3, 1, 1),
nn.BatchNorm2d(out_channels),
nn.ReLU() , 
)
 self.conv2 = nn.Sequential(
 nn.Conv2d(out_channels, out_channels, 3, 1, 1),
nn.BatchNorm2d(out_channels),
nn.ReLU() , 
)
 self._init_weights()
def _init_weights(self):
for m in self.modules() :
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight)
 if m.bias is not None:
nn.init.zeros_(m.bias)
 elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
 nn.init.zeros_(m.bias)
 def forward(self, x):
residual = x
out = self.conv1(x)
 out = self.conv2(out)
 out = F.avg_pool2d(out, 2)
 return out
max_clip = 30
train_m['item_cnt_day'] = train_m['item_cnt_day'].clip(0,max_clip ).astype(np.float16 )<merge>
class Classifier(nn.Module):
def __init__(self, num_classes):
super().__init__()
self.conv = nn.Sequential(
 ConvBlock(in_channels=3, out_channels=64),
ConvBlock(in_channels=64, out_channels=128),
ConvBlock(in_channels=128, out_channels=256),
ConvBlock(in_channels=256, out_channels=512)
)
 self.fc = nn.Sequential(
 nn.Dropout(0.2),
nn.Linear(512, 128),
nn.PReLU() ,
nn.BatchNorm1d(128),
nn.Dropout(0.1),
nn.Linear(128, num_classes), 
)
 def forward(self, x):
x = self.conv(x)
 x = torch.mean(x, dim=3)
 x, _ = torch.max(x, dim=2)
 x = self.fc(x)
 return x
for lag in lags:
train_new_df = train_m.copy()
train_new_df['date_block_num'] += lag
train_new_df = train_new_df[['date_block_num','shop_id','item_id']+lag_features]
train_new_df.columns = ['date_block_num','shop_id','item_id'] + [x+'_lag_'+str(lag)for x in lag_features]
test = pd.merge(test,train_new_df,on=['date_block_num','shop_id','item_id'],how='left')
 del train_new_df
gc.collect()
print('lag %s processed' %lag )<categorify>
Classifier(num_classes=num_classes )
for f in test.columns:
if 'item_cnt' in f:
test[f] = test[f].fillna(0)
 elif 'item_price' in f:
test[f] = test[f].fillna(test[f].median())
 test = data_compression(test )<drop_column>
def train_model(x_train, y_train, train_transforms):
num_epochs = 97
batch_size = 64
test_batch_size = 256
lr = 1e-3
eta_min = 1e-5
t_max = 10
num_classes = y_train.shape[1]
x_trn, x_val, y_trn, y_val = train_test_split(x_train, y_train, test_size=0.2, random_state=SEED)
 train_dataset = FATTrainDataset(x_train, y_train, train_transforms)
 valid_dataset = FATTrainDataset(x_val, y_val, train_transforms)
 train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
 valid_loader = DataLoader(valid_dataset, batch_size=test_batch_size, shuffle=False)
 model = Classifier(num_classes=num_classes ).cuda()
criterion = nn.BCEWithLogitsLoss().cuda()
optimizer = Adam(params=model.parameters() , lr=lr, amsgrad=False)
 scheduler = CosineAnnealingLR(optimizer, T_max=t_max, eta_min=eta_min)
 best_epoch = -1
best_lwlrap = 0.
 mb = master_bar(range(num_epochs))
for epoch in mb:
start_time = time.time()
model.train()
avg_loss = 0.
 for x_batch, y_batch in train_loader:
preds = model(x_batch.cuda())
 loss = criterion(preds, y_batch.cuda())
 optimizer.zero_grad()
loss.backward()
optimizer.step()
avg_loss += loss.item() / len(train_loader)
 model.eval()
valid_preds = np.zeros(( len(x_val), num_classes))
avg_val_loss = 0.
 ')
 for i,(x_batch, y_batch)in enumerate(valid_loader):
preds = model(x_batch.cuda() ).detach()
loss = criterion(preds, y_batch.cuda())
 preds = torch.sigmoid(preds)
 valid_preds[i * test_batch_size:(i+1)* test_batch_size] = preds.cpu().numpy()
avg_val_loss += loss.item() / len(valid_loader)
 score, weight = calculate_per_class_lwlrap(y_val, valid_preds)
 lwlrap =(score * weight ).sum()
scheduler.step()
if(epoch + 1)% 1 == 0:
elapsed = time.time() - start_time
mb.write(f'Epoch {epoch+1} - avg_train_loss: {avg_loss:.4f} avg_val_loss: {avg_val_loss:.4f} val_lwlrap: {lwlrap:.6f} time: {elapsed:.0f}s')
 if lwlrap > best_lwlrap:
best_epoch = epoch + 1
best_lwlrap = lwlrap
torch.save(model.state_dict() , 'weight_best.pt')
 ')
 return {
'best_epoch': best_epoch,
'best_lwlrap': best_lwlrap,
}
cols_to_drop = lag_features[:-1] + ['item_price']
print('Columns to drop')
 print(cols_to_drop )<drop_column>
result = train_model(x_train, y_train, transforms_dict['train'] )
train_cols = train_m.columns.values
test_cols = test.columns.values
for c in cols_to_drop:
if c in train_cols:
train_m = train_m.drop(c,axis=1)
 if c in test_cols:
test = test.drop(c,axis=1 )<data_type_conversions>
test_preds = predict_model(test_df['fname'], x_test, transforms_dict['test'], num_classes, tta=35 )
train_m['month'] = train_m['date_block_num']%12
train_m['month'] = train_m['month'].astype(np.int8)
 days = pd.Series([31,28,31,30,31,30,31,31,30,31,30,31])
 train_m['days'] = train_m['month'].map(days ).astype(np.int8)
 test['month'] = 11
test['month'] = test['month'].astype(np.int8)
 test['days'] = 30
test['days'] = test['days'].astype(np.int8 )<filter>
test_df[labels] = test_preds.values
test_df.to_csv('submission.csv', index=False)
 test_df.head()