|
a |
|
b/old/covidtesting_notebook.ipynb |
|
|
1 |
{ |
|
|
2 |
"nbformat": 4, |
|
|
3 |
"nbformat_minor": 0, |
|
|
4 |
"metadata": { |
|
|
5 |
"colab": { |
|
|
6 |
"name": "covidtesting notebook.ipynb", |
|
|
7 |
"provenance": [], |
|
|
8 |
"collapsed_sections": [], |
|
|
9 |
"toc_visible": true, |
|
|
10 |
"mount_file_id": "1LK7pcqyeGafFPUjp_1ld_vAp6ortxV9k", |
|
|
11 |
"authorship_tag": "ABX9TyNrMW/nJjb2vdqOvLx5Te+c", |
|
|
12 |
"include_colab_link": true |
|
|
13 |
}, |
|
|
14 |
"kernelspec": { |
|
|
15 |
"name": "python3", |
|
|
16 |
"display_name": "Python 3" |
|
|
17 |
}, |
|
|
18 |
"accelerator": "GPU" |
|
|
19 |
}, |
|
|
20 |
"cells": [ |
|
|
21 |
{ |
|
|
22 |
"cell_type": "markdown", |
|
|
23 |
"metadata": { |
|
|
24 |
"id": "view-in-github", |
|
|
25 |
"colab_type": "text" |
|
|
26 |
}, |
|
|
27 |
"source": [ |
|
|
28 |
"<a href=\"https://colab.research.google.com/github/ajsanjoaquin/COVID-19-Scanner/blob/master/covidtesting_notebook.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>" |
|
|
29 |
] |
|
|
30 |
}, |
|
|
31 |
{ |
|
|
32 |
"cell_type": "markdown", |
|
|
33 |
"metadata": { |
|
|
34 |
"id": "syNJC42pUjl9", |
|
|
35 |
"colab_type": "text" |
|
|
36 |
}, |
|
|
37 |
"source": [ |
|
|
38 |
"This model is provided as-is, and not meant to diagnose COVID-19. This model has no clinical approval, nor endorsements from any health organizations. At the moment, this model is a proof of concept. In no way is the author responsible for any damages resulting from using this model. License: MIT " |
|
|
39 |
] |
|
|
40 |
}, |
|
|
41 |
{ |
|
|
42 |
"cell_type": "markdown", |
|
|
43 |
"metadata": { |
|
|
44 |
"id": "fDTcYzSMDucn", |
|
|
45 |
"colab_type": "text" |
|
|
46 |
}, |
|
|
47 |
"source": [ |
|
|
48 |
"#PURE PYTORCH IMPLEMENTATION\n", |
|
|
49 |
"\n", |
|
|
50 |
"Model instantiation" |
|
|
51 |
] |
|
|
52 |
}, |
|
|
53 |
{ |
|
|
54 |
"cell_type": "code", |
|
|
55 |
"metadata": { |
|
|
56 |
"id": "kxVuivn32TCY", |
|
|
57 |
"colab_type": "code", |
|
|
58 |
"colab": {} |
|
|
59 |
}, |
|
|
60 |
"source": [ |
|
|
61 |
"#download model\n", |
|
|
62 |
"!wget -O corona_V2.pth https://www.dropbox.com/s/hovi7vc0edv8fxt/corona_V2.pth?dl=0" |
|
|
63 |
], |
|
|
64 |
"execution_count": 0, |
|
|
65 |
"outputs": [] |
|
|
66 |
}, |
|
|
67 |
{ |
|
|
68 |
"cell_type": "code", |
|
|
69 |
"metadata": { |
|
|
70 |
"id": "GZHgM1-Z8Oqb", |
|
|
71 |
"colab_type": "code", |
|
|
72 |
"colab": {} |
|
|
73 |
}, |
|
|
74 |
"source": [ |
|
|
75 |
"## The code below gives you Flatten and the double Adaptive Pooling (from fastai), plus\n", |
|
|
76 |
"## a viable head. You must fill the number of FC's nodes manually through the myhead function\n", |
|
|
77 |
"from torch import Tensor\n", |
|
|
78 |
"from torch import nn\n", |
|
|
79 |
"from torchvision import transforms\n", |
|
|
80 |
"from torch.autograd import Variable\n", |
|
|
81 |
"import PIL.Image\n", |
|
|
82 |
"import torch\n", |
|
|
83 |
"import torchvision\n", |
|
|
84 |
"import logging as log\n", |
|
|
85 |
"from typing import Optional # required for \"Optional[type]\"\n", |
|
|
86 |
"import os,re\n", |
|
|
87 |
"#if using CPU; else, comment out\n", |
|
|
88 |
"torch.cuda.device(\"cuda\")\n", |
|
|
89 |
"\n", |
|
|
90 |
"#put test images in test folder\n", |
|
|
91 |
"if not os.path.isdir('test'):\n", |
|
|
92 |
" os.makedirs('test')\n", |
|
|
93 |
"\n", |
|
|
94 |
"class Flatten(nn.Module):\n", |
|
|
95 |
" \"Flatten `x` to a single dimension, often used at the end of a model. `full` for rank-1 tensor\"\n", |
|
|
96 |
" def __init__(self, full:bool=False):\n", |
|
|
97 |
" super().__init__()\n", |
|
|
98 |
" self.full = full\n", |
|
|
99 |
"\n", |
|
|
100 |
" def forward(self, x):\n", |
|
|
101 |
" return x.view(-1) if self.full else x.view(x.size(0), -1)\n", |
|
|
102 |
"\n", |
|
|
103 |
"class AdaptiveConcatPool2d(nn.Module):\n", |
|
|
104 |
" \"Layer that concats `AdaptiveAvgPool2d` and `AdaptiveMaxPool2d`.\" # from pytorch\n", |
|
|
105 |
" def __init__(self, sz:Optional[int]=None): \n", |
|
|
106 |
" \"Output will be 2*sz or 2 if sz is None\"\n", |
|
|
107 |
" super().__init__()\n", |
|
|
108 |
" self.output_size = sz or 1\n", |
|
|
109 |
" self.ap = nn.AdaptiveAvgPool2d(self.output_size)\n", |
|
|
110 |
" self.mp = nn.AdaptiveMaxPool2d(self.output_size)\n", |
|
|
111 |
" def forward(self, x): return torch.cat([self.mp(x), self.ap(x)], 1)\n", |
|
|
112 |
" \n", |
|
|
113 |
"def myhead(nf, nc):\n", |
|
|
114 |
" return \\\n", |
|
|
115 |
" nn.Sequential( # the dropout is needed otherwise you cannot load the weights\n", |
|
|
116 |
" AdaptiveConcatPool2d(),\n", |
|
|
117 |
" Flatten(),\n", |
|
|
118 |
" nn.BatchNorm1d(nf,eps=1e-05,momentum=0.1,affine=True,track_running_stats=True),\n", |
|
|
119 |
" nn.Dropout(p=0.25,inplace=False),\n", |
|
|
120 |
" nn.Linear(nf, 512,bias=True),\n", |
|
|
121 |
" nn.ReLU(True),\n", |
|
|
122 |
" nn.BatchNorm1d(512,eps=1e-05,momentum=0.1,affine=True,track_running_stats=True),\n", |
|
|
123 |
" nn.Dropout(p=0.5,inplace=False),\n", |
|
|
124 |
" nn.Linear(512, nc,bias=True),\n", |
|
|
125 |
" )\n", |
|
|
126 |
"\n", |
|
|
127 |
"\n", |
|
|
128 |
"my_model=torchvision.models.resnet50() \n", |
|
|
129 |
"modules=list(my_model.children())\n", |
|
|
130 |
"modules.pop(-1) \n", |
|
|
131 |
"modules.pop(-1) \n", |
|
|
132 |
"temp=nn.Sequential(nn.Sequential(*modules))\n", |
|
|
133 |
"tempchildren=list(temp.children()) \n", |
|
|
134 |
"#append the special fastai head\n", |
|
|
135 |
"#Configured according to Model Architecture\n", |
|
|
136 |
"\n", |
|
|
137 |
"tempchildren.append(myhead(4096,2))\n", |
|
|
138 |
"model_r50=nn.Sequential(*tempchildren)\n", |
|
|
139 |
"\n", |
|
|
140 |
"#LOAD MODEL\n", |
|
|
141 |
"state = torch.load('corona_V2.pth')\n", |
|
|
142 |
"model_r50.load_state_dict(state['model'])\n", |
|
|
143 |
"\n", |
|
|
144 |
"\n", |
|
|
145 |
"#important to set to evaluation mode\n", |
|
|
146 |
"model_r50.eval()\n", |
|
|
147 |
"\n", |
|
|
148 |
"\n", |
|
|
149 |
"test_transforms = transforms.Compose([\n", |
|
|
150 |
" transforms.Resize(512),\n", |
|
|
151 |
" transforms.ToTensor(),\n", |
|
|
152 |
" transforms.Normalize(mean=[0.485, 0.456, 0.406],\n", |
|
|
153 |
" std=[0.229, 0.224, 0.225])\n", |
|
|
154 |
"])\n", |
|
|
155 |
"\n", |
|
|
156 |
"def predict_image(model,image):\n", |
|
|
157 |
" softmaxer = torch.nn.Softmax(dim=1)\n", |
|
|
158 |
" image_tensor = PIL.Image.open(image)\n", |
|
|
159 |
" image_tensor = image_tensor.convert('RGB')\n", |
|
|
160 |
" image_tensor = test_transforms(image_tensor).float()\n", |
|
|
161 |
" image_tensor = Variable(image_tensor,requires_grad=True)\n", |
|
|
162 |
" image_tensor=image_tensor.unsqueeze(0)\n", |
|
|
163 |
" image_tensor.cuda() #assuming using GPU w/ CUDA\n", |
|
|
164 |
"\n", |
|
|
165 |
" #convert evaluation to probabilities with softmax\n", |
|
|
166 |
" with torch.no_grad(): #turn off backpropagation\n", |
|
|
167 |
" processed=softmaxer(model(image_tensor))\n", |
|
|
168 |
" return processed[0] #return probabilities\n" |
|
|
169 |
], |
|
|
170 |
"execution_count": 0, |
|
|
171 |
"outputs": [] |
|
|
172 |
}, |
|
|
173 |
{ |
|
|
174 |
"cell_type": "markdown", |
|
|
175 |
"metadata": { |
|
|
176 |
"id": "bEe1PH4dwYix", |
|
|
177 |
"colab_type": "text" |
|
|
178 |
}, |
|
|
179 |
"source": [ |
|
|
180 |
"##Before running the code below, put the test images in the test folder that was just created." |
|
|
181 |
] |
|
|
182 |
}, |
|
|
183 |
{ |
|
|
184 |
"cell_type": "code", |
|
|
185 |
"metadata": { |
|
|
186 |
"id": "K8r9AL6X_F_F", |
|
|
187 |
"colab_type": "code", |
|
|
188 |
"colab": {} |
|
|
189 |
}, |
|
|
190 |
"source": [ |
|
|
191 |
"reg = re.compile('^.ipynb*')\n", |
|
|
192 |
"test_files=[file for file in sorted(os.listdir('test'))if not reg.match(file)]\n", |
|
|
193 |
"pytorch_results={filename:predict_image(model_r50,'test/'+filename) for filename in test_files}\n" |
|
|
194 |
], |
|
|
195 |
"execution_count": 0, |
|
|
196 |
"outputs": [] |
|
|
197 |
}, |
|
|
198 |
{ |
|
|
199 |
"cell_type": "markdown", |
|
|
200 |
"metadata": { |
|
|
201 |
"id": "FuRl6NDtw5-o", |
|
|
202 |
"colab_type": "text" |
|
|
203 |
}, |
|
|
204 |
"source": [ |
|
|
205 |
"###Results are saved in a .csv file in the colab workspace." |
|
|
206 |
] |
|
|
207 |
}, |
|
|
208 |
{ |
|
|
209 |
"cell_type": "code", |
|
|
210 |
"metadata": { |
|
|
211 |
"id": "t7YqjQQw_STi", |
|
|
212 |
"colab_type": "code", |
|
|
213 |
"colab": {} |
|
|
214 |
}, |
|
|
215 |
"source": [ |
|
|
216 |
"import pandas as pd\n", |
|
|
217 |
"final_df=pd.DataFrame.from_dict(pytorch_results,orient='index',columns=['corona','other']).rename_axis('filename').reset_index()\n", |
|
|
218 |
"final_df['corona']=final_df['corona'].apply(lambda x: x.item())\n", |
|
|
219 |
"final_df['other']=final_df['other'].apply(lambda x: x.item())\n", |
|
|
220 |
"final_df.loc[final_df['corona'] > final_df['other'], 'Predicted Label'] = \"Corona\"\n", |
|
|
221 |
"final_df.loc[final_df['corona'] < final_df['other'], 'Predicted Label'] = \"Other\"\n", |
|
|
222 |
"final_df.to_csv('results.csv', header=True)" |
|
|
223 |
], |
|
|
224 |
"execution_count": 0, |
|
|
225 |
"outputs": [] |
|
|
226 |
} |
|
|
227 |
] |
|
|
228 |
} |