{"cells":[{"metadata":{},"cell_type":"markdown","source":"# What is Pulmonary Fibrosis?\nAccording to [this website](https://www.pulmonaryfibrosis.org/life-with-pf/about-pf), Pulmonary Fibrosis is a lung disease that can be caused by many factors (e.g., drug, radiation, environmen, etc.)\n\nSome symptoms for this include:\n- Fatigue and weakness\n- Loss of appetite\n- Unexplained weight loss\n\n![A brief explanation of the Pulmonary Fibrosis](https://www.pulmonaryfibrosis.org/images/default-source/default-album/normal-and-impaired-gas-exchange.png?sfvrsn=c3b0918d_0)","execution_count":null},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"! ls -all ../input/osic-pulmonary-fibrosis-progression","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"dir = '../input/osic-pulmonary-fibrosis-progression/'\n# Read in train.csv.\ntrain_df = pd.read_csv(dir + 'train.csv')\ntrain_df.head(10)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# What's the age distribution of our patients?","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.distplot(train_df['Age'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# FVC distribution for both genders","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plot the distribution of FVC for Male patients.\nsns.distplot(train_df[train_df['Sex'] == 'Male']['FVC'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plot the distribution of FVC for Female patients.\nsns.distplot(train_df[train_df['Sex'] == 'Female']['FVC'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"According to [this site](https://www.nuvoair.com/blog/do-you-know-how-to-interpret-the-results-of-your-spirometry-test), \n- Average normal FVC value in healthy males aged 20~60 range from 4750 to 5500 ml.\n- Average normal FVC value in healthy females aged 20~60 range from 3250 to 3750 ml.\n\n\nOur data shows\n- Male patients' FVC is around 3000\n- Femaile patients' FVC is around 1500. (Although there is a fat tail in the distribution).","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"# What avg(FVC) partition by week looks like?\n\nSince the patients are receiving treatment, I'm expecting to see the aggregated trend for avg(FVC) from all patients to move up.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Calculate FVC avg partition by week column.\ntrain_df['avg_of_week'] = train_df.groupby(['Weeks'])['FVC'].transform(np.mean)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# A specific user's avg(FVC) movement compared to avg(FVC) per week.\n\nid_recover = 'ID00076637202199015035026'\n\ndef plot_specific_patient(id):\n    train_df_specificUser = train_df[train_df['Patient'] == id]\n    train_df_specificUser = train_df_specificUser.sort_values(\n        by='Weeks', ascending=False\n    )\n    # Plot\n    sns.lineplot(\n        x='Weeks',\n        y='value',\n        hue='variable',\n        data=pd.melt(train_df_specificUser[['Weeks', 'FVC', 'avg_of_week']], 'Weeks')\n    )\n\nplot_specific_patient(id_recover)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"For this patient (ID00076637202199015035026), the treatment is obvious working. The avg(FVC) of this patient (blue line) sees a surge as the week moves forward. (Becoming healthy?)","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"id_notRecover = 'ID00007637202177411956430'\nplot_specific_patient(id_notRecover)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"There are some other unfortunate patients (like ID00007637202177411956430) whose avg(FVC) kept falling, that's why the avg(FVC) for all patients (orange line) exhibits no clear trend of uprising.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"# What does the CT look like?\n\nThere are multiple CT images (.dcm) for a single patient.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_CT(id):\n    import pydicom\n    import os\n    \n    col = 5\n    row = 5\n    \n    fig = plt.figure(figsize=(12,12))\n    path = dir + 'train/'+id+'/'\n    imgs = os.listdir(path)\n    \n    for i in range(1, row*col+1):\n        filename = path+str(i)+'.dcm'\n        ds = pydicom.dcmread(filename)\n        fig.add_subplot(row, col, i)\n        plt.imshow(ds.pixel_array, cmap='gray')\n    plt.show()\n\n# For recovered patient.\nplot_CT(id_recover)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# For NOT recovered patient.\nplot_CT(id_notRecover)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"For the recovered patient, the CT shows the lungs are **turning dark** (I assume this is a good thing).\n\nFor the not recovered patient, the CT shows the lungs are **turning white** (I guess this means the situation is getting worse...)","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"# Build a baseline model.\nModified based on [Y.Nakama's notebook](https://www.kaggle.com/yasufuminakama/osic-lgb-baseline).","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import logging\nimport os\nfrom logging import getLogger, StreamHandler, FileHandler, Formatter\nfrom tqdm.notebook import tqdm\nfrom sklearn.model_selection import StratifiedKFold, GroupKFold, KFold\nfrom sklearn.metrics import mean_squared_error\nimport lightgbm as lgb","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"Utils declaration.\"\"\"\ndef get_logger(filename='log'):\n    logger = getLogger(__name__)\n    logger.setLevel(logging.INFO)\n    handler1 = StreamHandler()\n    handler1.setFormatter(Formatter('%(message)s'))\n    handler2 = FileHandler(filename=f\"{filename}.log\")\n    handler2.setFormatter(Formatter(\"%(message)s\"))\n    logger.addHandler(handler1)\n    logger.addHandler(handler2)\n    return logger\n\nlogger = get_logger()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"Config for training.\"\"\"\nOUTPUT_DIC = './'\nID = 'Patient_Week'\nTARGET = 'FVC'\nN_Fold = 4","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"Re-load data for a clean start.\"\"\"\ntrain = pd.read_csv('../input/osic-pulmonary-fibrosis-progression/train.csv')\ntrain['Patient_Week'] = train['Patient'].astype(str) + '_' + train['Weeks'].astype(str)\nprint(train.shape)\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"Construct train dataframe.\"\"\"\noutput = pd.DataFrame()\ngb = train.groupby('Patient')\ntk0 = tqdm(gb, total=len(gb))\nfor _, usr_df in tk0:\n    usr_output = pd.DataFrame()\n    for week, tmp in usr_df.groupby('Weeks'):\n        rename_cols = {'Weeks': 'base_Week', 'FVC': 'base_FVC', 'Percent': 'base_Percent', 'Age': 'base_Age'}\n        tmp = tmp.drop(columns='Patient_Week').rename(columns=rename_cols)\n        drop_cols = ['Age', 'Sex', 'SmokingStatus', 'Percent']\n        _usr_output = usr_df.drop(columns=drop_cols).rename(columns={'Weeks': 'predict_Week'}).merge(tmp, on='Patient')\n        _usr_output['Week_passed'] = _usr_output['predict_Week'] - _usr_output['base_Week']\n        usr_output = pd.concat([usr_output, _usr_output])\n    output = pd.concat([output, usr_output])\n    \ntrain = output[output['Week_passed']!=0].reset_index(drop=True)\nprint(train.shape)\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"Construct test dataframe.\"\"\"\ntest = pd.read_csv('../input/osic-pulmonary-fibrosis-progression/test.csv')\\\n        .rename(columns={'Weeks': 'base_Week', 'FVC': 'base_FVC', 'Percent': 'base_Percent', 'Age': 'base_Age'})\nsubmission = pd.read_csv('../input/osic-pulmonary-fibrosis-progression/sample_submission.csv')\nsubmission['Patient'] = submission['Patient_Week'].apply(lambda x: x.split('_')[0])\nsubmission['predict_Week'] = submission['Patient_Week'].apply(lambda x: x.split('_')[1]).astype(int)\ntest = submission.drop(columns=['FVC', 'Confidence']).merge(test, on='Patient')\ntest['Week_passed'] = test['predict_Week'] - test['base_Week']\nprint(test.shape)\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"Read in submission.csv.\"\"\"\nsubmission = pd.read_csv('../input/osic-pulmonary-fibrosis-progression/sample_submission.csv')\nprint(submission.shape)\nsubmission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"folds = train[['Patient_Week', 'Patient', 'FVC']].copy()\nN_FOLD = 4\nFold = GroupKFold(n_splits=N_FOLD)\ngroups = folds['Patient'].values\nfor n, (train_index, val_index) in enumerate(Fold.split(folds, folds[TARGET], groups)):\n    folds.loc[val_index, 'fold'] = int(n)\nfolds['fold'] = folds['fold'].astype(int)\nfolds.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"Model declaration.\"\"\"\ndef run_single_lightgbm(param, train_df, test_df, folds, features, target, fold_num=0, categorical=[]):\n    \n    trn_idx = folds[folds.fold != fold_num].index\n    val_idx = folds[folds.fold == fold_num].index\n    logger.info(f'len(trn_idx) : {len(trn_idx)}')\n    logger.info(f'len(val_idx) : {len(val_idx)}')\n    \n    if categorical == []:\n        trn_data = lgb.Dataset(train_df.iloc[trn_idx][features],\n                               label=target.iloc[trn_idx])\n        val_data = lgb.Dataset(train_df.iloc[val_idx][features],\n                               label=target.iloc[val_idx])\n    else:\n        trn_data = lgb.Dataset(train_df.iloc[trn_idx][features],\n                               label=target.iloc[trn_idx],\n                               categorical_feature=categorical)\n        val_data = lgb.Dataset(train_df.iloc[val_idx][features],\n                               label=target.iloc[val_idx],\n                               categorical_feature=categorical)\n\n    oof = np.zeros(len(train_df))\n    predictions = np.zeros(len(test_df))\n\n    num_round = 10000\n\n    clf = lgb.train(param,\n                    trn_data,\n                    num_round,\n                    valid_sets=[trn_data, val_data],\n                    verbose_eval=100,\n                    early_stopping_rounds=100)\n\n    oof[val_idx] = clf.predict(train_df.iloc[val_idx][features], num_iteration=clf.best_iteration)\n\n    fold_importance_df = pd.DataFrame()\n    fold_importance_df[\"Feature\"] = features\n    fold_importance_df[\"importance\"] = clf.feature_importance(importance_type='gain')\n    fold_importance_df[\"fold\"] = fold_num\n\n    predictions += clf.predict(test_df[features], num_iteration=clf.best_iteration)\n    \n    # RMSE\n    logger.info(\"fold{} RMSE score: {:<8.5f}\".format(fold_num, np.sqrt(mean_squared_error(target[val_idx], oof[val_idx]))))\n    \n    return oof, predictions, fold_importance_df\n\n\ndef run_kfold_lightgbm(param, train, test, folds, features, target, n_fold=5, categorical=[]):\n    \n    logger.info(f\"================================= {n_fold}fold lightgbm =================================\")\n    \n    oof = np.zeros(len(train))\n    predictions = np.zeros(len(test))\n    feature_importance_df = pd.DataFrame()\n\n    for fold_ in range(n_fold):\n        print(\"Fold {}\".format(fold_))\n        _oof, _predictions, fold_importance_df = run_single_lightgbm(param,\n                                                                     train,\n                                                                     test,\n                                                                     folds,\n                                                                     features,\n                                                                     target,\n                                                                     fold_num=fold_,\n                                                                     categorical=categorical)\n        feature_importance_df = pd.concat([feature_importance_df, fold_importance_df], axis=0)\n        oof += _oof\n        predictions += _predictions / n_fold\n\n    # RMSE\n    logger.info(\"CV RMSE score: {:<8.5f}\".format(np.sqrt(mean_squared_error(target, oof))))\n\n    logger.info(f\"=========================================================================================\")\n    \n    return feature_importance_df, predictions, oof\n\n    \ndef show_feature_importance(feature_importance_df, name):\n    cols = (feature_importance_df[[\"Feature\", \"importance\"]]\n            .groupby(\"Feature\")\n            .mean()\n            .sort_values(by=\"importance\", ascending=False)[:50].index)\n    best_features = feature_importance_df.loc[feature_importance_df.Feature.isin(cols)]\n\n    #plt.figure(figsize=(8, 16))\n    plt.figure(figsize=(6, 4))\n    sns.barplot(x=\"importance\", y=\"Feature\", data=best_features.sort_values(by=\"importance\", ascending=False))\n    plt.title('Features importance (averaged/folds)')\n    plt.tight_layout()\n    plt.savefig(OUTPUT_DICT+f'feature_importance_{name}.png')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import category_encoders as ce\n\ntarget = train['FVC']\ntest['FVC'] = np.nan\n\n# features\ncat_features = ['Sex', 'SmokingStatus']\nnum_features = [c for c in test.columns if (test.dtypes[c] != 'object') & (c not in cat_features)]\nfeatures = num_features + cat_features\ndrop_features = ['Patient_Week', 'FVC', 'predict_Week', 'base_Week']\nfeatures = [c for c in features if c not in drop_features]\n\nif cat_features:\n    ce_oe = ce.OrdinalEncoder(cols=cat_features, handle_unknown='impute')\n    ce_oe.fit(train)\n    train = ce_oe.transform(train)\n    test = ce_oe.transform(test)\n        \nlgb_param = {'objective': 'regression',\n             'metric': 'rmse',\n             'boosting_type': 'gbdt',\n             'learning_rate': 0.01,\n             'seed': 42,\n             'max_depth': -1,\n             'verbosity': -1,\n            }\n\nfeature_importance_df, predictions, oof = run_kfold_lightgbm(lgb_param, train, test, folds, features, target, \n                                                             n_fold=N_FOLD, categorical=cat_features)\n    \nshow_feature_importance(feature_importance_df, TARGET)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"Create confidence labels.\"\"\"\nimport math\ntrain['FVC_pred'] = oof\ntest['FVC_pred'] = predictions\n\n# baseline score\ntrain['Confidence'] = 100\ntrain['sigma_clipped'] = train['Confidence'].apply(lambda x: max(x, 70))\ntrain['diff'] = abs(train['FVC'] - train['FVC_pred'])\ntrain['delta'] = train['diff'].apply(lambda x: min(x, 1000))\ntrain['score'] = -math.sqrt(2)*train['delta']/train['sigma_clipped'] - np.log(math.sqrt(2)*train['sigma_clipped'])\nscore = train['score'].mean()\nprint(score)\ntrain.head(10)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import scipy as sp\nfrom functools import partial\n\ndef loss_func(weight, row):\n    confidence = weight\n    sigma_clipped = max(confidence, 70)\n    diff = abs(row['FVC'] - row['FVC_pred'])\n    delta = min(diff, 1000)\n    score = -math.sqrt(2)*delta/sigma_clipped - np.log(math.sqrt(2)*sigma_clipped)\n    return -score\n\nresults = []\ntk0 = tqdm(train.iterrows(), total=len(train))\nfor _, row in tk0:\n    loss_partial = partial(loss_func, row=row)\n    weight = [100]\n    #bounds = [(70, 100)]\n    #result = sp.optimize.minimize(loss_partial, weight, method='SLSQP', bounds=bounds)\n    result = sp.optimize.minimize(loss_partial, weight, method='SLSQP')\n    x = result['x']\n    results.append(x[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# optimized score\ntrain['Confidence'] = results\ntrain['sigma_clipped'] = train['Confidence'].apply(lambda x: max(x, 70))\ntrain['diff'] = abs(train['FVC'] - train['FVC_pred'])\ntrain['delta'] = train['diff'].apply(lambda x: min(x, 1000))\ntrain['score'] = -math.sqrt(2)*train['delta']/train['sigma_clipped'] - np.log(math.sqrt(2)*train['sigma_clipped'])\nscore = train['score'].mean()\nprint(score)\ntrain.head(10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TARGET = 'Confidence'\n\ntarget = train[TARGET]\ntest[TARGET] = np.nan\n\n# features\ncat_features = ['Sex', 'SmokingStatus']\nnum_features = [c for c in test.columns if (test.dtypes[c] != 'object') & (c not in cat_features)]\nfeatures = num_features + cat_features\ndrop_features = [ID, TARGET, 'predict_Week', 'base_Week', 'FVC', 'FVC_pred']\nfeatures = [c for c in features if c not in drop_features]\n\nlgb_param = {'objective': 'regression',\n             'metric': 'rmse',\n             'boosting_type': 'gbdt',\n             'learning_rate': 0.01,\n             'seed': SEED,\n             'max_depth': -1,\n             'verbosity': -1,\n            }\n\nfeature_importance_df, predictions, oof = run_kfold_lightgbm(lgb_param, train, test, folds, features, target, \n                                                             n_fold=N_FOLD, categorical=cat_features)\n    \nshow_feature_importance(feature_importance_df, TARGET)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['Confidence'] = oof\ntrain['sigma_clipped'] = train['Confidence'].apply(lambda x: max(x, 70))\ntrain['diff'] = abs(train['FVC'] - train['FVC_pred'])\ntrain['delta'] = train['diff'].apply(lambda x: min(x, 1000))\ntrain['score'] = -math.sqrt(2)*train['delta']/train['sigma_clipped'] - np.log(math.sqrt(2)*train['sigma_clipped'])\nscore = train['score'].mean()\nprint(score)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def lb_metric(train):\n    train['Confidence'] = oof\n    train['sigma_clipped'] = train['Confidence'].apply(lambda x: max(x, 70))\n    train['diff'] = abs(train['FVC'] - train['FVC_pred'])\n    train['delta'] = train['diff'].apply(lambda x: min(x, 1000))\n    train['score'] = -math.sqrt(2)*train['delta']/train['sigma_clipped'] - np.log(math.sqrt(2)*train['sigma_clipped'])\n    score = train['score'].mean()\n    return score","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"score = lb_metric(train)\nlogger.info(f'Local Score: {score}')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test['Confidence'] = predictions","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"Submission.\"\"\"\nsub = submission.drop(columns=['FVC', 'Confidence']).merge(test[['Patient_Week', 'FVC_pred', 'Confidence']], \n                                                           on='Patient_Week')\nsub.columns = submission.columns\nsub.to_csv('submission.csv', index=False)\nsub.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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":4}