|
| 1 | +import numpy as np |
| 2 | +import torch |
| 3 | +import torch.nn as nn |
| 4 | +from torch.autograd import Variable |
| 5 | +from pytorch2keras.converter import pytorch_to_keras |
| 6 | + |
| 7 | + |
| 8 | +class MaxPool(nn.Module): |
| 9 | + """Module for MaxPool conversion testing |
| 10 | + """ |
| 11 | + |
| 12 | + def __init__(self, inp=10, out=16, kernel_size=3, bias=True): |
| 13 | + super(MaxPool, self).__init__() |
| 14 | + self.conv3d = nn.Conv3d(inp, out, kernel_size=kernel_size, bias=bias) |
| 15 | + self.pool3d = nn.MaxPool3d(kernel_size=3, padding=1) |
| 16 | + |
| 17 | + def forward(self, x): |
| 18 | + x = self.conv3d(x) |
| 19 | + x = self.pool3d(x) |
| 20 | + return x |
| 21 | + |
| 22 | + |
| 23 | +if __name__ == '__main__': |
| 24 | + max_error = 0 |
| 25 | + for i in range(100): |
| 26 | + kernel_size = np.random.randint(1, 7) |
| 27 | + inp = np.random.randint(kernel_size + 1, 30) |
| 28 | + out = np.random.randint(1, 30) |
| 29 | + |
| 30 | + model = MaxPool(inp, out, kernel_size, inp % 2) |
| 31 | + |
| 32 | + input_np = np.random.uniform(0, 1, (1, inp, inp, inp, inp)) |
| 33 | + input_var = Variable(torch.FloatTensor(input_np)) |
| 34 | + output = model(input_var) |
| 35 | + |
| 36 | + k_model = pytorch_to_keras(model, input_var, (inp, inp, inp, inp,), verbose=True) |
| 37 | + |
| 38 | + pytorch_output = output.data.numpy() |
| 39 | + keras_output = k_model.predict(input_np) |
| 40 | + |
| 41 | + error = np.max(pytorch_output - keras_output) |
| 42 | + print(error) |
| 43 | + if max_error < error: |
| 44 | + max_error = error |
| 45 | + |
| 46 | + print('Max error: {0}'.format(max_error)) |
0 commit comments