Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/Natural Language Processing with Attention Models/Week 4 - Chatbot/w4_unittest.py
Views: 13373
import numpy as np1import trax2#from trax import layers as tl3#from trax.fastmath import numpy as fastnp4#from trax.supervised import training56# UNIT TEST for UNQ_C17def test_get_conversation(target):89data = {'file1.json': {'log':[{'text': 'hi'},10{'text': 'hello'},11{'text': 'nice'}]},12'file2.json':{'log':[{'text': 'a b'},13{'text': ''},14{'text': 'good '},15{'text': 'no?'}]}}1617res1 = target('file1.json', data)18res2 = target('file2.json', data)1920expected1 = ' Person 1: hi Person 2: hello Person 1: nice'21expected2 = ' Person 1: a b Person 2: Person 1: good Person 2: no?'2223success = 024fails = 02526try:27assert res1 == expected128success += 129except ValueError:30print('Error in test 1 \nResult : ', res1, 'x \nExpected: ', expected1)31fails += 132try:33assert res2 == expected234success += 135except:36print('Error in test 2 \nResult : ', res2, ' \nExpected: ', expected2)37fails += 13839if fails == 0:40print("\033[92m All tests passed")41else:42print('\033[92m', success," Tests passed")43print('\033[91m', fails, " Tests failed")444546# UNIT TEST for UNQ_C247def test_reversible_layer_forward(target):48f1 = lambda x: x + 249g1 = lambda x: x * 35051f2 = lambda x: x + 152g2 = lambda x: x * 25354input_vector1 = np.array([1, 2, 3, 4, 5, 6, 7, 8])55expected1 = np.array([8, 10, 12, 14, 29, 36, 43, 50])5657input_vector2 = np.array([1] * 128)58expected2 = np.array([3] * 64 + [7] * 64)5960success = 061fails = 062try:63res = target(input_vector1, f1, g1)64assert isinstance(res, np.ndarray)65success += 166except:67print('Wrong type! Output is not of type np.ndarray')68fails += 169try:70res = target(input_vector1, f1, g1)71assert np.allclose(res, expected1)72success += 173except ValueError:74print('Error in test 1 \nResult : ', res, 'x \nExpected: ', expected1)75fails += 176try:77res = target(input_vector2, f2, g2)78assert np.allclose(res, expected2)79success += 180except:81print('Error in test 2 \nResult : ', res, ' \nExpected: ', expected2)82fails += 18384if fails == 0:85print("\033[92m All tests passed")86else:87print('\033[92m', success," Tests passed")88print('\033[91m', fails, " Tests failed")899091# UNIT TEST for UNQ_C392def test_reversible_layer_reverse(target):9394f1 = lambda x: x + 295g1 = lambda x: x * 39697f2 = lambda x: x + 198g2 = lambda x: x * 299100input_vector1 = np.array([1, 2, 3, 4, 5, 6, 7, 8])101expected1 = np.array([-3, 0, 3, 6, 2, 0, -2, -4])102103input_vector2 = np.array([1] * 128)104expected2 = np.array([1] * 64 + [-1] * 64)105106success = 0107fails = 0108try:109res = target(input_vector1, f1, g1)110assert isinstance(res, np.ndarray)111success += 1112except:113print('Wrong type! Output is not of type np.ndarray')114fails += 1115try:116res = target(input_vector1, f1, g1)117assert np.allclose(res, expected1)118success += 1119except ValueError:120print('Error in test 1 \nResult : ', res, 'x \nExpected: ', expected1)121fails += 1122try:123res = target(input_vector2, f2, g2)124assert np.allclose(res, expected2)125success += 1126except:127print('Error in test 2 \nResult : ', res, ' \nExpected: ', expected2)128fails += 1129130if fails == 0:131print("\033[92m All tests passed")132else:133print('\033[92m', success," Tests passed")134print('\033[91m', fails, " Tests failed")135136137# UNIT TEST for UNQ_C4138def test_ReformerLM(target):139test_cases = [140{141"name":"layer_len_check",142"expected":11,143"error":"We found {} layers in your model. It should be 11.\nCheck the LSTM stack before the dense layer"144},145{146"name":"simple_test_check",147"expected":"Serial[ShiftRight(1)Embedding_train_512DropoutPositionalEncodingDup_out2ReversibleSerial_in2_out2[ReversibleHalfResidualV2_in2_out2[Serial[LayerNorm]SelfAttention]ReversibleSwap_in2_out2ReversibleHalfResidualV2_in2_out2[Serial[LayerNormDense_2048DropoutFastGeluDense_512Dropout]]ReversibleSwap_in2_out2ReversibleHalfResidualV2_in2_out2[Serial[LayerNorm]SelfAttention]ReversibleSwap_in2_out2ReversibleHalfResidualV2_in2_out2[Serial[LayerNormDense_2048DropoutFastGeluDense_512Dropout]]ReversibleSwap_in2_out2]Concatenate_in2LayerNormDropoutDense_trainLogSoftmax]",148"error":"The ReformerLM is not defined properly."149}150]151temp_model = target('train')152153success = 0154fails = 0155156for test_case in test_cases:157try:158if test_case['name'] == "simple_test_check":159assert test_case["expected"] == str(temp_model).replace(' ', '').replace('\n','')160success += 1161if test_case['name'] == "layer_len_check":162if test_case["expected"] == len(temp_model.sublayers):163success += 1164else:165print(test_case["error"].format(len(temp_model.sublayers)))166fails += 1167except:168print(test_case['error'])169fails += 1170171if fails == 0:172print("\033[92m All tests passed")173else:174print('\033[92m', success," Tests passed")175print('\033[91m', fails, " Tests failed")176177178# UNIT TEST for UNQ_C5179def test_tasks(train_task, eval_task):180target = train_task181success = 0182fails = 0183184# Test the labeled data parameter for train_task185try:186strlabel = str(target._labeled_data)187assert ("generator" in strlabel) and ("add_loss_weights" in strlabel)188success += 1189except:190fails += 1191print("Wrong labeled data parameter in train_task")192193# Test the cross entropy loss data parameter194try:195strlabel = str(target._loss_layer)196assert(strlabel == "CrossEntropyLoss_in3")197success += 1198except:199fails += 1200print("Wrong loss functions. CrossEntropyLoss_in3 was expected")201202# Test the optimizer parameter203try:204assert(isinstance(target.optimizer, trax.optimizers.adam.Adam))205success += 1206except:207fails += 1208print("Wrong optimizer")209210# Test the schedule parameter211try:212assert(isinstance(target._lr_schedule,trax.supervised.lr_schedules._BodyAndTail))213success += 1214except:215fails += 1216print("Wrong learning rate schedule type")217218# Test the _n_steps_per_checkpoint parameter219try:220assert(target._n_steps_per_checkpoint==10)221success += 1222except:223fails += 1224print("Wrong checkpoint step frequency")225226target = eval_task227# Test the labeled data parameter for eval_task228try:229strlabel = str(target._labeled_data)230assert ("generator" in strlabel) and ("add_loss_weights" in strlabel)231success += 1232except:233fails += 1234print("Wrong labeled data parameter in eval_task")235236# Test the metrics in eval_task237try:238strlabel = str(target._metrics).replace(' ', '')239assert(strlabel == "[CrossEntropyLoss_in3,Accuracy_in3]")240success += 1241except:242fails += 1243print(f"Wrong metrics. found {strlabel} but expected [CrossEntropyLoss_in3,Accuracy_in3]")244245246if fails == 0:247print("\033[92m All tests passed")248else:249print('\033[92m', success," Tests passed")250print('\033[91m', fails, " Tests failed")251252253254255