{"cells":[{"metadata":{},"cell_type":"markdown","source":"# データの確認  \n途中くらいまでデータ読み込みのコードになります。  \nこのKernelでは、  \n・画像の確認  \n・マスク画像の確認  \n・悪性度の高い組織と正常組織の比較  \n・データの分布  \n  \nなどについて調べます。  ","execution_count":null},{"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\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":{"trusted":true},"cell_type":"code","source":"import os\n\n# There are two ways to load the data from the PANDA dataset:\n# Option 1: Load images using openslide\nimport openslide\n# Option 2: Load images using skimage (requires that tifffile is installed)\nimport skimage.io\nimport random\nimport seaborn as sns\nimport cv2\n\n# General packages\nimport pandas as pd\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport PIL\nfrom IPython.display import Image, display\n\n# Plotly for the interactive viewer (see last section)\nimport plotly.graph_objs as go","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# 大元のディレクトリ\nBASE_PATH = '../input/prostate-cancer-grade-assessment'\n\n# trainingとmask画像データのディレクトリ\ndata_dir = f'{BASE_PATH}/train_images'\nmask_dir = f'{BASE_PATH}/train_label_masks'\n\n\n# train.csv,その他testとsubmissionのディレクトリ\ntrain = pd.read_csv(f'{BASE_PATH}/train.csv').set_index('image_id')\ntest = pd.read_csv(f'{BASE_PATH}/test.csv')\nsubmission = pd.read_csv(f'{BASE_PATH}/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display(train.head())\nprint(\"Shape of training data :\", train.shape)\nprint(\"unique data provider :\", len(train.data_provider.unique()))\nprint(\"unique isup_grade(target) :\", len(train.isup_grade.unique()))\nprint(\"unique gleason_score :\", len(train.gleason_score.unique()))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#ISUPグレード5(悪性度の高い)の画像をピックアップ\nres_5 = train.query(\"isup_grade == 5 and data_provider == 'radboud'\")\nres_5.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#ISUPグレード0(正常組織)の画像をピックアップ\nres_0 = train.query(\"isup_grade == 0 and data_provider == 'radboud'\")\nres_0.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def display_image(image_id,x,y,level):\n    isup_grade = train.loc[image_id][\"isup_grade\"]\n    biopsy = openslide.OpenSlide(os.path.join(data_dir,image_id + '.tiff'))\n    biopsy_mask = openslide.OpenSlide(os.path.join(mask_dir,image_id + '_mask.tiff'))\n    print(\"画像情報\")\n    print(\"image_id\",image_id)\n    print(\"ISUPグレード：\",isup_grade)\n    print(\"画像サイズ:\",biopsy.dimensions)\n    zoom = [\"高い\",\"普通\",\"低い\"]\n    print(\"拡大率:\",zoom[level])\n    \n    region = biopsy.read_region((x,y), level, (512, 512))\n    region_mask = biopsy_mask.read_region((x,y), level, (512, 512))\n    \n    f,ax = plt.subplots(1,2,figsize=(16,18))\n    cmap = matplotlib.colors.ListedColormap(['black', 'gray', 'green', 'yellow', 'orange', 'red'])\n    ax[0].imshow(region)\n    ax[0].axis('off')\n    ax[0].set_title(f\"ID: {image_id}\\nISUP: {isup_grade}\")\n    ax[1].imshow(np.asarray(region_mask)[:,:,0], cmap=cmap, interpolation='nearest', vmin=0, vmax=5)\n    ax[1].axis('off')\n    ax[1].set_title(\"mask_image\")\n\n    plt.show() ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images = [\"007433133235efc27a39f11df6940829\", #grade0\n          \"01642d24ac5520681d6a20f6c42dc4fe\", #grade0\n          \"02577ddcd838f2559936453b6071dc17\", #grade0\n          \"00928370e2dfeb8a507667ef1d4efcbb\", #grade5\n          \"00c15b23b30a5ba061358d9641118904\", #grade5\n          \"00c52cb4db1c7a5811a8f070a910c038\"  #grade5\n         ]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# トレーニング画像の確認  \nまず最初に、トレーニング画像と、そのどの場所が悪性であるのかをマスク画像を用いて確認していきます。  \n正常組織と悪性度の高い組織について、様々な拡大率で2例ずつ見てみます。  \n","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"# マスク画像のグレードについて  \n各マスク画像の色は、次のグレードを表しています。  \n## 黒：背景。組織ではない部分  \n## 灰色：結合組織や非上皮組織(癌には関係ない組織のことです)  \n## 緑：正常な上皮組織  \n## 黄色：がん組織(グリソン分類３)  \n## オレンジ：がん組織(グリソン分類４)  \n## 赤：がん組織(グリソン分類５)  ","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"まず、正常な組織(ISUPグレード0)の画像について3つの倍率で見てみます  \n画像から、以下のことが分かります。  \n・多くの場所は診断に関係ない非上皮性組織である。  \n・上皮性組織には細胞核が集中している。  \n・上皮性組織は文字通り組織の表面に位置することが分かる。  \n・核の配置が規則的である。  ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#一番遠い視野での画像\ndisplay_image(\"007433133235efc27a39f11df6940829\",2000,8000,2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#同画像を拡大したもの\ndisplay_image(\"007433133235efc27a39f11df6940829\",4000,11000,1)\n#更に上皮組織を拡大したもの\ndisplay_image(\"007433133235efc27a39f11df6940829\",4300,12500,0)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"次に、悪性度の高い組織画像について、同じく3段階の倍率で見てみます。  \n以下のことが分かります。  \n・マスク画像において、悪性度の高い赤色を示す割合が非常に多い  \n・組織表面でなくとも、細胞核の密集率が非常に高い  \n・拡大率中の画像を正常細胞と比較した時に、とにかく細胞核の数が多いのが目立つ  \n・核の形、大きさがまばらである  \n・正常細胞に対して、核の配置が規則的でない  ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#遠くから\ndisplay_image(\"00928370e2dfeb8a507667ef1d4efcbb\",2000,8000,2)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#赤いマスクがされている部分について拡大\ndisplay_image(\"00928370e2dfeb8a507667ef1d4efcbb\",5000,8000,1)\n#更に拡大\ndisplay_image(\"00928370e2dfeb8a507667ef1d4efcbb\",6200,8700,0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#正常細胞例2\ndisplay_image(\"01642d24ac5520681d6a20f6c42dc4fe\",5000,5000,2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#緑マスク部にめがけて拡大。\ndisplay_image(\"01642d24ac5520681d6a20f6c42dc4fe\",5000,7000,1)\n#更に拡大\ndisplay_image(\"01642d24ac5520681d6a20f6c42dc4fe\",6000,7300,0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#ISUPグレード5(悪性度高)細胞例2\ndisplay_image(\"00928370e2dfeb8a507667ef1d4efcbb\",2500,8000,2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#悪性部に拡大\ndisplay_image(\"00928370e2dfeb8a507667ef1d4efcbb\",4500,8500,1)\n#さらに拡大\ndisplay_image(\"00928370e2dfeb8a507667ef1d4efcbb\",5500,8700,0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#また、同画像のオレンジ(グリソンスコア4)の部分についても見てみる。\ndisplay_image(\"00928370e2dfeb8a507667ef1d4efcbb\",4500,12000,1)\n#さらに拡大\ndisplay_image(\"00928370e2dfeb8a507667ef1d4efcbb\",5200,12800,0)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# データの分布  \n画像の特徴を一通り見終わったので、次は主要なデータ分布を調べます。  \nまずは研究所ごとのデータの提供割合について見てみます。","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#データを提供してる研究所は以下の2つ。\ntrain[\"data_provider\"].unique()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_ct(data):\n    left = [i for i in range(len(data))]\n    height = [i[1] for i in data]\n    labels = [i[0] for i in data]\n    plt.bar(left, height, width=0.5,linewidth=2, tick_label=labels)\n    plt.title(\"data_provider\")\n    plt.ylabel(\"count\")\n    plt.xlabel(\"provider\")\n    plt.show()\n    \n\ndata = [\n    ['karolinska',(train[\"data_provider\"] =='karolinska').sum()],\n    ['radboud',(train[\"data_provider\"] =='radboud').sum()]\n]\n\n\nplot_ct(data)\nprint(\"施設ごとのデータ提供割合：\")\nfor i,j in data:\n    print(i,\":\",round(j/len(train)*100,2),\"%\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"2施設のデータに偏りは無いことが分かりました。  \n次に、ISUPグレードの分布を確認します。","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_isup(data):\n    left = [i for i in range(len(data))]\n    height = [i[1] for i in data]\n    labels = [i[0] for i in data]\n    plt.bar(left, height, width=0.5,linewidth=2, tick_label=labels)\n    plt.title(\"isup_grade\")\n    plt.ylabel(\"count\")\n    plt.xlabel(\"isup_grade\")\n    plt.show()\n    \n\ndata = [[i,(train[\"isup_grade\"] == i).sum()] for i in range(6)]\n\nplot_isup(data)\nprint(\"それぞれのISUPグレードの割合：\")\nfor i,j in data:\n    print(\"グレード\",i,\":\",round(j/len(train)*100,2),\"%\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"グレード0(陰性)とグレード1(悪性度の低いグレード)の割合が高く、他のデータの割合がほとんど同じであることが分かります。  \n特にグレード3~5は12%に統一されており、わざとこのように仕組んでいるのかな？と感じます。  \n\nテストケースでこのような分布になっているとは限らないので、注意が必要です。  \n  \n更に、施設ごとのISUPグレードも見ておきましょう。  ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"print('karolinskaのみ')\ndata = [[i,((train[\"isup_grade\"] == i) & (train[\"data_provider\"] =='karolinska')).sum()] for i in range(6)]\n\nplot_isup(data)\nprint(\"それぞれのISUPグレードの割合：\")\nfor i,j in data:\n    print(\"グレード\",i,\":\",round(j/len(train)*100,2),\"%\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('radboudのみ')\ndata = [[i,((train[\"isup_grade\"] == i) & (train[\"data_provider\"] =='radboud')).sum()] for i in range(6)]\n\nplot_isup(data)\nprint(\"それぞれのISUPグレードの割合：\")\nfor i,j in data:\n    print(\"グレード\",i,\":\",round(j/len(train)*100,2),\"%\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"施設ごとにかなりバラツキがあるのが分かりました。  \n特徴としては、  \nkarolinskaはグレード0,1の割合が比較的高い。  \nradboudは全体的に均一な分布となっている。  \n\nテストケースにおいて、data_prividerは事前に特徴量として渡されるデータです。  \nこのようなデータの偏りがあることを考慮すると、施設ごとにモデルを作成する、という方法が有効な手段になりそうです。  \n\n最後に、ISUPグレードではなく、グリソン分類についても分布を見ておきたいと思います。  \nグリソン分類は、細胞上皮においてその面積が占める割合が大きいものから2つ撮ってきて、3+3～5+5までの分類で表します。(陰性の場合は0+0またはnegative)  \n更にその和からISUPグレードを求める、というふうになっています。(コンペトップにISUP算出法の図があります)  \nまずはデータ全体での分布を見てみましょう。  ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train[\"gleason_score\"].unique()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_gleason(data):\n    left = [i for i in range(len(data))]\n    height = [i[1] for i in data]\n    labels = [\"nega\" if i[0] == \"negative\" else i[0] for i in data]\n    plt.bar(left, height, width=0.5,linewidth=2, tick_label=labels)\n    plt.title(\"gleason_score\")\n    plt.ylabel(\"count\")\n    plt.xlabel(\"gleason_score\")\n    plt.show()\n    \n\ndata = [[i,(train[\"gleason_score\"] == i).sum()] for i in train[\"gleason_score\"].unique()]\nplot_gleason(data)\nprint(\"それぞれのグリソン分類の割合：\")\nfor i,j in data:\n    print(i,\":\",round(j/len(train)*100,2),\"%\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"negativeと0+0は同義ですが、どうやら研究所によって表記が異なるようです。  \n0+0：karolinskaでの陰性表記  \nnegative：radboudでの陰性表記  ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in [\"karolinska\",\"radboud\"]:\n    res = train[train[\"data_provider\"] == i]\n    print(\"0+0 in \",i,\":\",any(\"0+0\" == i for i in res[\"gleason_score\"]))\n    print(\"negative in \",i,\":\",any(\"negative\" == i for i in res[\"gleason_score\"]))\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"施設ごとのデータ分布も確認します。","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"print('karolinskaのみ')\n\ndata = [[i,((train[\"gleason_score\"] == i) & (train[\"data_provider\"] =='karolinska') ).sum()] for i in train[\"gleason_score\"].unique()]\nplot_gleason(data)\nprint(\"それぞれのグリソン分類の割合：\")\nfor i,j in data:\n    print(i,\":\",round(j/len(train)*100,2),\"%\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('radboudのみ')\n\ndata = [[i,((train[\"gleason_score\"] == i) & (train[\"data_provider\"] =='radboud') ).sum()] for i in train[\"gleason_score\"].unique()]\nplot_gleason(data)\nprint(\"それぞれのグリソン分類の割合：\")\nfor i,j in data:\n    print(i,\":\",round(j/len(train)*100,2),\"%\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"この2つのデータの比較からは、\nkarolinskaでは5+から始まる症例はほとんど扱っていない   \nそのため、karolinskaにおけるISUPグレード5のほとんどは4+5のグリソン分類によるものである。  \nkarolinskaでは陽性の場合3+3か3+4が大半を占めている。  \nradboudではデータの分布が比較的均一であるが、5+から始まるデータはやはり少ない。  \n\nといったことが読み取れます。","execution_count":null}],"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}