{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Calculate F score on multi-label classification task with scikit-learn and scipy.sparse\n---"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\n\nfrom scipy.sparse import lil_matrix\nfrom sklearn.metrics import fbeta_score","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","collapsed":true,"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":false},"cell_type":"markdown","source":"## single-label\nexample from [scikit-learn fbeta_score](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.fbeta_score.html)"},{"metadata":{"trusted":true},"cell_type":"code","source":"y_true = [0, 1, 2, 0, 1, 2]\ny_pred = [0, 2, 1, 0, 0, 1]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fbeta_score(y_true, y_pred, average='macro', beta=0.5)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## multi-label"},{"metadata":{"trusted":true},"cell_type":"code","source":"y_true = [[0, 1], [1], [1, 2], [0], [1], [0, 2]]\ny_pred = [[0], [0, 2], [1, 2], [2], [0, 1], [1, 2]]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# fbeta_score(y_true, y_pred, average='macro', beta=0.5)\n# -> ValueError: You appear to be using a legacy multi-label data representation. Sequence of sequences are no longer supported; use a binary array or sparse matrix instead.","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Convert into sparse matrix"},{"metadata":{"trusted":true},"cell_type":"code","source":"def label_to_sm(labels, n_classes):\n    sm = lil_matrix((len(labels), n_classes))\n    for i, label in enumerate(labels):\n        sm[i, label] = 1\n    return sm","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_true_sm = label_to_sm(labels=y_true, n_classes=3)\ny_true_sm.toarray()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred_sm = label_to_sm(labels=y_pred, n_classes=3)\ny_pred_sm.toarray()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fbeta_score(y_true_sm, y_pred_sm, average='macro', beta=0.5)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"yay!"}],"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}