{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-output":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\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\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.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"! du -sk /kaggle/input/prostate-cancer-grade-assessment/train_images\n\n# about 35GB","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport openslide\nimport matplotlib.pyplot as plt\n\nfrom tqdm import tqdm\nfrom sklearn.model_selection import train_test_split","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv('../input/prostate-cancer-grade-assessment/train.csv')\ntest_df = pd.read_csv('../input/prostate-cancer-grade-assessment/test.csv')\nprint(train_df.shape)\nprint(test_df.shape)\ntrain_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def preprocess_image(image_path, desired_size=224):\n    biopsy = openslide.OpenSlide(image_path)\n    im = np.array(biopsy.get_thumbnail(size=(desired_size,desired_size)))\n    im = np.resize(im,(desired_size,desired_size,3)) / 255\n    \n    return im","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img_1 = f\"../input/prostate-cancer-grade-assessment/train_images/{train_df['image_id'][25]}.tiff\"\na = openslide.OpenSlide(img_1)\na.get_thumbnail(size=(512,512))","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"%%time\n\n# get the number of training images from the target\\id dataset\nN = train_df.shape[0] # run on all data(50percent of data)\n#N = 1000 # run on sample\n# create an empty matrix for storing the images\nx_train = np.empty((N, 224, 224, 3), dtype=np.float32)\n# loop through the images from the images ids from the target\\id dataset\n# then grab the cooresponding image from disk, pre-process, and store in matrix in memory\nfor i, image_id in enumerate(tqdm(train_df['image_id'])):\n    x_train[i, :, :, :] = preprocess_image(\n        f'../input/prostate-cancer-grade-assessment/train_images/{image_id}.tiff'\n    )\n    # if sampling\n    if i >= N-1:\n        break","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if os.path.exists(f'../input/prostate-cancer-grade-assessment/test_images'):\n    # do the same thing as the last cell but on the test\\holdout set\n    N = test_df.shape[0]\n    x_test = np.empty((N, 224, 224, 3), dtype=np.float32)\n    for i, image_id in enumerate(tqdm(test_df['image_id'])):\n        x_test[i, :, :, :] = preprocess_image(\n            f'../input/prostate-cancer-grade-assessment/test_images/{image_id}.tiff'\n        )\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# pre-processing the target (i.e. one-hot encoding the target)\ny_train = pd.get_dummies(train_df['isup_grade']).values.astype(np.int32)[0:N]\n\n# Further target pre-processing\n\n# Instead of predicting a single label, we will change our target to be a multilabel problem; \n# i.e., if the target is a certain class, then it encompasses all the classes before it. \n# E.g. encoding a class 4 retinopathy would usually be [0, 0, 0, 1], \n# but in our case we will predict [1, 1, 1, 1]. For more details, \n# please check out Lex's kernel.\n\ny_train_multi = np.empty(y_train.shape, dtype=y_train.dtype)\ny_train_multi[:, 5] = y_train[:, 5]\n\nfor i in range(4, -1, -1):\n    y_train_multi[:, i] = np.logical_or(y_train[:, i], y_train_multi[:, i+1])\n\nprint(\"Original y_train:\", y_train.sum(axis=0))\nprint(\"Multilabel version:\", y_train_multi.sum(axis=0))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train, x_val, y_train, y_val = train_test_split(\n    x_train, y_train_multi, \n    test_size=0.30, \n    random_state=2020\n)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.save('X_train.npy', x_train)\nnp.save('y_train.npy', y_train)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"heelo\")","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}