Kaggle competition: APTOS 2019 Blindness Detection
<SOS> metric: QuadraticWeightedKappa Kaggle data source: aptos-2019-blindness-detection<feature_engineering>
%reload_ext autoreload
%autoreload 2
%matplotlib inline
%matplotlib inline
cnt_vec = CountVectorizer()
cnt_vec.fit(df_train['joined_ing'].values.tolist())
 x_train_cnt = cnt_vec.transform(df_train['joined_ing'].values.tolist())
 x_test_cnt = cnt_vec.transform(df_test['joined_ing'].values.tolist() )<categorify>
md_ef = EfficientNet.from_pretrained('efficientnet-b5', num_classes=1 )
tfidf_vec = TfidfVectorizer(binary=True)
 tfidf_vec.fit(df_train['joined_ing'].values.tolist())
 x_train_tfidf = tfidf_vec.transform(df_train['joined_ing'].values.tolist())
 x_test_tfidf = tfidf_vec.transform(df_test['joined_ing'].values.tolist() )<categorify>
def get_df() :
base_image_dir = os.path.join('.. ', 'input/aptos2019-blindness-detection/')
 train_dir = os.path.join(base_image_dir,'train_images/')
 df = pd.read_csv(os.path.join(base_image_dir, 'train.csv'))
df['path'] = df['id_code'].map(lambda x: os.path.join(train_dir,'{}.png'.format(x)))
 df = df.drop(columns=['id_code'])
 df = df.sample(frac=1 ).reset_index(drop=True)
 test_df = pd.read_csv('.. /input/aptos2019-blindness-detection/sample_submission.csv')
 return df, test_df
df, test_df = get_df()
x_train = np.hstack(( x_train_cnt.todense() , x_train_tfidf.todense()))
x_test = np.hstack(( x_test_cnt.todense() , x_test_tfidf.todense()))<train_on_grid>
bs = 64
sz = 224
tfms = get_transforms(do_flip=True,flip_vert=True )
model = OneVsRestClassifier(LogisticRegression())
 model.fit(x_train, y_train )<predict_on_test>
def qk(y_pred, y):
return torch.tensor(cohen_kappa_score(torch.round(y_pred), y, weights='quadratic'), device='cuda:0' )
y_pred = model.predict(x_test )<categorify>
learn = Learner(data,
md_ef,
metrics = [qk],
model_dir="models" ).to_fp16()
learn.data.add_test(ImageList.from_df(test_df,
'.. /input/aptos2019-blindness-detection',
folder='test_images',
suffix='.png'))
id_test = df_test['id']
y_pred = le.inverse_transform(y_pred )<save_to_csv>
learn.load('abcdef');
df_sub = pd.DataFrame()
df_sub['id'] = id_test
df_sub['cuisine'] = y_pred
df_sub.to_csv('ans_sub.csv', index=False )<string_transform>
class OptimizedRounder(object):
def __init__(self):
self.coef_ = 0
def _kappa_loss(self, coef, X, y):
X_p = np.copy(X)
 for i, pred in enumerate(X_p):
if pred < coef[0]:
X_p[i] = 0
elif pred >= coef[0] and pred < coef[1]:
X_p[i] = 1
elif pred >= coef[1] and pred < coef[2]:
X_p[i] = 2
elif pred >= coef[2] and pred < coef[3]:
X_p[i] = 3
else:
X_p[i] = 4
ll = metrics.cohen_kappa_score(y, X_p, weights='quadratic')
 return -ll
def fit(self, X, y):
loss_partial = partial(self._kappa_loss, X=X, y=y)
 initial_coef = [0.5, 1.5, 2.5, 3.5]
self.coef_ = sp.optimize.minimize(loss_partial, initial_coef, method='nelder-mead')
 print(-loss_partial(self.coef_['x']))
def predict(self, X, coef):
X_p = np.copy(X)
 for i, pred in enumerate(X_p):
if pred < coef[0]:
X_p[i] = 0
elif pred >= coef[0] and pred < coef[1]:
X_p[i] = 1
elif pred >= coef[1] and pred < coef[2]:
X_p[i] = 2
elif pred >= coef[2] and pred < coef[3]:
X_p[i] = 3
else:
X_p[i] = 4
return X_p
def coefficients(self):
return self.coef_['x']
train_df = pd.read_json('.. /input/train.json')
 test_df = pd.read_json('.. /input/test.json')
 train_df['seperated_ingredients'] = train_df['ingredients'].apply(','.join)
 test_df['seperated_ingredients'] = test_df['ingredients'].apply(','.join )<categorify>
def run_subm(learn=learn, coefficients=[0.6, 1.6, 2.6, 3.6]):
opt = OptimizedRounder()
preds,y = learn.get_preds(DatasetType.Test)
 tst_pred = opt.predict(preds, coefficients)
 test_df.diagnosis = tst_pred.astype(int)
 test_df.to_csv('submission.csv',index=False)
 print('done' )