Best Python code snippet using hypothesis
dataset.py
Source:dataset.py
...24 self.return_domain = return_domain25 self.src = src26 def __len__(self):27 return len(self.data)28 def get_example(self, i, r=None):29 x, y = self.data[i]30 if r is None:31 r = np.random.randint(self.n_domain)32 x = imrotate(np.tile(x, (3, 1, 1)), self.rotate[r]).transpose(2, 0, 1)[[0]]33 if self.return_domain:34 return x, y, r35 else:36 return x.astype(np.float32), y.astype(np.int8)37class SVHNDataset(dataset_mixin.DatasetMixin):38 img_size = (28, 28)39 def __init__(self, root=os.path.join(dataset_path, 'SVHN_MNIST'), src='train', size=999999999, k=None):40 if src == 'train':41 mat = io.loadmat(os.path.join(root, 'train_32x32.mat'))42 elif src == 'test':43 mat = io.loadmat(os.path.join(root, 'test_32x32.mat'))44 else:45 raise ValueError46 matx = mat['X'].transpose(2, 3, 0, 1).mean(axis=0)47 maty = mat['y'][:, 0].astype(np.int8)48 if k is None:49 self.x = []50 for x in matx[:size]:51 self.x.append(imresize(x, self.img_size)[np.newaxis, ...])52 self.x = np.array(self.x, dtype=np.float32)53 self.y = maty[:size]54 else:55 self.x, self.y = [], []56 counter = defaultdict(int)57 n, i = 0, 058 while n < k * 10:59 x = imresize(matx[n], self.img_size)[np.newaxis, ...]60 y = maty[n]61 if counter[y] < k:62 self.x.append(x)63 self.y.append(y)64 n += 165 i += 166 self.x = np.array(self.x, dtype=np.float32)67 def __len__(self):68 return 11000#len(self.x)69 def get_example(self, i):70 i = i % len(self.x)71 return self.x[i], self.y[i]72class USPSDataset(dataset_mixin.DatasetMixin):73 img_size = (28, 28)74 n_classes = 1075 def __init__(self):76 mat = io.loadmat('./datasets/usps_all.mat')77 self.data = mat['data']78 def __len__(self):79 return 1100 * 1080 def get_example(self, i):81 ix = i // 1082 y = i % 1083 x = imresize(self.data[:, ix, y].reshape(16, 16), self.img_size)[np.newaxis, ...]84 return x, y85class MNIST_MDataset(dataset_mixin.DatasetMixin):86 img_size = (28, 28)87 n_classes = 1088 def __init__(self, data_root=os.path.join(dataset_path, 'mnist_m'), src='train', transform=None):89 self.transform = transform90 if src == 'train':91 data_list = os.path.join(data_root, 'mnist_m_train_labels.txt')92 self.root = os.path.join(data_root, 'mnist_m_train')93 elif src == 'test':94 data_list = os.path.join(data_root, 'mnist_m_test_labels.txt')95 self.root = os.path.join(data_root, 'mnist_m_test')96 else:97 raise ValueError98 f = open(data_list, 'r')99 data_list = f.readlines()100 f.close()101 self.n_data = len(data_list)102 self.img_paths = []103 self.img_labels = []104 for data in data_list:105 self.img_paths.append(data[:-3])106 self.img_labels.append(data[-2])107 def get_example(self, item):108 img_paths, labels = self.img_paths[item], self.img_labels[item]109 imgs = Image.open(os.path.join(self.root, img_paths)).convert('RGB')110 img = imresize(np.array(imgs), self.img_size).transpose(2, 0, 1).astype(np.float32)111 # nch 3 -> 1112 img = img.mean(axis=0)[np.newaxis, ...]113 if self.transform is not None:114 img = self.transform(img)115 labels = int(labels)116 return img, labels117 def __len__(self):118 return self.n_data119class CrossDomainDigitDataset(dataset_mixin.DatasetMixin):120 img_size = (28, 28)121 n_classes = 10122 def __init__(self, datasets, return_domain=True):123 self.n_domain = len(datasets)124 self.datasets = datasets125 self.return_domain = return_domain126 def get_example(self, i, r=None):127 if r is None:128 r = np.random.randint(self.n_domain)129 x, y = self.datasets[r][i]130 if self.return_domain:131 return x.astype(np.float32), y, r132 else:133 return x.astype(np.float32), y134 def __len__(self):135 return min(map(len, self.datasets))136if __name__ == '__main__':137 # m = RotateMnistDataset()138 # x, y, r = m.get_example(0, r=0)139 # imsave('./png/0.png', np.tile(x.transpose(1, 2, 0), (1, 1, 3)))140 # x, y, r = m.get_example(0, r=1)141 # imsave('./png/1.png', np.tile(x.transpose(1, 2, 0), (1, 1, 3)))142 # x, y, r = m.get_example(0, r=4)143 # imsave('./png/4.png', np.tile(x.transpose(1, 2, 0), (1, 1, 3)))144 mnist_train, test = get_mnist(ndim=3)145 mnist_m = MNIST_MDataset()146 svhn = SVHNDataset()147 usps = USPSDataset()148 digits = CrossDomainDigitDataset(datasets=[mnist_train, mnist_m, svhn, usps])149 print(len(digits))150 x, y, r = digits.get_example(0, r=0)151 print(x.shape, y, r)152 x, y, r = digits.get_example(1, r=1)153 print(x.shape, y, r)154 x, y, r = digits.get_example(2, r=2)155 print(x.shape, y, r)156 x, y, r = digits.get_example(3, r=3)...
metrics_tests.py
Source:metrics_tests.py
...11 averaged_r_squared,12 overall_censored_mape,13 averaged_censored_mape14)15def get_example() -> pd.DataFrame():16 """17 Get example of DataFrame with actual values and predictions.18 :return:19 example DataFrame20 """21 df = pd.DataFrame(22 [[1, 2, 3],23 [1, 4, 5],24 [2, 10, 8],25 [2, 8, 10]],26 columns=['key', 'actual_value', 'prediction']27 )28 return df29class TestMetrics(unittest.TestCase):30 """31 Tests of evaluational metrics.32 """33 def test_overall_r_squared(self) -> type(None):34 """35 Test `overall_r_squared` function.36 :return:37 None38 """39 df = get_example()40 score = overall_r_squared(df)41 self.assertEquals(score, 0.75)42 def test_averaged_r_squared(self) -> type(None):43 """44 Test `averaged_r_squared` function.45 :return:46 None47 """48 df = get_example()49 score = averaged_r_squared(df, ['key'])50 self.assertEquals(score, -1.5)51 def test_overall_censored_mape(self) -> type(None):52 """53 Test `overall_censored_mape` function.54 :return:55 None56 """57 df = get_example()58 score = overall_censored_mape(df)59 self.assertEquals(score, 30)60 def test_overall_censored_mape_with_zeros(self) -> type(None):61 """62 Test correct work of `overall_censored_mape` function63 with zero forecasts made for zero actual values.64 :return:65 None66 """67 first_df = get_example()68 second_df = pd.DataFrame(69 [[3, 0, 0],70 [3, 0, 0],71 [4, 0, 0],72 [4, 0, 0]],73 columns=['key', 'actual_value', 'prediction']74 )75 df = pd.concat([first_df, second_df])76 score = overall_censored_mape(df)77 self.assertEquals(score, 15)78 def test_overall_censored_mape_with_missings(self) -> type(None):79 """80 Test correct work of `overall_censored_mape` function81 with some values missed.82 :return:83 None84 """85 df = get_example()86 df.loc[0, 'prediction'] = None87 df.loc[1, 'actual_value'] = np.nan88 score = overall_censored_mape(df)89 self.assertEquals(score, 22.5)90 def test_averaged_censored_mape(self) -> type(None):91 """92 Test `averaged_r_censored_mape` function.93 :return:94 None95 """96 df = get_example()97 score = averaged_censored_mape(df, ['key'])98 self.assertEquals(score, 30)99 def test_averaged_censored_mape_with_empty_series(self) -> type(None):100 """101 Test correct work of `overall_censored_mape` function102 with DataFrame that contains an empty time series.103 :return:104 None105 """106 df = get_example()107 df.loc[0, 'prediction'] = None108 df.loc[1, 'actual_value'] = np.nan109 score = averaged_censored_mape(df, ['key'])110 self.assertEquals(score, 22.5)111def main():112 test_loader = unittest.TestLoader()113 suites_list = []114 testers = [115 TestMetrics()116 ]117 for tester in testers:118 suite = test_loader.loadTestsFromModule(tester)119 suites_list.append(suite)120 overall_suite = unittest.TestSuite(suites_list)...
dataset_mixin.py
Source:dataset_mixin.py
...29 ... def __init__(self, values):30 ... self.values = values31 ... def __len__(self):32 ... return len(self.values)33 ... def get_example(self, i):34 ... return self.values[i]35 ...36 >>> ds = SimpleDataset([0, 1, 2, 3, 4, 5])37 >>> ds[1] # Access by int38 139 >>> ds[1:3] # Access by slice40 [1, 2]41 >>> ds[[4, 0]] # Access by one-dimensional integer list42 [4, 0]43 >>> index = numpy.arange(3)44 >>> ds[index] # Access by one-dimensional integer numpy.ndarray45 [0, 1, 2]46 """47 if isinstance(index, slice):48 current, stop, step = index.indices(len(self))49 return [self.get_example(i) for i in50 six.moves.range(current, stop, step)]51 elif isinstance(index, list) or isinstance(index, numpy.ndarray):52 return [self.get_example(i) for i in index]53 else:54 return self.get_example(index)55 def __len__(self):56 """Returns the number of data points."""57 raise NotImplementedError58 def get_example(self, i):59 """Returns the i-th example.60 Implementations should override it. It should raise :class:`IndexError`61 if the index is invalid.62 Args:63 i (int): The index of the example.64 Returns:65 The i-th example.66 """...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!