Function to do numpy like padding on tensors. Only works for 2-D padding. Inputs: x (tensor): tensor to pad pad (tuple): tuple of (left, right, top, bottom) pad sizes mode (str): 'symmetric', 'wrap', 'constant, 'reflect', 'replicate', or 'zero'. T
(x, pad, mode='constant', value=0)
| 260 | |
| 261 | |
| 262 | def mypad(x, pad, mode='constant', value=0): |
| 263 | """ Function to do numpy like padding on tensors. Only works for 2-D |
| 264 | padding. |
| 265 | |
| 266 | Inputs: |
| 267 | x (tensor): tensor to pad |
| 268 | pad (tuple): tuple of (left, right, top, bottom) pad sizes |
| 269 | mode (str): 'symmetric', 'wrap', 'constant, 'reflect', 'replicate', or |
| 270 | 'zero'. The padding technique. |
| 271 | """ |
| 272 | if mode == 'symmetric': |
| 273 | # Vertical only |
| 274 | if pad[0] == 0 and pad[1] == 0: |
| 275 | m1, m2 = pad[2], pad[3] |
| 276 | l = x.shape[-2] |
| 277 | xe = reflect(np.arange(-m1, l + m2, dtype='int32'), -0.5, l - 0.5) |
| 278 | return x[:, :, xe] |
| 279 | # horizontal only |
| 280 | elif pad[2] == 0 and pad[3] == 0: |
| 281 | m1, m2 = pad[0], pad[1] |
| 282 | l = x.shape[-1] |
| 283 | xe = reflect(np.arange(-m1, l + m2, dtype='int32'), -0.5, l - 0.5) |
| 284 | return x[:, :, :, xe] |
| 285 | # Both |
| 286 | else: |
| 287 | m1, m2 = pad[0], pad[1] |
| 288 | l1 = x.shape[-1] |
| 289 | xe_row = reflect(np.arange(-m1, l1 + m2, dtype='int32'), -0.5, l1 - 0.5) |
| 290 | m1, m2 = pad[2], pad[3] |
| 291 | l2 = x.shape[-2] |
| 292 | xe_col = reflect(np.arange(-m1, l2 + m2, dtype='int32'), -0.5, l2 - 0.5) |
| 293 | i = np.outer(xe_col, np.ones(xe_row.shape[0])) |
| 294 | j = np.outer(np.ones(xe_col.shape[0]), xe_row) |
| 295 | return x[:, :, i, j] |
| 296 | elif mode == 'periodic': |
| 297 | # Vertical only |
| 298 | if pad[0] == 0 and pad[1] == 0: |
| 299 | xe = np.arange(x.shape[-2]) |
| 300 | xe = np.pad(xe, (pad[2], pad[3]), mode='wrap') |
| 301 | return x[:, :, xe] |
| 302 | # Horizontal only |
| 303 | elif pad[2] == 0 and pad[3] == 0: |
| 304 | xe = np.arange(x.shape[-1]) |
| 305 | xe = np.pad(xe, (pad[0], pad[1]), mode='wrap') |
| 306 | return x[:, :, :, xe] |
| 307 | # Both |
| 308 | else: |
| 309 | xe_col = np.arange(x.shape[-2]) |
| 310 | xe_col = np.pad(xe_col, (pad[2], pad[3]), mode='wrap') |
| 311 | xe_row = np.arange(x.shape[-1]) |
| 312 | xe_row = np.pad(xe_row, (pad[0], pad[1]), mode='wrap') |
| 313 | i = np.outer(xe_col, np.ones(xe_row.shape[0])) |
| 314 | j = np.outer(np.ones(xe_col.shape[0]), xe_row) |
| 315 | return x[:, :, i, j] |
| 316 | |
| 317 | elif mode == 'constant' or mode == 'reflect' or mode == 'replicate': |
| 318 | return F.pad(x, pad, mode, value) |
| 319 | elif mode == 'zero': |
no test coverage detected