{"cells":[{"metadata":{"_uuid":"d165f767744afde69a48aaa03d9a1de555dd6ee1"},"cell_type":"markdown","source":"Small script to calculate exact class weights using probing results from :  https://www.kaggle.com/c/PLAsTiCC-2018/discussion/67194 "},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"'''\nSolve system of non-linear equations to determine exact weights after probing\n'''\n\nimport numpy as np\nfrom scipy.optimize import fsolve\n\n# Class probing results and name for the weight var in fsolve below\ncd = {\n    '99' : (30.701, 'a'),\n    '95' : (32.620, 'b'),\n    '92' : (32.620, 'c'),\n    '90' : (32.620, 'd'),\n    '88' : (32.620, 'e'),\n    '67' : (32.620, 'f'),\n    '65' : (32.620, 'g'),\n    '64' : (30.692, 'h'),\n    '62' : (32.620, 'i'),\n    '53' : (32.622, 'j'),\n    '52' : (32.620, 'k'),\n    '42' : (32.620, 'l'),\n    '16' : (32.620, 'm'),\n    '15' : (30.702, 'n'),\n    '6' : (32.620, 'o'),\n}\n\n# Build non-linear system of equations expression\nfinal_str = ''\nfor i, (v, var) in enumerate(cd.values()):\n    sum_except = ''\n    sum_all = ''\n    for j, (v2, var2) in enumerate(cd.values()):\n        sum_all += var2\n        if j != i:\n            sum_except += var2\n        else:\n            sum_except += '0'\n        if j < len(cd.values()) - 1:\n            sum_all += ' + '\n            sum_except += ' + '\n    final_str = final_str + f'{-np.log(1e-15)} * ({sum_except}) / ({sum_all}) - {str(v)},'\n\n#print(final_str)\n\n# Solve non-linear system of eqs\ndef eqs(aa):\n    a, b, c, d, e, f, g, h, i, j, k, l, m, n, o = aa\n    return (eval(final_str))\n\nres = fsolve(eqs, np.ones(15))\n\n# Normalize weights for convenience\nres = res / np.min(res)\n\n# Print exact weights\nfor _class, weight in zip(cd.keys(), res):\n    print(f'Weight for class {_class} = {weight:.5f}')","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","collapsed":true,"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":false},"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.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}