(request)
| 4 | import torch.nn as nn |
| 5 | |
| 6 | def predict(request): |
| 7 | class MultiClassNet(nn.Module): |
| 8 | def __init__(self, NUM_FEATURES, NUM_CLASSES, HIDDEN_FEATURES): |
| 9 | super().__init__() |
| 10 | self.lin1 = nn.Linear(NUM_FEATURES, HIDDEN_FEATURES) |
| 11 | self.lin2 = nn.Linear(HIDDEN_FEATURES, NUM_CLASSES) |
| 12 | self.log_softmax = nn.LogSoftmax(dim=1) |
| 13 | self.relu = nn.ReLU() |
| 14 | |
| 15 | def forward(self, x): |
| 16 | x = self.lin1(x) |
| 17 | x = self.relu(x) |
| 18 | x = self.lin2(x) |
| 19 | x = self.log_softmax(x) |
| 20 | return x |
| 21 | # model instance |
| 22 | model = MultiClassNet(HIDDEN_FEATURES=6, NUM_CLASSES=3, NUM_FEATURES=4) |
| 23 | |
| 24 | # model weights |
| 25 | URL = 'https://storage.googleapis.com/deploy_iris_model/model_iris_state.pt' |
| 26 | r = requests.get(URL) |
| 27 | local_temp_file = "/tmp/model.pt" |
| 28 | file = open(local_temp_file, "wb") |
| 29 | file.write(r.content) |
| 30 | file.close() |
| 31 | model.load_state_dict(torch.load(local_temp_file)) |
| 32 | |
| 33 | dict_data = request.get_json() |
| 34 | X = torch.tensor([dict_data['data']]) |
| 35 | |
| 36 | y_test_hat_softmax = model(X) |
| 37 | y_test_hat = torch.max(y_test_hat_softmax.data, 1) |
| 38 | y_test_cls = y_test_hat.indices.detach().numpy()[0] |
| 39 | cls_dict = { |
| 40 | 0: 'setosa', |
| 41 | 1: 'versicolor', |
| 42 | 2: 'virginica' |
| 43 | } |
| 44 | |
| 45 | result = f"Your flower belongs to class {cls_dict[y_test_cls]}." |
| 46 | return result |
nothing calls this directly
no test coverage detected