text_plain_output_1.png
from sklearn.metrics import cohen_kappa_score

import cv2

import numpy as np

import numpy as np # linear algebra

import pandas as pd

import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

import scipy as sp

SIZE = 224
train_df = pd.read_csv(PATH + '/train.csv')
test_df = pd.read_csv(PATH + '/sample_submission.csv')

def crop_image(img, tol=7):
    mask = img > tol
    return img[np.ix_(mask.any(1), mask.any(0))]
def open_aptos2019_image(fn, convert_mode, after_open) -> Image:
    image = cv2.imread(fn)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    image = crop_image(image)
    image = cv2.resize(image, (SIZE, SIZE))
    image = cv2.addWeighted(image, 4, cv2.GaussianBlur(image, (0, 0), SIZE / 10), -4, 128)
    return Image(pil2tensor(image, np.float32).div_(255))
vision.data.open_image = open_aptos2019_image

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 = 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')
    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']

optR = OptimizedRounder()
optR.fit(valid_preds, valid_y)
coefficients = optR.coefficients()
valid_predictions = optR.predict(valid_preds, coefficients)[:, 0].astype(int)
test_predictions = optR.predict(test_preds, coefficients)[:, 0].astype(int)
valid_score = cohen_kappa_score(valid_y.numpy().astype(int), valid_predictions, weights='quadratic')

test_df.diagnosis = test_predictions
test_df.to_csv('submission.csv', index=None)
test_df.head()