{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\n'''\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n'''\n# Any results you write to the current directory are saved as output.\nfrom sklearn.metrics import recall_score\nimport time\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from numba import jit,autojit\n@jit('float32(float32[:],float32[:])')\ndef score(label:np.array,target:np.array) -> float:\n    score = 0\n    labels = np.concatenate((label,target))\n    labels = np.unique(labels)\n    for i in labels:\n        index = np.where(target==i)\n        TP = (label[index]==i).sum()\n        FN = (label[index]!=i).sum()\n        score += (TP / (TP+FN+1e-20))\n    return score/(len(labels))\ndef MacroRecall(label:np.array,target:np.array) -> float:\n    return score(label.astype(np.float32),target.astype(np.float32))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Record scores & excecution times roughly loop x 100000"},{"metadata":{"trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"num_trial=100000\ntimes1=[]\nrecords1=[]\ntimes2=[]\nrecords2=[]\nfor _ in range(num_trial):\n    num_labels = np.random.randint(168)\n    num_size = np.random.randint(500)\n    label = np.random.randint(num_labels+1,size=num_size+1)\n    target = np.random.randint(num_labels+1,size=num_size+1)\n    start_time = time.monotonic()\n    records1.append(MacroRecall(label,target))\n    times1.append(time.monotonic()-start_time)\n    start_time = time.monotonic()\n    records2.append(recall_score(target,label,average='macro'))\n    times2.append(time.monotonic()-start_time)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Check discrepancies threshold 1e-7 and 1e-5"},{"metadata":{"trusted":true},"cell_type":"code","source":"diff_scores = np.subtract(records1,records2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Mismatch counts : {}'.format(sum(abs(diff_scores)>=1e-7)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Mismatch counts : {}'.format(sum(abs(diff_scores)>=1e-5)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"custom_mean = np.mean(times1)\nsklearn_mean = np.mean(times2)\ncustom_std = np.std(times1)\nsklearn_std = np.std(times2)\nmean = np.mean(np.hstack([times1,times2]))\nstd = np.std(np.hstack([times1,times2]))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### check execution time"},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.hist(np.log(times1),bins=2000,label='custom')\nplt.hist(np.log(times2),bins=2000,label='sklearn-macro recall')\nplt.legend()\nplt.title('log transform of excution time')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(f'the percentage of outlier custom :{100*sum(times1>=mean+10*std)/len(times1)}%')\nprint(f'the percentage of outlier sklearn macro recall :{100*sum(times2>=mean+10*std)/len(times2)}%')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.bar(['custom', 'sklearn-macro recall'],np.hstack([custom_mean,sklearn_mean]),yerr=np.hstack([custom_std,sklearn_std]))\nplt.ylim((0,max(custom_mean,sklearn_mean)+2*0.002))\nplt.title('mean execution time with std')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"check_records = pd.DataFrame([records1,times1,records2,times2,diff_scores]).T.rename(columns={0:'custom'\n                                                                                              ,1:'custom_exec'\n                                                                                             ,2:'sklearn'\n                                                                                              ,3:'sklearn_exec'\n                                                                                             ,4:'diff_score'})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"check_records.to_csv('check_records.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"check_records.sample(20)","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":1}