How to use multiple_of method in Lemoncheesecake

Best Python code snippet using lemoncheesecake

test_crop_size_multiple.py

Source:test_crop_size_multiple.py Github

copy

Full Screen

1# ------------------------------------------------------------------------------------------2# Copyright (c) Microsoft Corporation. All rights reserved.3# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.4# ------------------------------------------------------------------------------------------5from typing import Any, Optional6import pytest7import torch8from InnerEye.Common.type_annotations import IntOrTuple3, TupleInt39from InnerEye.ML.config import ModelArchitectureConfig, SegmentationModelBase10from InnerEye.ML.models.architectures.base_model import BaseSegmentationModel, CropSizeConstraints11from InnerEye.ML.models.architectures.unet_3d import UNet3D12from InnerEye.ML.utils.model_util import build_net13class SimpleModel(BaseSegmentationModel):14 def __init__(self, input_channels: int, channels: list, n_classes: int, kernel_size: int,15 crop_size_constraints: CropSizeConstraints = None):16 super().__init__(input_channels=input_channels, name="SimpleModel", crop_size_constraints=crop_size_constraints)17 self.channels = channels18 self.n_classes = n_classes19 self.kernel_size = kernel_size20 self.model = torch.nn.Sequential(21 torch.nn.Conv3d(input_channels, channels[0], kernel_size=self.kernel_size),22 torch.nn.ConvTranspose3d(channels[0], n_classes, kernel_size=self.kernel_size)23 )24 def forward(self, x: Any) -> Any: # type: ignore25 x = self.model(x)26 return x27def test_crop_size_constraints() -> None:28 """29 Test the basic logic to validate a crop size inside of a CropSizeConstraints instance.30 """31 def check(crop_size: TupleInt3,32 multiple_of: Optional[IntOrTuple3] = None,33 minimum: Optional[IntOrTuple3] = None) -> CropSizeConstraints:34 constraints = CropSizeConstraints(minimum_size=minimum, multiple_of=multiple_of)35 constraints.validate(crop_size)36 return constraints37 # crop_size_multiple == 1: Any crop size is allowed.38 c = check((9, 10, 11), multiple_of=1)39 # If a scalar multiple_of is used, it should be stored expanded along dimensions40 assert c.multiple_of == (1, 1, 1)41 # Using a tuple multiple_of: Crop is twice as large as multiple_of in each dimension, this is hence valid.42 c = check((10, 12, 14), multiple_of=(5, 6, 7))43 assert c.multiple_of == (5, 6, 7)44 # Minimum size has not been provided, should default to multiple_of.45 assert c.minimum_size == (5, 6, 7)46 # Try with a couple more common crop sizes47 check((32, 64, 64), multiple_of=16)48 check((1, 64, 64), multiple_of=(1, 16, 16))49 # Crop size is at the allowed minimum: This is valid50 check((3, 4, 5), multiple_of=(3, 4, 5))51 # Provide a scalar minimum: Should be stored expanded into 3 dimensions52 c = check((9, 10, 11), minimum=2)53 assert c.minimum_size == (2, 2, 2)54 assert c.multiple_of is None55 # Provide a tuple minimum56 c = check((9, 10, 11), minimum=(5, 6, 7))57 assert c.minimum_size == (5, 6, 7)58 # A crop size at exactly the minimum is valid59 check((5, 6, 7), minimum=(5, 6, 7))60 # Checking for minimum and multiple at the same time61 check((9, 10, 11), minimum=1, multiple_of=1)62 check((10, 12, 14), minimum=(5, 6, 7), multiple_of=2)63 def assert_fails(crop_size: TupleInt3,64 multiple_of: Optional[IntOrTuple3] = None,65 minimum: Optional[IntOrTuple3] = None) -> None:66 with pytest.raises(ValueError) as err:67 check(crop_size, multiple_of, minimum)68 assert str(crop_size) in str(err)69 assert "Crop size is not valid" in str(err)70 # Crop size is not a multiple of 2 in dimensions 0 and 171 assert_fails((3, 4, 5), 2)72 # Crop size is not a multiple of 6 in dimension 273 assert_fails((3, 4, 5), (3, 4, 6))74 assert_fails((16, 16, 200), 16)75 # Crop size is too small76 assert_fails((1, 2, 3), (10, 10, 10))77 assert_fails((10, 20, 30), multiple_of=10, minimum=20)78 # Minimum size must be at least as large as multiple_of:79 with pytest.raises(ValueError) as err:80 CropSizeConstraints(minimum_size=10, multiple_of=20, num_dimensions=2)81 assert "minimum size must be at least as large as the multiple_of" in str(err)82 assert "(10, 10)" in str(err)83 assert "(20, 20)" in str(err)84 # Check that num_dimensions is working as expected (though not presently used in the codebase)85 c = CropSizeConstraints(minimum_size=30, multiple_of=10, num_dimensions=2)86 assert c.multiple_of == (10, 10)87 assert c.minimum_size == (30, 30)88def test_crop_size_constructor() -> None:89 """90 Test error handling in the constructor of CropSizeConstraints91 """92 # Minimum size is given as 3-tuple, but working with 2 dimensions:93 with pytest.raises(ValueError) as err:94 CropSizeConstraints(minimum_size=(1, 2, 3), num_dimensions=2)95 assert "must have length 2" in str(err)96 # Minimum size and multiple_of are not compatible:97 with pytest.raises(ValueError) as err:98 CropSizeConstraints(minimum_size=(1, 2, 3), multiple_of=16)99 assert "The minimum size must be at least as large" in str(err)100def test_crop_size_check_in_model() -> None:101 """102 Test that crop size checks are correctly integrated and called from within BaseModel103 """104 def create_model(crop_size: TupleInt3, multiple_of: IntOrTuple3) -> BaseSegmentationModel:105 model = SimpleModel(1, [1], 2, 2, crop_size_constraints=CropSizeConstraints(multiple_of=multiple_of))106 model.validate_crop_size(crop_size)107 return model108 # crop_size_multiple == 1: Any crop size is allowed.109 m = create_model((9, 10, 11), 1)110 assert m.crop_size_constraints.multiple_of == (1, 1, 1)111 m = create_model((10, 12, 14), (5, 6, 7))112 assert m.crop_size_constraints.multiple_of == (5, 6, 7)113 def assert_fails(crop_size: TupleInt3, crop_size_multiple: IntOrTuple3) -> None:114 with pytest.raises(ValueError) as err:115 create_model(crop_size, crop_size_multiple)116 assert "Crop size is not valid" in str(err)117 # Crop size is not a multiple of 2 in dimensions 0 and 1118 assert_fails((3, 4, 5), 2)119 # Crop size constraints field should be generated as not empty if not provided in the120 # constructor - this simplifies code in the inference pipeline.121 model = SimpleModel(1, [1], 2, 2)122 assert model.crop_size_constraints is not None123 assert model.crop_size_constraints.minimum_size == (1, 1, 1)124 assert model.crop_size_constraints.multiple_of == (1, 1, 1)125 model.validate_crop_size((1, 1, 1))126def test_crop_size_multiple_in_build_net() -> None:127 """128 Tests if the the crop_size validation is really called in the model creation code129 """130 config = SegmentationModelBase(architecture=ModelArchitectureConfig.UNet3D,131 image_channels=["ct"],132 feature_channels=[1],133 kernel_size=3,134 crop_size=(17, 16, 16),135 should_validate=False)136 # Crop size of 17 in dimension 0 is invalid for a UNet3D, should be multiple of 16.137 # This should raise a ValueError.138 with pytest.raises(ValueError) as ex:139 build_net(config)140 assert "Training crop size: Crop size is not valid" in str(ex)141 config.crop_size = (16, 16, 16)142 config.test_crop_size = (17, 18, 19)143 with pytest.raises(ValueError) as ex:144 build_net(config)145 assert "Test crop size: Crop size is not valid" in str(ex)146def crop_size_multiple_unet3d(crop_size: TupleInt3,147 downsampling_factor: IntOrTuple3,148 num_downsampling_paths: int,149 expected_crop_size_multiple: TupleInt3) -> None:150 model = UNet3D(name="",151 input_image_channels=1,152 initial_feature_channels=32,153 num_classes=2,154 kernel_size=3,155 downsampling_factor=downsampling_factor,156 num_downsampling_paths=num_downsampling_paths)157 assert model.crop_size_constraints.multiple_of == expected_crop_size_multiple158 model.validate_crop_size(crop_size)159def test_crop_size_multiple_unet3d() -> None:160 # Standard UNet with downsampling 2, 4 downsampling stages: Minimum crop is 16161 crop_size_multiple_unet3d(crop_size=(16, 64, 64), downsampling_factor=2, num_downsampling_paths=4,162 expected_crop_size_multiple=(16, 16, 16))163 # Only 3 downsampling stages: each reduces by a factor 2, hence minimum crop size should be 8164 crop_size_multiple_unet3d(crop_size=(16, 64, 64), downsampling_factor=2, num_downsampling_paths=3,165 expected_crop_size_multiple=(8, 8, 8))166 # UNet3D as used in UNet2D: No down-sampling in Z direction. Any crop size in Z is allowed, crop size167 # at least 16 in X and Y168 crop_size_multiple_unet3d(crop_size=(16, 64, 64), downsampling_factor=(1, 2, 2), num_downsampling_paths=4,169 expected_crop_size_multiple=(1, 16, 16))170 # Non-standard downsampling factor of 3, 2 downsampling stages: Minimum crop is 3*3 = 9171 crop_size_multiple_unet3d(crop_size=(9, 9, 9), downsampling_factor=3, num_downsampling_paths=2,172 expected_crop_size_multiple=(9, 9, 9))173def test_restrict_crop_size_too_small() -> None:174 """Test the modification of crop sizes when the image size is below the minimum."""175 shape = (10, 30, 40)176 crop_size = (20, 40, 20)177 stride = (10, 20, 20)178 constraint = CropSizeConstraints(multiple_of=16)179 with pytest.raises(ValueError) as e:180 constraint.restrict_crop_size_to_image(shape, crop_size, stride)181 # Error message should contain the actual image size182 assert str(shape) in e.value.args[0]183 assert "16" in e.value.args[0]184def check_restrict_crop(constraint: CropSizeConstraints,185 shape: TupleInt3,186 crop_size: TupleInt3,187 stride: TupleInt3,188 expected_crop: TupleInt3,189 expected_stride: TupleInt3) -> None:190 (crop_new, stride_new) = constraint.restrict_crop_size_to_image(shape, crop_size, stride)191 assert crop_new == expected_crop192 assert stride_new == expected_stride193 # Stride and crop must be integer tuples194 assert isinstance(crop_new[0], int)195 assert isinstance(stride_new[0], int)196def test_restrict_crop_size() -> None:197 """Test the modification of crop sizes when the image size is smaller than the crop."""198 shape = (20, 35, 40)199 crop_size = (25, 40, 20)200 stride = (10, 20, 20)201 constraint = CropSizeConstraints(multiple_of=16)202 # Expected new crop size is the elementwise minimum of crop_size and shape,203 # rounded up to the nearest multiple of 16204 expected_crop = (32, 48, 32)205 # Stride should maintain (elementwise) the same ratio to crop as before206 expected_stride = (12, 24, 32)207 check_restrict_crop(constraint, shape, crop_size, stride, expected_crop, expected_stride)208def test_restrict_crop_size_tuple() -> None:209 """Test the modification of crop sizes when the image size is smaller than the crop,210 and the crop_multiple is a tuple with element-wise multiples."""211 shape = (20, 35, 40)212 crop_size = (25, 40, 20)213 stride = (10, 20, 20)214 constraint = CropSizeConstraints(multiple_of=(1, 16, 16))215 # Expected new crop size is the elementwise minimum of crop_size and shape,216 # rounded down to the nearest multiple of 16, apart from dimension 0217 expected_crop = (20, 48, 32)218 expected_stride = (8, 24, 32)219 check_restrict_crop(constraint, shape, crop_size, stride, expected_crop, expected_stride)220def test_restrict_crop_size_large_image() -> None:221 """Test the modification of crop sizes when the image size is larger than the crop:222 The crop and stride should be returned unchanged."""223 shape = (30, 50, 50)224 crop_size = (20, 40, 40)225 stride = crop_size226 constraint = CropSizeConstraints(multiple_of=1)227 expected_crop = crop_size228 expected_stride = stride229 check_restrict_crop(constraint, shape, crop_size, stride, expected_crop, expected_stride)230 constraint2 = CropSizeConstraints(multiple_of=1, minimum_size=999)231 with pytest.raises(ValueError) as err:232 check_restrict_crop(constraint2, shape, crop_size, stride, expected_crop, expected_stride)233 assert "at least a size of" in str(err)234 assert "999" in str(err)235def test_restrict_crop_size_uneven() -> None:236 """237 Test a case when the image is larger than the crop in Z, but not in X and Y.238 """239 shape = (20, 30, 30)240 crop_size = (10, 60, 60)241 stride = crop_size242 constraint = CropSizeConstraints(multiple_of=1)243 expected_crop = (10, 30, 30)244 expected_stride = (10, 30, 30)...

Full Screen

Full Screen

game_list.py

Source:game_list.py Github

copy

Full Screen

1import collections2import functools3import gspread_asyncio4from oauth2client.service_account import ServiceAccountCredentials5import re6import common7## Range & co8@functools.total_ordering9class _Least:10 # Default __eq__ is fine assuming there is only one instance11 def __gt__(self, other):12 return False13least = _Least()14@functools.total_ordering15class _Greatest:16 # Default __eq__ is fine assuming there is only one instance17 def __lt__(self, other):18 return False19greatest = _Greatest()20def _round_low_to_multiple(low, multiple_of):21 return low if low is least else low + (-low % multiple_of)22def _round_high_to_multiple(high, multiple_of):23 return high if high is greatest else high - (high % multiple_of)24class Range:25 def __init__(self, low, high, multiple_of=1):26 assert (low is least) or isinstance(low, int)27 assert (high is greatest) or isinstance(high, int)28 assert isinstance(multiple_of, int)29 self.low = _round_low_to_multiple(low, multiple_of)30 self.high = _round_high_to_multiple(high, multiple_of)31 self.multiple_of = multiple_of32 def __bool__(self):33 return self.low <= self.high34 def __contains__(self, x):35 return (self.low <= x <= self.high) and ((x % self.multiple_of) == 0)36 def __str__(self):37 if not self:38 return 'none'39 if self.low is least:40 if self.high is greatest:41 s = 'any'42 else:43 s = f'up to {self.high}'44 elif self.high is greatest:45 s = f'{self.low}+'46 elif self.low == self.high:47 return f'{self.low}'48 else:49 s = f'{self.low}..{self.high}'50 if self.multiple_of == 1:51 return s52 if self.multiple_of == 2:53 return f'{s} even'54 return f'{s} multiple of {self.multiple_of}'55 def simplified(self, implicit_low, implicit_high):56 assert (implicit_low is least) or isinstance(implicit_low, int)57 assert (implicit_high is greatest) or isinstance(implicit_high, int)58 implicit_low = _round_low_to_multiple(implicit_low, self.multiple_of)59 implicit_high = _round_high_to_multiple(implicit_high, self.multiple_of)60 low = max(self.low, implicit_low)61 high = min(self.high, implicit_high)62 if low >= high:63 # Either empty or one number in range64 return Range(low, high)65 return Range(66 least if low == implicit_low else low,67 greatest if high == implicit_high else high,68 self.multiple_of)69## Parsing70_num_re = re.compile('[0-9]+')71def _nums(s):72 for m in _num_re.finditer(s):73 yield int(m.group())74def _max_num(s):75 return max(_nums(s), default=None)76_num_plus_re = re.compile(r'([0-9]+)\+')77def _num_range(s):78 multiple_of = 2 if 'even' in s.lower() else 179 if m := _num_plus_re.search(s):80 return Range(int(m.group(1)), greatest, multiple_of)81 if nums := list(_nums(s)):82 return Range(min(nums), max(nums), multiple_of)83 return None84_Field = collections.namedtuple('_Field',85 'name heading_re parse sub_heading_row required',86 defaults=(lambda s: s, None, False))87_fields = [88 _Field('title', re.compile('title', re.IGNORECASE), required=True),89 _Field('platform', re.compile('platform', re.IGNORECASE)),90 _Field('max_players', re.compile('max.+player', re.IGNORECASE), _max_num),91 _Field('good_players', re.compile('good.+player', re.IGNORECASE), _num_range),92 _Field('owns', re.compile('who.+owns', re.IGNORECASE), bool, sub_heading_row=2)]93_heading_row = 094_data_begin_row = 395Game = collections.namedtuple('Game', (field.name for field in _fields))96def _fixup(game):97 if game.good_players is None:98 return game99 if good_players := game.good_players.simplified(1,100 greatest if game.max_players is None else game.max_players):101 return game._replace(good_players=good_players)102 # Assume we didn't parse the good players field properly...103 return game._replace(good_players=None)104class _Loc:105 def __init__(self, field):106 self.field = field107 self.begin_col = None108 # self.end_col set once found109 # self.sub_headings set at end of _get_locs110def _get_locs(rows):111 locs = {field.name: _Loc(field) for field in _fields}112 cont_loc = None113 for col, heading in enumerate(rows[_heading_row]):114 if heading:115 cont_loc = None116 for loc in locs.values():117 heading_re = loc.field.heading_re118 if heading_re.search(heading):119 if loc.begin_col is not None:120 raise common.Error(121 f'I found multiple headings matching "{heading_re.pattern}" in the GL spreadsheet.')122 loc.begin_col = col123 loc.end_col = col + 1124 if loc.field.sub_heading_row is not None:125 cont_loc = loc126 break127 elif cont_loc is not None:128 if rows[cont_loc.field.sub_heading_row][col]:129 cont_loc.end_col = col + 1130 else:131 cont_loc = None132 for loc in locs.values():133 if loc.begin_col is None:134 raise common.Error(135 f'I couldn\'t find a heading matching "{loc.field.heading_re.pattern}" in the GL spreadsheet.')136 if loc.field.sub_heading_row is not None:137 loc.sub_headings = rows[loc.field.sub_heading_row][loc.begin_col:loc.end_col]138 seen = set()139 for sub_heading in loc.sub_headings:140 if sub_heading in seen:141 raise common.Error(142 'There are multiple columns in the GL spreadsheet under '143 f'{rows[_heading_row][loc.begin_col]} with the same '144 f'sub-heading ({sub_heading}).')145 seen.add(sub_heading)146 return locs147class _MissingRequiredField(Exception):148 pass149def _parse_field(loc, row):150 values = []151 for s in row[loc.begin_col:loc.end_col]:152 if loc.field.required and not s:153 raise _MissingRequiredField()154 values.append(loc.field.parse(s))155 return values[0] if loc.field.sub_heading_row is None else dict(zip(loc.sub_headings, values))156GameList = collections.namedtuple('GameList', 'names games')157def _parse(rows):158 rows = [[s.strip() for s in row] for row in rows]159 locs = _get_locs(rows)160 names = set(locs['owns'].sub_headings)161 games = []162 for row in rows[_data_begin_row:]:163 try:164 values = {loc.field.name: _parse_field(loc, row) for loc in locs.values()}165 except _MissingRequiredField:166 continue167 games.append(_fixup(Game(**values)))168 return GameList(names, games)169## Google Sheets stuff170def _make_gsheets_client_manager(gsheets_creds):171 def get_creds():172 return ServiceAccountCredentials.from_json_keyfile_name(173 gsheets_creds, ['https://www.googleapis.com/auth/spreadsheets.readonly'])174 return gspread_asyncio.AsyncioGspreadClientManager(get_creds)175async def _fetch_gsheets_rows(cm, id):176 c = await cm.authorize()177 ss = await c.open_by_key(id)178 ws = await ss.get_worksheet(0)179 return await ws.get_all_values()180## Top level181class Session:182 def __init__(self, gsheets_creds):183 self.__cm = _make_gsheets_client_manager(gsheets_creds)184 async def fetch(self, id):185 rows = await _fetch_gsheets_rows(self.__cm, id)...

Full Screen

Full Screen

Ostroumov_DZ_6-1.py

Source:Ostroumov_DZ_6-1.py Github

copy

Full Screen

1"""21. Подсчитать, сколько было выделено памяти под переменные в ранее разработанных3программах в рамках первых трех уроков.4Проанализировать результат и определить программы с наиболее эффективным использованием памяти.5Примечание: Для анализа возьмите любые 1-3 ваших программы или несколько вариантов кода для одной и той же задачи.6Результаты анализа вставьте в виде комментариев к коду.7Также укажите в комментариях версию Python и разрядность вашей ОС.8/// версия Python 3.99/// Windows 10 pro x6410/// 3-8. Матрица 5x4 заполняется вводом с клавиатуры кроме последних элементов строк.11Программа должна вычислять сумму введенных элементов каждой строки и записывать ее в последнюю ячейку строки.12В конце следует вывести полученную матрицу.13"""14import random15import sys16def m_string(a):17 """18 формирует массив на заданное количество элементов19 :param a: длинна требуемого массива20 :return: возращает массив21 """22 array = [0] * a23 for i in range(a):24 array[i] = int(random.randint(1, 100))25 return array26def counter(a):27 """28 считает сумму элементов массива и записывает результат в конец массива29 :param a: передается массив30 :return: возращается массив с посчитанной суммой элементов массива31 """32 summ = 033 for item in a:34 summ += int(item)35 return a.append(summ)36m_string_1 = m_string(3)37counter(m_string_1)38result = [m_string_1]39result_3 = sys.getsizeof(result) + sys.getsizeof(m_string_1)40print(f'{sys.getsizeof(result) = }, {sys.getsizeof(m_string_1) = },\n'41 f'общее количество затраченной памяти: {result_3}\n \n \n')42"""43sys.getsizeof(result) = 64, sys.getsizeof(m_string_1) = 120,44общее количество затраченной памяти: 18445/// 3 - 1. В диапазоне натуральных чисел от 2 до 99 определить,46сколько из них кратны каждому из чисел в диапазоне от 2 до 9.47"""48nums = [n for n in range(2, 100)]49multiple_of = {"два": 0, "три": 0, "четыре": 0, "пять": 0, "шесть": 0, "семь": 0, "восемь": 0, "девять": 0}50# для анализа ввожу дополниетельные переменные:51two = 052three = 053four = 054five = 055six = 056seven = 057eight = 058nine = 059for item in nums:60 if item % 2 == 0:61 multiple_of["два"] += 162 two += 163 if item % 3 == 0:64 multiple_of["три"] += 165 three += 166 if item % 4 == 0:67 multiple_of["четыре"] += 168 four += 169 if item % 5 == 0:70 multiple_of["пять"] += 171 five += 172 if item % 6 == 0:73 multiple_of["шесть"] += 174 six += 175 if item % 7 == 0:76 multiple_of["семь"] += 177 seven += 178 if item % 8 == 0:79 multiple_of["восемь"] += 180 eight += 181 if item % 9 == 0:82 multiple_of["девять"] += 183 nine += 184result_1 = sys.getsizeof(nums) + sys.getsizeof(multiple_of)85result_2 = two + three + four + five + six + seven + eight + nine + sys.getsizeof(nums)86print(f'{sys.getsizeof(nums) = }, {sys.getsizeof(multiple_of) = }, всего {result_1}')87print(f'каждая "индивдуальная" переменная будет занимать {two} памяти')88print(f'без словаря, с индивидуальными переменными: {result_2}')89'''90sys.getsizeof(nums) = 920, sys.getsizeof(multiple_of) = 360, всего 128091каждая "индивдуальная" переменная будет занимать 49 памяти92без словаря, с индивидуальными переменными: 1098...

Full Screen

Full Screen

transforms_resize_modulo_pad_crop.py

Source:transforms_resize_modulo_pad_crop.py Github

copy

Full Screen

1import collections2import functools3from numbers import Number4from typing import Union, Optional5import numpy as np6from .transforms import CriteriaFn7from ..transforms import transforms8from ..transforms import crop9from ..basic_typing import ShapeX10from ..utils import batch_pad_minmax_joint11from typing_extensions import Literal12def _transform_resize_modulo_crop_pad(13 features_names,14 batch,15 multiple_of,16 mode,17 padding_mode,18 padding_constant_value):19 resized_arrays = []20 arrays = [batch[name] for name in features_names]21 for a in arrays[1:]:22 assert len(a.shape) == len(arrays[0].shape)23 assert a.shape[2:] == arrays[0].shape[2:], f'selected tensors MUST have the same size. ' \24 f'Expected={a.shape}, got={arrays[0].shape}'25 if len(features_names) > 0:26 shape = arrays[0].shape[2:]27 if isinstance(multiple_of, Number):28 multiple_of = [multiple_of] * (len(shape))29 multiple_of = np.asarray(multiple_of)30 assert len(shape) == len(multiple_of), 'expected multiple_of expressed as [D]HW shape!'31 shape_extra = arrays[0].shape[2:] % multiple_of32 if mode == 'pad':33 # padding is centered34 padding = multiple_of - shape_extra35 padding_left = padding // 236 padding_right = padding - padding_left37 padding_left = [0] + list(padding_left)38 padding_right = [0] + list(padding_right)39 resized_arrays = batch_pad_minmax_joint(40 arrays,41 padding_left,42 padding_right,43 padding_mode,44 padding_constant_value45 )46 elif mode == 'crop':47 s = list(shape - shape_extra)48 assert min(s) > 0, f'shape is too small! Use a different mode. ' \49 f'Got={arrays[0].shape[2:]}, multiple_of={multiple_of}'50 resized_arrays = crop.transform_batch_random_crop_joint(arrays, [None] + s)51 else:52 raise NotImplementedError(f'mode={mode} is not handled!')53 new_batch = collections.OrderedDict(zip(features_names, resized_arrays))54 for feature_name, feature_value in batch.items():55 if feature_name not in features_names:56 # not in the transformed features, so copy the original value57 new_batch[feature_name] = feature_value58 return new_batch59class TransformResizeModuloCropPad(transforms.TransformBatchWithCriteria):60 """61 Resize tensors by padding or cropping the tensor so its shape is a multiple of a ``multiple_of``.62 This can be particularly helpful in encoder-decoder architecture with skip connection which can impose63 constraints on the input shape (e.g., the input must be a multiple of 32 pixels).64 Args:65 multiple_of: a sequence of size `len(array.shape)-2` such that shape % multiple_of == 0. To achieve this,66 the tensors will be padded or cropped.67 criteria_fn: function applied on each feature. If satisfied, the feature will be transformed, if not68 the original feature is returned69 padding_mode: `numpy.pad` mode. Currently supported are ('constant', 'edge', 'symmetric')70 mode: one of `crop`, `pad`. If `pad`, the selected tensors will be padded to achieve the71 size tensor.shape % multiple_of == 0. If `crop`, the selected tensors will be cropped72 instead with a randomly selected cropping position.73 Returns:74 dictionary with the selected tensors cropped or padded to the appropriate size75 """76 def __init__(77 self,78 multiple_of: Union[int, ShapeX],79 criteria_fn: Optional[CriteriaFn] = None,80 mode: Literal['crop', 'pad'] = 'crop',81 padding_mode: Literal['edge', 'constant', 'symmetric'] = 'constant',82 padding_constant_value: int = 0):83 if criteria_fn is None:84 criteria_fn = transforms.criteria_is_array_4_or_above85 super().__init__(86 criteria_fn=criteria_fn,87 transform_fn=functools.partial(88 _transform_resize_modulo_crop_pad,89 padding_mode=padding_mode,90 mode=mode,91 padding_constant_value=padding_constant_value,92 multiple_of=multiple_of)93 )...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Lemoncheesecake automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful