{"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\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 read-only \"../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\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import scipy as sp\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nfrom typing import Dict\nimport pydicom\nimport glob, os, tqdm\nimport warnings\nfrom sklearn.metrics import mean_squared_error\n\nwarnings.filterwarnings('ignore')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"os.getcwd()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"meta = pd.read_csv('/kaggle/input/metadatapf/meta_data.csv') #meta data from CT images\ntrain = pd.read_csv('../input/osic-pulmonary-fibrosis-progression/train.csv')\ntest = pd.read_csv('../input/osic-pulmonary-fibrosis-progression/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#creating single entry of features from CT data across all dicoms from single session\ndf_meta = meta.groupby(['Patient']).agg(\n    {\n     'img_mean': ['mean', 'std'],\n     'img_std':['mean', 'std']\n    }\n)\ndf_meta.columns = df_meta.columns.map('_'.join)\ndf_meta = df_meta.reset_index()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#3 patients in the training set did not have DCM images, thus they are removed and only those on whom we have CT are kept (should consider a scenario when dicom data is not available in test?)\ndf_patient = pd.merge(left=df_meta, right=train, how='left', on='Patient')\n#df_patient.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Doing one_hot_encoding on cateogrical variables, Sex and Smoking Status\n\nsex_dummies = pd.get_dummies(df_patient.Sex)\nsmoking_dummies = pd.get_dummies(df_patient.SmokingStatus)\ndf = pd.concat([df_patient, sex_dummies, smoking_dummies], axis=1)\ndf.drop(columns=['Sex', 'SmokingStatus'], inplace=True)\n#df.head() #df now has training data of all patients on whom we also have dicoms available","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Since the original training data contained patients which are also in the test set, we decided to remove those patients from training set\ntrain_patient_ids = set(df['Patient'].unique())\ntest_patient_ids = set(test['Patient'].unique())\n\ntrain_no_test_ids = train_patient_ids.intersection(test_patient_ids) #just identifying those patients from test set which are in training set as well\n\nif train_no_test_ids: #removing test data if there is some overlap, else not\n    for id in train_no_test_ids:\n        df = df.loc[df.Patient != id]\n        \n#df_test = df.copy()\n#df_test_empty = pd.DataFrame(columns = df.columns)\n\n# final train dataset \"df\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = df.drop(columns=['FVC', 'Patient', 'Percent']) #dropping patient ID and FVC (as that is to be predicted) and Percentage (as that is dependent on FVC so can't use)\ny = df['FVC'] # separating out the predicted feature","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#creating a very simple linear regression model with all the features and all data from all test patients\nlm = LinearRegression()\nmodel = lm.fit(X,y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.coef_","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def extract_dicom_meta_data(filename: str) -> Dict:\n    # Load image\n    \n    image_data = pydicom.read_file(filename)\n    img=np.array(image_data.pixel_array).flatten()\n    row = {\n        'Patient': image_data.PatientID,\n        'body_part_examined': image_data.BodyPartExamined,\n        'image_position_patient': image_data.ImagePositionPatient,\n        'image_orientation_patient': image_data.ImageOrientationPatient,\n        'photometric_interpretation': image_data.PhotometricInterpretation,\n        'rows': image_data.Rows,\n        'columns': image_data.Columns,\n        'pixel_spacing': image_data.PixelSpacing,\n        'window_center': image_data.WindowCenter,\n        'window_width': image_data.WindowWidth,\n        'modality': image_data.Modality,\n        'StudyInstanceUID': image_data.StudyInstanceUID,\n        'SeriesInstanceUID': image_data.StudyInstanceUID,\n        'StudyID': image_data.StudyInstanceUID, \n        'SamplesPerPixel': image_data.SamplesPerPixel,\n        'BitsAllocated': image_data.BitsAllocated,\n        'BitsStored': image_data.BitsStored,\n        'HighBit': image_data.HighBit,\n        'PixelRepresentation': image_data.PixelRepresentation,\n        'RescaleIntercept': image_data.RescaleIntercept,\n        'RescaleSlope': image_data.RescaleSlope,\n        'img_min': np.min(img),\n        'img_max': np.max(img),\n        'img_mean': np.mean(img),\n        'img_std': np.std(img)}\n\n    return row","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#extracting image data from test CTs (this step can take some time)\ntest_image_path = '/kaggle/input/osic-pulmonary-fibrosis-progression/test'\ntest_image_files = glob.glob(os.path.join(test_image_path, '*', '*.dcm'))\n\nmeta_data_test = []\nfor filename in tqdm.tqdm(test_image_files):\n    try:\n        meta_data_test.append(extract_dicom_meta_data(filename))\n    except Exception as e:\n        continue","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"meta_data_test = pd.DataFrame.from_dict(meta_data_test) #make meta data from test as a pd dataframe\nmeta_data_test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"meta_data_test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#creating single entry of features from CT data of test patients across all dicoms from single session\ndf_meta_test = meta_data_test.groupby(['Patient']).agg(\n    {\n     'img_mean': ['mean', 'std'],\n     'img_std':['mean', 'std']\n    }\n)\ndf_meta_test.columns = df_meta_test.columns.map('_'.join)\ndf_meta_test = df_meta_test.reset_index()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_patient_test = pd.merge(left=df_meta_test, right=test, how='left', on='Patient')\ndf_patient_test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#we first need to make sure that all levels of all categories are covered in test data\ndf_patient_test['Sex'] = pd.Categorical(df_patient_test['Sex'], categories=['Male', 'Female'])\ndf_patient_test['SmokingStatus'] = pd.Categorical(df_patient_test['SmokingStatus'], categories=['Ex-smoker', 'Never smoked', 'Currently smokes'])\n\nsex_dummies = pd.get_dummies(df_patient_test.Sex)\nsmoking_dummies = pd.get_dummies(df_patient_test.SmokingStatus)\ndf_test = pd.concat([df_patient_test, sex_dummies, smoking_dummies], axis=1)\ndf_test.drop(columns=['Sex', 'SmokingStatus'], inplace=True)\ndf_test.head() #df_test now has testing data of all patients in test folder (what if)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test_final = df_test.drop(columns=['FVC', 'Patient', 'Percent'])\ny_test = df_test['FVC']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test_final","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred = lm.predict(df_test_final)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_test","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"rmse_pred = mean_squared_error(y_test, y_pred)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"rmse_pred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def metric(actual_fvc, predicted_fvc, confidence, return_values = False):\n    \"\"\"\n        Calculates the modified Laplace Log Likelihood score for this competition.\n        Credits: https://www.kaggle.com/rohanrao/osic-understanding-laplace-log-likelihood\n    \"\"\"\n    sd_clipped = np.maximum(confidence, 70)\n    delta = np.minimum(np.abs(actual_fvc - predicted_fvc), 1000)\n    metric = - np.sqrt(2) * delta / sd_clipped - np.log(np.sqrt(2) * sd_clipped)\n\n    if return_values:\n        return metric\n    else:\n        return np.mean(metric)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"score = metric(y_test, y_pred, np.std(y_pred))\n\nprint('OOF log-Laplace likelihood score:', score)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#still to work on it.....\n'''\notest = pd.read_csv('../input/osic-pulmonary-fibrosis-progression/test.csv')\nfor i in range(len(otest)):\n    subm.loc[subm['Patient_Week']==otest.Patient[i]+'_'+str(otest.Weeks[i]), 'FVC'] = otest.FVC[i] #all they are doing is still using the test data while training, and also predicting on it just that replacing their prediction with the real value in test data\n    subm.loc[subm['Patient_Week']==otest.Patient[i]+'_'+str(otest.Weeks[i]), 'Confidence'] = 0.1\n\nsubm[[\"Patient_Week\",\"FVC\",\"Confidence\"]].to_csv(\"submission.csv\", index=False)\n'''","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test_sub = pd.DataFrame(columns=['Patient', 'Weeks'])\nfor id in df_test.Patient:\n    data = {'Patient': [id for x in range(-12, 134)],\n                  'Weeks': [x for x in range(-12, 134)]\n                  }\n    df_inter = pd.DataFrame(data, columns=['Patient', 'Weeks'])\n    df_test_sub = pd.concat([df_test_sub, df_inter])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test_sub","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test_sub_final = pd.merge(left=df_test, right=df_test_sub, on='Patient', how='right')\ndf_test_sub_final.drop(columns=['Weeks_x'], inplace=True)\ndf_test_sub_final.rename(columns={'Weeks_y': 'Weeks'}, inplace=True)\ndf_test_sub_final","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test_rm = df_test_sub_final.drop(columns=['Patient', 'FVC', 'Percent'])\ndf_test_sub_final['FVC_pred'] = lm.predict(df_test_rm)\ndf_test_sub_final","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"final_submission = df_test_sub_final[['Patient', 'Weeks']]\nfinal_submission['Patient_Week'] = final_submission['Patient'] + \"_\" + final_submission['Weeks'].astype(str)\nfinal_submission['FVC'] = df_test_sub_final[['FVC_pred']]\nfinal_submission = final_submission.drop(columns=['Patient', 'Weeks'])\nfinal_submission['Confidence'] = 100\nfinal_submission","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"final_submission.to_csv(\"submission.csv\", index=False)","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}