-
Notifications
You must be signed in to change notification settings - Fork 34
/
breastcancer_detection.py
475 lines (351 loc) · 18.6 KB
/
breastcancer_detection.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
# -*- coding: utf-8 -*-
"""Breastcancer_detection.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1b07qsM3ojGzP5buT9-EKXmr8SVUe2B6g
# Creating an AI app for Breast Cancer Detection
# Importing the libraries
First up is importing the packages you'll need. It's good practice to keep all the imports at the beginning of your code. As you work through this notebook and find you need to import a package, make sure to add the import up here. The notebook was made on Google Colab.
"""
# We need pillow version of 5.3.0
# We will uninstall the older version first
!pip uninstall -y Pillow
# Install the new one
!pip install Pillow==5.3.0
# Let's verify the version
# This should print 5.3.0. If it doesn't, then restart your runtime:
# Menu > Runtime > Restart Runtime
!pip install image
!pip3 install http://download.pytorch.org/whl/cu80/torch-0.4.0-cp36-cp36m-linux_x86_64.whl
!pip3 install torchvision
import PIL
print(PIL.PILLOW_VERSION)
# We will verify that GPU is enabled for this notebook
# Following should print: CUDA is available! Training on GPU ...
# if it prints otherwise, then you need to enable GPU:
# From Menu > Runtime > Change Runtime Type > Hardware Accelerator > GPU
# %matplotlib inline
# %config InlineBackend.figure_format = 'retina'
import torch
import numpy as np
import matplotlib.pyplot as plt
import torch
import time
import numpy as np
from torch import nn, optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
import torchvision
from collections import OrderedDict
from torch.autograd import Variable
from PIL import Image
from torch.optim import lr_scheduler
import copy
import json
import os
from os.path import exists
# check if CUDA is available
train_on_gpu = torch.cuda.is_available()
if not train_on_gpu:
print('CUDA is not available. Training on CPU ...')
else:
print('CUDA is available! Training on GPU ...')
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
"""# Load the data
Here you'll use 'torchvision' to load the data ([documentation](http://pytorch.org/docs/0.3.0/torchvision/index.html)). The dataset is split into two parts, training and validation. For the training, you'll want to apply transformations such as random scaling, cropping, and flipping. This will help the network generalize leading to better performance. If you use a pre-trained network, you'll also need to make sure the input data is resized to 224x224 pixels as required by the networks.
The validation set is used to measure the model's performance on data it hasn't seen yet. For this you don't want any scaling or rotation transformations, but you'll need to resize then crop the images to the appropriate size.
The pre-trained networks available from 'torchvision' were trained on the ImageNet dataset where each color channel was normalized separately. For both sets you'll need to normalize the means and standard deviations of the images to what the network expects. For the means, it's ' [0.485, 0.456, 0.406]' and for the standard deviations ''[0.229, 0.224, 0.225]' , calculated from the ImageNet images. These values will shift each color channel to be centered at 0 and range from -1 to 1.
"""
# I made a smaller version of the dataset, original one has classes and subclasses.
# I just wanted to keep 2 classes: Benign and Malignant.
#Download and unzip de folder
!gdown https://drive.google.com/uc?id=1r6YNGwijUHawsRHKy8qQk12FW-VQXw4p
!unzip -qq b_cancer_data2.zip
#Organizing the dataset
data_dir = '/b_cancer_data2'
train_dir = data_dir + '/train'
valid_dir = data_dir + '/valid'
nThreads = 4
batch_size = 32
use_gpu = torch.cuda.is_available()
"""# Label mapping
You'll also need to load in a mapping from category label to category name. You can find this in the file `cate.json`. It's a JSON object which you can read in with the [`json` module](https://docs.python.org/2/library/json.html). This will give you a dictionary mapping the integer encoded categories to the actual names.
"""
import json
with open('cate.json', 'r') as f:
cat_to_name = json.load(f)
# Define your transforms for the training and validation sets
# Data augmentation and normalization for training
data_transforms = {
'train': transforms.Compose([
transforms.RandomRotation(30),
transforms.RandomResizedCrop(224),
#transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'valid': transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
# Load the datasets with ImageFolder
data_dir = 'b_cancer_data2'
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),
data_transforms[x])
for x in ['train', 'valid']}
# Using the image datasets and the trainforms, define the dataloaders
dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch_size,
shuffle=True, num_workers=4)
for x in ['train', 'valid']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'valid']}
class_names = image_datasets['train'].classes
"""# Building and training the classifier
Now that the data is ready, it's time to build and train the classifier. As usual, you should use one of the pretrained models from `torchvision.models` to get the image features. Build and train a new feed-forward classifier using those features. Resnet-152 pretrained model is used for this image classifier.
# Picking a pretrained model: Resnet-152
We decided to used the pre-trained **Resnet-152** to extract features for classification.
**Resnet-152 **is a type of specialized neural network that helps to handle more sophisticated deep learning tasks and models. It has received quite a bit of attention at recent IT conventions, and is being considered for helping with the training of deep networks.
Resnet introduces a structure called residual learning unit to alleviate the degradation of deep neural networks. This unit's structure is a feedforward network with a shortcut connection which adds new inputs into the network and generates new outputs. The main merit of this unit is that it produces better classification accuracy without increasing the complexity of the model
"""
# Build and train your network
# 1. Load resnet-152 pre-trained network
model = models.resnet152(pretrained=True)
# Freeze parameters so we don't backprop through them
for param in model.parameters():
param.requires_grad = False
#Let's check the model architecture:
print(model)
# 2. Define a new, untrained feed-forward network as a classifier, using ReLU activations
# Our input_size matches the in_features of pretrained model
from collections import OrderedDict
# Creating the classifier ordered dictionary first
classifier = nn.Sequential(OrderedDict([
('fc1', nn.Linear(2048, 512)),
('relu', nn.ReLU()),
('dropout1', nn.Dropout(p=0.5)),
('fc2', nn.Linear(512, 2)),
('output', nn.LogSoftmax(dim=1))
]))
# Replacing the pretrained model classifier with our classifier
model.fc = classifier
#Function to train the model
def train_model(model, criterion, optimizer, scheduler, num_epochs=10):
since = time.time()
best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0
for epoch in range(1, num_epochs+1):
print('Epoch {}/{}'.format(epoch, num_epochs))
print('-' * 10)
# Each epoch has a training and validation phase
for phase in ['train', 'valid']:
if phase == 'train':
scheduler.step()
model.train() # Set model to training mode
else:
model.eval() # Set model to evaluate mode
running_loss = 0.0
running_corrects = 0
# Iterate over data.
for inputs, labels in dataloaders[phase]:
inputs, labels = inputs.to(device), labels.to(device)
# zero the parameter gradients
optimizer.zero_grad()
# forward
# track history if only in train
with torch.set_grad_enabled(phase == 'train'):
outputs = model(inputs)
loss = criterion(outputs, labels)
_, preds = torch.max(outputs, 1)
# backward + optimize only if in training phase
if phase == 'train':
loss.backward()
optimizer.step()
# statistics
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
epoch_loss = running_loss / dataset_sizes[phase]
epoch_acc = running_corrects.double() / dataset_sizes[phase]
print('{} Loss: {:.4f} Acc: {:.4f}'.format(
phase, epoch_loss, epoch_acc))
# deep copy the model
if phase == 'valid' and epoch_acc > best_acc:
best_acc = epoch_acc
best_model_wts = copy.deepcopy(model.state_dict())
print()
time_elapsed = time.time() - since
print('Training complete in {:.0f}m {:.0f}s'.format(
time_elapsed // 60, time_elapsed % 60))
print('Best valid accuracy: {:4f}'.format(best_acc))
# load best model weights
model.load_state_dict(best_model_wts)
return model
# Train a model with a pre-trained network
num_epochs = 10
if use_gpu:
print ("Using GPU: "+ str(use_gpu))
model = model.cuda()
# NLLLoss because our output is LogSoftmax
criterion = nn.NLLLoss()
# Adam optimizer with a learning rate
#optimizer = optim.Adam(model.fc.parameters(), lr=0.005)
optimizer = optim.SGD(model.fc.parameters(), lr = .0006, momentum=0.9)
# Decay LR by a factor of 0.1 every 5 epochs
exp_lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.1)
model_ft = train_model(model, criterion, optimizer, exp_lr_scheduler, num_epochs=10)
# Do validation on the test set
def test(model, dataloaders, device):
model.eval()
accuracy = 0
model.to(device)
for images, labels in dataloaders['valid']:
images = Variable(images)
labels = Variable(labels)
images, labels = images.to(device), labels.to(device)
output = model.forward(images)
ps = torch.exp(output)
equality = (labels.data == ps.max(1)[1])
accuracy += equality.type_as(torch.FloatTensor()).mean()
print("Testing Accuracy: {:.3f}".format(accuracy/len(dataloaders['valid'])))
test(model, dataloaders, device)
"""# Save the checkpoint
Now that the network is trained, we will save the model so we can load it later for making predictions. We will save the mapping of classes to indices which we get from one of the image datasets: `image_datasets['train'].class_to_idx`. We will attach this to the model as an attribute which makes inference easier later on.
```model.class_to_idx = image_datasets['train'].class_to_idx```
Remember that we'll want to completely rebuild the model later so we can use it for inference. Make sure to include any information you need in the checkpoint. If you want to load the model and keep training, you'll want to save the number of epochs as well as the optimizer state, `optimizer.state_dict`. You'll likely want to use this trained model in the next part of the project, so best to save it now.
"""
# Save the checkpoint
model.class_to_idx = dataloaders['train'].dataset.class_to_idx
model.epochs = num_epochs
checkpoint = {'input_size': [3, 224, 224],
'batch_size': dataloaders['train'].batch_size,
'output_size': 2,
'state_dict': model.state_dict(),
'data_transforms': data_transforms,
'optimizer_dict':optimizer.state_dict(),
'class_to_idx': model.class_to_idx,
'epoch': model.epochs}
torch.save(checkpoint, '8960_checkpoint.pth')
"""# Loading the checkpoint
At this point it's good to write a function that can load a checkpoint and rebuild the model. That way you can come back to this project and keep working on it without having to retrain the network.
"""
#Load the trained model from here:
!gdown https://drive.google.com/uc?id=16RqsH1oCROSJiCR0f2gWCs4Xaz3JRTw9
#https://drive.google.com/open?id=16RqsH1oCROSJiCR0f2gWCs4Xaz3JRTw9
# Write a function that loads a checkpoint and rebuilds the model
def load_checkpoint(filepath):
checkpoint = torch.load(filepath)
model = models.resnet152()
# Our input_size matches the in_features of pretrained model
input_size = 2048
output_size = 2
classifier = nn.Sequential(OrderedDict([
('fc1', nn.Linear(2048, 512)),
('relu', nn.ReLU()),
#('dropout1', nn.Dropout(p=0.2)),
('fc2', nn.Linear(512, 2)),
('output', nn.LogSoftmax(dim=1))
]))
# Replacing the pretrained model classifier with our classifier
model.fc = classifier
model.load_state_dict(checkpoint['state_dict'])
return model, checkpoint['class_to_idx']
# Get index to class mapping
loaded_model, class_to_idx = load_checkpoint('8960_checkpoint.pth')
idx_to_class = { v : k for k,v in class_to_idx.items()}
"""# Inference for classification
Now you'll write a function to use a trained network for inference. That is, you'll pass an image into the network and predict the class. Write a function called `predict` that takes an image and a model, then returns the top $K$ most likely classes along with the probabilities. It should look like
"""
def process_image(image):
''' Scales, crops, and normalizes a PIL image for a PyTorch model,
returns an Numpy array
'''
# Process a PIL image for use in a PyTorch model
size = 256, 256
image.thumbnail(size, Image.ANTIALIAS)
image = image.crop((128 - 112, 128 - 112, 128 + 112, 128 + 112))
npImage = np.array(image)
npImage = npImage/255.
imgA = npImage[:,:,0]
imgB = npImage[:,:,1]
imgC = npImage[:,:,2]
imgA = (imgA - 0.485)/(0.229)
imgB = (imgB - 0.456)/(0.224)
imgC = (imgC - 0.406)/(0.225)
npImage[:,:,0] = imgA
npImage[:,:,1] = imgB
npImage[:,:,2] = imgC
npImage = np.transpose(npImage, (2,0,1))
return npImage
def imshow(image, ax=None, title=None):
"""Imshow for Tensor."""
if ax is None:
fig, ax = plt.subplots()
# PyTorch tensors assume the color channel is the first dimension
# but matplotlib assumes is the third dimension
image = image.numpy().transpose((1, 2, 0))
# Undo preprocessing
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
image = std * image + mean
# Image needs to be clipped between 0 and 1 or it looks like noise when displayed
image = np.clip(image, 0, 1)
ax.imshow(image)
return ax
"""# Class Prediction
Once you can get images in the correct format, it's time to write a function for making predictions with your model. A common practice is to predict the top 5 or so (usually called top-$K$) most probable classes. You'll want to calculate the class probabilities then find the $K$ largest values.
To get the top $K$ largest values in a tensor use [`x.topk(k)`](http://pytorch.org/docs/master/torch.html#torch.topk). This method returns both the highest `k` probabilities and the indices of those probabilities corresponding to the classes. You need to convert from these indices to the actual class labels using `class_to_idx` which hopefully you added to the model or from an `ImageFolder` you used to load the data ([see here](#Save-the-checkpoint)). Make sure to invert the dictionary so you get a mapping from index to class as well.
Again, this method should take a path to an image and a model checkpoint, then return the probabilities and classes.
```python
probs, classes = predict(image_path, model)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
"""
def predict(image_path, model, topk=2):
''' Predict the class (or classes) of an image using a trained deep learning model.
'''
# Implement the code to predict the class from an image file
image = torch.FloatTensor([process_image(Image.open(image_path))])
model.eval()
output = model.forward(Variable(image))
pobabilities = torch.exp(output).data.numpy()[0]
top_idx = np.argsort(pobabilities)[-topk:][::-1]
top_class = [idx_to_class[x] for x in top_idx]
top_probability = pobabilities[top_idx]
return top_probability, top_class
print (predict('b_cancer_data2/valid/MALIGNANT/SOB_M_DC-14-2985-200-007.png', loaded_model))
"""# Sanity Checking
Now that you can use a trained model for predictions, check to make sure it makes sense. Even if the validation accuracy is high, it's always good to check that there aren't obvious bugs. Use `matplotlib` to plot the probabilities for the top 5 classes as a bar graph, along with the input image. It should look like this:
"""
# Display an image along with the top 2 classes
def view_classify(img, probabilities, classes, mapper):
''' Function for viewing an image and it's predicted classes.
'''
img_filename = img.split('/')[-2]
img = Image.open(img)
fig, (ax1, ax2) = plt.subplots(figsize=(6,10), ncols=1, nrows=2)
cancer_type = mapper[img_filename]
ax1.set_title(cancer_type)
ax1.imshow(img)
ax1.axis('off')
y_pos = np.arange(len(probabilities))
ax2.barh(y_pos, probabilities)
ax2.set_yticks(y_pos)
ax2.set_yticklabels([mapper[x] for x in classes])
ax2.invert_yaxis()
img = 'b_cancer_data2/valid/MALIGNANT/SOB_M_DC-14-2985-200-007.png'
p, c = predict(img, loaded_model)
view_classify(img, p, c, cat_to_name)
img = 'b_cancer_data2/valid/MALIGNANT/SOB_M_PC-14-12465-400-013.png'
p, c = predict(img, loaded_model)
view_classify(img, p, c, cat_to_name)
img = 'b_cancer_data2/valid/BENIGN/SOB_B_A-14-22549AB-400-005.png'
p, c = predict(img, loaded_model)
view_classify(img, p, c, cat_to_name)
"""# CONCLUSIONS
The model can be improved if you change some hyperparameters. You can try using a different pretrained model. It's up to you. Let us know if you can improve the accuracy!
"""