{"cells":[{"metadata":{},"cell_type":"markdown","source":"I implemented continuous approximation of quadratic weighted cohen's kappa on Keras refering sklearn implementation.  The below function can be used as loss function (but for loss, shoudd change 1-k to k for smaller the better).  \nBut this does not work well when I use it directly as loss function in optimization...why ?"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport keras.backend as K\n\ndef QWKloss(y_true, y_pred):\n    N = K.sum(y_true)\n    n_classes = 5\n\n    # K.expand_dims(y_true, -1)  # N * K * 1\n    # K.expand_dims(y_pred, 1)  # N * 1 * K\n    C = K.batch_dot(K.expand_dims(y_true, -1), K.expand_dims(y_pred, 1))  # N * K * K\n    C = K.sum(C, axis=0)\n    \n    sum0 = K.sum(C, axis=0)\n    sum1 = K.sum(C, axis=1)\n    E = K.dot(K.reshape(sum0, (n_classes,1)), K.reshape(sum1, (1,n_classes))) / N\n    \n    W = np.zeros([n_classes, n_classes], dtype=np.int)\n    W += np.arange(n_classes)\n    W = (W - W.T) ** 2\n    \n    k = K.sum(W*C) / K.sum(W*E)\n    k = k\n    return 1-k","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"# check ~ comparing sklearn\nfor _ in range(10):\n    N = 1000\n    y_true = np.eye(5)[np.random.randint(5, size=(N))]\n    y_pred = np.random.uniform(size=(N, 5))\n    y_pred /= y_pred.sum(axis=1, keepdims=True)\n\n    from sklearn.metrics import cohen_kappa_score\n    # sklearn can not treat probability vector.\n    skl = cohen_kappa_score(np.argmax(y_true, axis=1), np.argmax(y_pred, axis=1), weights='quadratic')\n\n    s = QWKloss(y_true, np.eye(5)[np.argmax(y_pred, axis=1)])\n    org = K.get_value(s)\n    \n    print(skl, org)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}