Best Python code snippet using green
lift_test.py
Source:lift_test.py
...22from tensorflow_model_analysis.eval_saved_model import testutil23from tensorflow_model_analysis.metrics import metric_types24from tensorflow_model_analysis.metrics import metric_util25class LiftTest(testutil.TensorflowModelAnalysisTest, parameterized.TestCase):26 def _assert_test(self,27 num_buckets,28 baseline_examples,29 comparison_examples,30 lift_metric_value,31 ignore_out_of_bound_examples=False):32 eval_config = config.EvalConfig(33 cross_slicing_specs=[config.CrossSlicingSpec()])34 computations = lift.Lift(35 num_buckets=num_buckets,36 ignore_out_of_bound_examples=ignore_out_of_bound_examples).computations(37 eval_config=eval_config)38 histogram = computations[0]39 lift_metrics = computations[1]40 with beam.Pipeline() as pipeline:41 # pylint: disable=no-value-for-parameter42 baseline_result = (43 pipeline44 | 'CreateB' >> beam.Create(baseline_examples)45 | 'ProcessB' >> beam.Map(metric_util.to_standard_metric_inputs)46 | 'AddSliceB' >> beam.Map(lambda x: ((), x))47 | 'ComputeHistogramB' >> beam.CombinePerKey(histogram.combiner)48 ) # pyformat: ignore49 comparison_result = (50 pipeline51 | 'CreateC' >> beam.Create(comparison_examples)52 | 'ProcessC' >> beam.Map(metric_util.to_standard_metric_inputs)53 | 'AddSliceC' >> beam.Map(lambda x: (('slice'), x))54 | 'ComputeHistogramC' >> beam.CombinePerKey(histogram.combiner)55 ) # pyformat: ignore56 # pylint: enable=no-value-for-parameter57 merged_result = ((baseline_result, comparison_result)58 | 'MergePCollections' >> beam.Flatten())59 def check_result(got):60 try:61 self.assertLen(got, 2)62 slice_1, metric_1 = got[0]63 slice_2, metric_2 = got[1]64 lift_value = None65 if not slice_1:66 lift_value = lift_metrics.cross_slice_comparison(metric_1, metric_2)67 else:68 lift_value = lift_metrics.cross_slice_comparison(metric_2, metric_1)69 self.assertDictElementsAlmostEqual(70 lift_value, {71 metric_types.MetricKey(name=f'lift@{num_buckets}'):72 lift_metric_value,73 })74 except AssertionError as err:75 raise util.BeamAssertException(err)76 util.assert_that(merged_result, check_result, label='result')77 def testLift_continuousLabelsAndPredictions(self):78 baseline_examples = [{79 'labels': np.array([0.0]),80 'predictions': np.array([0.1]),81 'example_weights': np.array([3.0]),82 }, {83 'labels': np.array([0.3]),84 'predictions': np.array([0.5]),85 'example_weights': np.array([5.0]),86 }, {87 'labels': np.array([0.6]),88 'predictions': np.array([0.8]),89 'example_weights': np.array([2.0]),90 }, {91 'labels': np.array([0.9]),92 'predictions': np.array([0.3]),93 'example_weights': np.array([8.0]),94 }, {95 'labels': np.array([0.9]),96 'predictions': np.array([0.9]),97 'example_weights': np.array([3.0]),98 }]99 comparison_examples = [{100 'labels': np.array([0.0]),101 'predictions': np.array([0.8]),102 'example_weights': np.array([1.0]),103 }, {104 'labels': np.array([0.2]),105 'predictions': np.array([0.3]),106 'example_weights': np.array([2.0]),107 }, {108 'labels': np.array([0.5]),109 'predictions': np.array([0.5]),110 'example_weights': np.array([5.0]),111 }, {112 'labels': np.array([0.7]),113 'predictions': np.array([0.4]),114 'example_weights': np.array([2.0]),115 }, {116 'labels': np.array([0.9]),117 'predictions': np.array([0.3]),118 'example_weights': np.array([3.0]),119 }]120 self._assert_test(3, baseline_examples, comparison_examples, -0.136013986)121 def testLift_baselineAndComparisonAreSame(self):122 baseline_examples = [{123 'labels': np.array([0.0]),124 'predictions': np.array([0.1]),125 'example_weights': np.array([3.0]),126 }, {127 'labels': np.array([0.3]),128 'predictions': np.array([0.5]),129 'example_weights': np.array([5.0]),130 }, {131 'labels': np.array([0.6]),132 'predictions': np.array([0.8]),133 'example_weights': np.array([2.0]),134 }, {135 'labels': np.array([0.9]),136 'predictions': np.array([0.3]),137 'example_weights': np.array([8.0]),138 }, {139 'labels': np.array([1.0]),140 'predictions': np.array([0.9]),141 'example_weights': np.array([3.0]),142 }]143 self._assert_test(3, baseline_examples, baseline_examples, 0.0)144 def testLift_ignoringOutOfBoundExamples(self):145 baseline_examples = [146 {147 'labels': np.array([0.0]),148 'predictions': np.array([0.1]),149 'example_weights': np.array([3.0]),150 },151 {152 'labels': np.array([0.3]),153 'predictions': np.array([0.5]),154 'example_weights': np.array([5.0]),155 },156 {157 'labels': np.array([0.6]),158 'predictions': np.array([0.8]),159 'example_weights': np.array([2.0]),160 },161 {162 'labels': np.array([0.9]),163 'predictions': np.array([0.3]),164 'example_weights': np.array([8.0]),165 },166 {167 'labels': np.array([-0.9]), # Ignore this example168 'predictions': np.array([0.3]),169 'example_weights': np.array([8.0]),170 },171 {172 'labels': np.array([0.9]),173 'predictions': np.array([0.9]),174 'example_weights': np.array([3.0]),175 }176 ]177 comparison_examples = [178 {179 'labels': np.array([0.0]),180 'predictions': np.array([0.8]),181 'example_weights': np.array([1.0]),182 },183 {184 'labels': np.array([0.2]),185 'predictions': np.array([0.3]),186 'example_weights': np.array([2.0]),187 },188 {189 'labels': np.array([0.5]),190 'predictions': np.array([0.5]),191 'example_weights': np.array([5.0]),192 },193 {194 'labels': np.array([0.7]),195 'predictions': np.array([0.4]),196 'example_weights': np.array([2.0]),197 },198 {199 'labels': np.array([1.9]), # Ignore this example200 'predictions': np.array([0.3]),201 'example_weights': np.array([8.0]),202 },203 {204 'labels': np.array([0.9]),205 'predictions': np.array([0.3]),206 'example_weights': np.array([3.0]),207 }208 ]209 self._assert_test(210 3,211 baseline_examples,212 comparison_examples,213 -0.136013986,214 ignore_out_of_bound_examples=True)215 def testLift_binaryLabelsAndContinuousPredictions(self):216 baseline_examples = [{217 'labels': np.array([0.0]),218 'predictions': np.array([0.1]),219 'example_weights': np.array([3.0]),220 }, {221 'labels': np.array([0.0]),222 'predictions': np.array([0.5]),223 'example_weights': np.array([5.0]),224 }, {225 'labels': np.array([1.0]),226 'predictions': np.array([0.8]),227 'example_weights': np.array([2.0]),228 }, {229 'labels': np.array([1.0]),230 'predictions': np.array([0.3]),231 'example_weights': np.array([8.0]),232 }, {233 'labels': np.array([1.0]),234 'predictions': np.array([0.9]),235 'example_weights': np.array([3.0]),236 }]237 comparison_examples = [{238 'labels': np.array([0.0]),239 'predictions': np.array([0.8]),240 'example_weights': np.array([1.0]),241 }, {242 'labels': np.array([0.0]),243 'predictions': np.array([0.3]),244 'example_weights': np.array([2.0]),245 }, {246 'labels': np.array([0.0]),247 'predictions': np.array([0.5]),248 'example_weights': np.array([5.0]),249 }, {250 'labels': np.array([1.0]),251 'predictions': np.array([0.4]),252 'example_weights': np.array([2.0]),253 }, {254 'labels': np.array([1.0]),255 'predictions': np.array([0.3]),256 'example_weights': np.array([3.0]),257 }]258 self._assert_test(2, baseline_examples, comparison_examples, 0.01715976331)259 def testLift_binaryLabelsAndPredictions(self):260 baseline_examples = [{261 'labels': np.array([0.0]),262 'predictions': np.array([1.0]),263 'example_weights': np.array([3.0]),264 }, {265 'labels': np.array([0.0]),266 'predictions': np.array([0.0]),267 'example_weights': np.array([5.0]),268 }, {269 'labels': np.array([1.0]),270 'predictions': np.array([0.0]),271 'example_weights': np.array([2.0]),272 }, {273 'labels': np.array([1.0]),274 'predictions': np.array([1.0]),275 'example_weights': np.array([8.0]),276 }, {277 'labels': np.array([1.0]),278 'predictions': np.array([0.0]),279 'example_weights': np.array([3.0]),280 }]281 comparison_examples = [{282 'labels': np.array([0.0]),283 'predictions': np.array([1.0]),284 'example_weights': np.array([1.0]),285 }, {286 'labels': np.array([0.0]),287 'predictions': np.array([0.0]),288 'example_weights': np.array([2.0]),289 }, {290 'labels': np.array([0.0]),291 'predictions': np.array([1.0]),292 'example_weights': np.array([5.0]),293 }, {294 'labels': np.array([1.0]),295 'predictions': np.array([0.0]),296 'example_weights': np.array([2.0]),297 }, {298 'labels': np.array([1.0]),299 'predictions': np.array([1.0]),300 'example_weights': np.array([3.0]),301 }]302 self._assert_test(2, baseline_examples, comparison_examples, 0.224852071)303 def testLift_raisesExceptionWhenEvalConfigIsNone(self):304 with self.assertRaises(ValueError):305 _ = lift.Lift(num_buckets=3).computations()306 def testLift_raisesExceptionWhenCrossSlicingSpecIsAbsent(self):307 with self.assertRaises(ValueError):308 _ = lift.Lift(num_buckets=3).computations(eval_config=config.EvalConfig())309if __name__ == '__main__':...
scc.py
Source:scc.py
...85 for k in d1:86 if sorted(d1[k]) != sorted(d2[k]):87 return False88 return True89def _assert_test(g, expected_counts, expected_groups = None):90 groups = scc(g)91 if expected_groups:92 assert _assert_dict_equal(groups, expected_groups), '%s -- %s' % (expected_groups, groups)93 assert count_len(groups) == expected_counts, '%s -- %s' % (expected_counts,94 count_len(groups))95 nodes = set()96 for s in g:97 nodes.add(s)98 for t in g[s]:99 nodes.add(t)100 assert sum(count_len(groups)) == len(nodes), '%s -- %s' % (sum(count_len(groups)), len(nodes))101 def _same_group(groups, s, t):102 """Return true if s and t are in the same group."""103 for group in groups.values():104 if s in group and t in group:105 return True106 return False107 def _is_connected(g, s, t):108 explored = {}109 def _dsf(g, i):110 explored[i] = True111 if i in g:112 for j in g[i]:113 if j not in explored:114 _dsf(g, j)115 _dsf(g, s)116 return t in explored117 for s in nodes:118 for t in nodes:119 s_to_t = _is_connected(g, s, t)120 t_to_s = _is_connected(g, t, s)121 # print '%s -> %s: %s, %s -> %s: %s' % (s, t, s_to_t, s, t, t_to_s)122 # print 'is same group: %s' % (_same_group(groups, s, t))123 if _same_group(groups, s, t):124 assert s_to_t and t_to_s, '%s and %s should be in same group. %s' % (s, t, groups)125 else:126 assert not s_to_t or not t_to_s, '%s and %s should not be in the same group. %s' % (s, t, groups)127def test1():128 g ={1: [7],129 7: [4, 9],130 4: [1],131 9: [6],132 6: [3, 8],133 3: [9],134 8: [2],135 2: [5],136 5: [8],137 }138 _assert_test(g,139 [3, 3, 3],140 {1: [1, 4, 7],141 2: [2, 5, 8],142 6: [6, 3, 9]})143 g = {1: [2],144 2: [3],145 3: [1, 4]}146 _assert_test(g,147 [3, 1],148 {1: [3, 2, 1], 4: [4]})149 g = {1: [2, 2],150 2: [3, 1],151 3: [4, 2, 2]}152 _assert_test(g,153 [3, 1],154 {1: [1, 2, 3], 4: [4]})155 g = {2: [46, 15],156 46: [15, 9],157 15: [9],158 }159 _assert_test(g,160 [1, 1, 1, 1])161def tests():162 g = read_input('test1.txt')163 expected = {1: [6, 3, 5, 1],164 2: [10, 4, 2],165 11: [11],166 9: [8, 7, 9]}167 _assert_test(g,168 [4, 3, 3, 1],169 expected)170 g = read_input('test2.txt')171 expected = {1: [5, 2, 1],172 3: [8, 4, 3],173 6: [7, 6]}174 _assert_test(g,175 [3, 3, 2],176 expected)177 g = read_input('test3.txt')178 _assert_test(g,179 [6, 3, 2, 1])180 g = read_input('test4.txt')181 _assert_test(g,182 [35, 7, 1, 1, 1, 1, 1, 1, 1, 1])183 g = read_input('test5.txt')184 _assert_test(g,[36, 7, 1, 1, 1, 1, 1, 1, 1])185 g = read_input('test6.txt')186 _assert_test(g, [8, 5, 2, 1])187 g = read_input('test7.txt')188 _assert_test(g, [3, 3, 3, 1])189 g = read_input('test8.txt')190 _assert_test(g, [3, 3, 3, 1])191def random_tests(test_cnt=300):192 for _ in xrange(test_cnt):193 problem_size = random.randint(2, 500)194 g = {}195 for s in range(1, problem_size+1):196 g[s] = []197 for t in range(1, problem_size + 1):198 if s == t: continue199 if random.randint(1, 300) < 100:200 g[s].append(t)201 groups1 = scc(g, 'stack')202 groups2 = scc(g, 'rec')203 assert _assert_dict_equal(groups1, groups2), '%s \n%s\n%s' % (g, groups1, groups2)204def read_input(filename):...
code_challenge.py
Source:code_challenge.py
...20 ([9,10,19,13,19,13],19),21 ([16,0,11,4,8,16,0,11],12),22 ([5,17, 18, 11, 13, 18, 11, 13],22),23 ([5,10,19,13,10,13],24)]24 _assert_test(tests, repeats)25 26def capitalize(string):27 even_altered = "".join([ s.upper() if i % 2 == 0 else s 28 for i,s in enumerate(string)])29 return [even_altered, even_altered.swapcase()]30def test_capitalize():31 tests = [32 ("abcdef", ['AbCdEf', 'aBcDeF']),33 ("codewars", ['CoDeWaRs', 'cOdEwArS']),34 ("abracadabra", ['AbRaCaDaBrA', 'aBrAcAdAbRa'])]35 _assert_test(tests, capitalize)36def isPrime(num):37 from math import sqrt38 return num >=2 and not [n for n in range(2, int(sqrt(num))) if num % n == 0]39def maxMultiple(divisor, bound):40 for n in range(bound,0,-1):41 if n % divisor == 0:42 return n43 return max([n for n in range(bound, 0, -1) if n % divisor == 0])44def test_maxMultiple():45 tests = [46 ((2,7),6),47 ((3,10),9),48 ((7,17),14),49 ((10,50),50),50 ((37,200),185),51 ((7,100),98)]52 53 _assert_test(tests, maxMultiple)54def _assert_test(input_expect_arr, func):55 for test_input, expected in input_expect_arr:56 print(test_input,expected, func(*test_input))57 assert func(*test_input) == expected58def main():59 #test_maxMultiple()60 stringify_list([8, 11,12,13,14,15, 25,72,88])61if __name__ == '__main__':...
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!!