-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvertML.py
74 lines (62 loc) · 2.77 KB
/
convertML.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
import torch
import torch.nn as nn
from PIL import Image
import torchvision.transforms as transforms
class Face_Emotion_CNN(nn.Module):
def __init__(self):
super(Face_Emotion_CNN, self).__init__()
self.cnn1 = nn.Conv2d(in_channels=1, out_channels=8, kernel_size=3)
self.cnn2 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3)
self.cnn3 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3)
self.cnn4 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3)
self.cnn5 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3)
self.cnn6 = nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3)
self.cnn7 = nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3)
self.relu = nn.ReLU()
self.pool1 = nn.MaxPool2d(2, 1)
self.pool2 = nn.MaxPool2d(2, 2)
self.cnn1_bn = nn.BatchNorm2d(8)
self.cnn2_bn = nn.BatchNorm2d(16)
self.cnn3_bn = nn.BatchNorm2d(32)
self.cnn4_bn = nn.BatchNorm2d(64)
self.cnn5_bn = nn.BatchNorm2d(128)
self.cnn6_bn = nn.BatchNorm2d(256)
self.cnn7_bn = nn.BatchNorm2d(256)
self.fc1 = nn.Linear(1024, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, 7)
self.dropout = nn.Dropout(0.3)
self.log_softmax = nn.LogSoftmax(dim=1)
def forward(self, x):
x = self.relu(self.pool1(self.cnn1_bn(self.cnn1(x))))
x = self.relu(self.pool1(self.cnn2_bn(self.dropout(self.cnn2(x)))))
x = self.relu(self.pool1(self.cnn3_bn(self.cnn3(x))))
x = self.relu(self.pool1(self.cnn4_bn(self.dropout(self.cnn4(x)))))
x = self.relu(self.pool2(self.cnn5_bn(self.cnn5(x))))
x = self.relu(self.pool2(self.cnn6_bn(self.dropout(self.cnn6(x)))))
x = self.relu(self.pool2(self.cnn7_bn(self.dropout(self.cnn7(x)))))
x = x.view(x.size(0), -1)
x = self.relu(self.dropout(self.fc1(x)))
x = self.relu(self.dropout(self.fc2(x)))
x = self.log_softmax(self.fc3(x))
return x
def count_parameters(self):
return sum(p.numel() for p in self.parameters() if p.requires_grad)
if __name__ == '__main__':
bn_model = Face_Emotion_CNN()
x = torch.randn(1,1,48,48)
print('Shape of output = ',bn_model(x).shape)
print('No of Parameters of the BatchNorm-CNN Model =',bn_model.count_parameters())
model = Face_Emotion_CNN()
model_path = 'pytorch_model.pt'
model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
model.eval()
example_input = torch.randn(1, 1, 48, 48)
traced_model = torch.jit.trace(model, example_input)
import coremltools as ct
try:
mlmodel = ct.convert(traced_model, inputs=[ct.TensorType(name="input", shape=example_input.shape)], source= "PyTorch")
mlmodel.save("ModelNew.mlpackage")
print("CoreML Model Saved Successfully")
except Exception as e:
print(f"Error converting to CoreML: {e}")