rdkulkarni commited on
Commit
39bf8ff
1 Parent(s): 52722b6

Upload neural_network_model.py

Browse files
Files changed (1) hide show
  1. neural_network_model.py +131 -0
neural_network_model.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torchvision import models
2
+ from torch import nn
3
+ import torch
4
+ from collections import OrderedDict
5
+
6
+ def set_parameter_requires_grad(model, feature_extracting):
7
+ if feature_extracting:
8
+ for param in model.parameters():
9
+ param.requires_grad = False
10
+
11
+ def initialize_existing_models(model_name, model_type, num_classes, feature_extract, hidden_units, use_pretrained=True):
12
+ # Initialize these variables which will be set in this if statement. Each of these variables is model specific.
13
+ model_ft = None
14
+ input_size = 0
15
+
16
+ if model_name == "resnet18":
17
+ model_ft = models.resnet18(pretrained=use_pretrained)
18
+ set_parameter_requires_grad(model_ft, feature_extract)
19
+ num_ftrs = model_ft.fc.in_features
20
+ model_ft.fc = nn.Sequential(
21
+ nn.Linear(num_ftrs, num_classes),
22
+ nn.LogSoftmax(dim=1))
23
+ input_size = 224
24
+ elif model_name == "alexnet":
25
+ model_ft = models.alexnet(pretrained=use_pretrained)
26
+ set_parameter_requires_grad(model_ft, feature_extract)
27
+ num_ftrs = model_ft.classifier[6].in_features
28
+ model_ft.classifier[6] = nn.Sequential(
29
+ nn.Linear(num_ftrs,num_classes),
30
+ nn.LogSoftmax(dim=1))
31
+ input_size = 224
32
+ elif model_name in ["vgg11_bn", "vgg13", "vgg16"]:
33
+ model_ft = models.vgg11_bn(pretrained=use_pretrained)
34
+ set_parameter_requires_grad(model_ft, feature_extract)
35
+ num_ftrs = model_ft.classifier[6].in_features
36
+ model_ft.classifier[6] = nn.Sequential(
37
+ nn.Linear(num_ftrs,num_classes),
38
+ nn.LogSoftmax(dim=1))
39
+ input_size = 224
40
+ elif model_name == "squeezenet":
41
+ model_ft = models.squeezenet1_0(pretrained=use_pretrained)
42
+ set_parameter_requires_grad(model_ft, feature_extract)
43
+ model_ft.classifier[1] = nn.Sequential(
44
+ nn.Conv2d(512, num_classes, kernel_size=(1,1), stride=(1,1)),
45
+ nn.LogSoftmax(dim=1))
46
+ model_ft.num_classes = num_classes
47
+ input_size = 224
48
+ elif model_name == "densenet121":
49
+ model_ft = models.densenet121(pretrained=use_pretrained)
50
+ set_parameter_requires_grad(model_ft, feature_extract)
51
+ num_ftrs = model_ft.classifier.in_features
52
+ model_ft.classifier = nn.Sequential(
53
+ nn.Linear(num_ftrs, num_classes),
54
+ nn.LogSoftmax(dim=1))
55
+ input_size = 224
56
+ elif model_name == "inception": # This model expects (299,299) sized images and has auxiliary output
57
+ model_ft = models.inception_v3(pretrained=use_pretrained)
58
+ set_parameter_requires_grad(model_ft, feature_extract)
59
+ # Handle the auxilary net
60
+ num_ftrs = model_ft.AuxLogits.fc.in_features
61
+ model_ft.AuxLogits.fc = nn.Sequential(
62
+ nn.Linear(num_ftrs, num_classes),
63
+ nn.LogSoftmax(dim=1))
64
+ # Handle the primary net
65
+ num_ftrs = model_ft.fc.in_features
66
+ model_ft.fc = nn.Sequential(
67
+ nn.Linear(num_ftrs,num_classes),
68
+ nn.LogSoftmax(dim=1))
69
+ input_size = 299
70
+ else:
71
+ print("Invalid model name, please use one of the models supported by this application, exiting...")
72
+ exit()
73
+ return model_ft, input_size
74
+
75
+ #Get pre-trained model specifications and override with classifier portion with user activation units
76
+ def build_custom_models(model_name, model_type, num_classes, feature_extract, hidden_units, use_pretrained=True):
77
+
78
+ model_ft = getattr(models, model_name)(pretrained = use_pretrained)
79
+ set_parameter_requires_grad(model_ft, feature_extract)
80
+ if model_name == 'resnet18':
81
+ in_features = model_ft.fc.in_features
82
+ else:
83
+ try: #Is there an iterable classifier layer for the model chosen?
84
+ iter(model_ft.classifier)
85
+ except TypeError: #If no, choose the classifier layer with no index
86
+ in_features = model_ft.classifier.in_features
87
+ else:
88
+ try: #If yes, check if first index has in_features attribute
89
+ in_features = model_ft.classifier[0].in_features
90
+ except AttributeError: #If No, check if second index has in_features attribute
91
+ in_features = model_ft.classifier[1].in_features
92
+
93
+ hidden_layers = [in_features] + hidden_units
94
+ layer_builder = (
95
+ lambda i, v : (f"fc{i}", nn.Linear(hidden_layers[i-1], v)),
96
+ lambda i, v: (f"relu{i}", nn.ReLU()),
97
+ lambda i, v: (f"drop{i}", nn.Dropout())
98
+ )
99
+
100
+ layers = [f(i, v) for i, v in enumerate(hidden_layers) if i > 0 for f in layer_builder]
101
+ layers += [('fc_final', nn.Linear(hidden_layers[-1], num_classes)),
102
+ ('output', nn.LogSoftmax(dim=1))]
103
+
104
+ if model_name == 'resnet18':
105
+ fc = nn.Sequential(OrderedDict(layers))
106
+ model_ft.fc = fc
107
+ else:
108
+ classifier = nn.Sequential(OrderedDict(layers))
109
+ model_ft.classifier = classifier
110
+ # print("AFTER")
111
+ # print(model.classifier)
112
+
113
+ return model_ft
114
+
115
+ #Define model/ neural network class
116
+ # class ImageClassifier(nn.Module):
117
+ # def __init__(self):
118
+ # super(ImageClassifer, self).__init__()
119
+ # self.flatten = nn.Flatten()
120
+ # self.model_stack = nn.Sequential(
121
+ # nn.Linear(),
122
+ # nn.ReLU(),
123
+ # nn.Dropout(0.2),
124
+ # nn.Linear(),
125
+ # nn.LogSoftmax(dim=1)
126
+ # )
127
+
128
+ # def forward(self, x):
129
+ # x = self.flatten(x)
130
+ # logits = self.model_stack(x)
131
+ # return logits