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/Custom Models, Layers, and Loss Functions with TensorFlow/Week 1 - Functional APIs/utils.py
Views: 13371
import numpy as np1import tensorflow as tf2from tensorflow.keras.models import Model3from tensorflow.keras.layers import Dense, Input4from sklearn.model_selection import train_test_split56def test_loop(test_cases):78success = 09fails = 01011for test_case in test_cases:12try:13assert test_case["result"] == test_case["expected"]14success += 11516except:17fails += 118print(f'{test_case["name"]}: {test_case["error_message"]}\nExpected: {test_case["expected"]}\nResult: {test_case["result"]}\nPlease open utils.py if you want to see the unit test here.\n')1920if fails == 0:21print("\033[92m All public tests passed")2223else:24print('\033[92m', success," Tests passed")25print('\033[91m', fails, " Tests failed")26raise Exception(test_case["error_message"])2728def test_white_df(white_df):2930test_cases = [31{32"name": "type_check",33"result": type(white_df.is_red[0]),34"expected": np.int64,35"error_message": f'white_df.is_red has an incorrect type.'36},37{38"name": "output_check",39"result": white_df.is_red[0],40"expected": 0,41"error_message": "white_df.is_red is not set correctly"42},43{44"name": "len_check",45"result": len(white_df),46"expected": 3961,47"error_message": "Number of rows is incorrect. Please drop duplicates."48}49]5051test_loop(test_cases)5253def test_red_df(red_df):5455test_cases = [56{57"name": "type_check",58"result": type(red_df.is_red[0]),59"expected": np.int64,60"error_message": f'red_df.is_red has an incorrect type.'61},62{63"name": "output_check",64"result": red_df.is_red[0],65"expected": 1,66"error_message": "red_df.is_red is not set correctly"67},68{69"name": "len_check",70"result": len(red_df),71"expected": 1359,72"error_message": "Number of rows is incorrect. Please drop duplicates."73}74]7576test_loop(test_cases)7778def test_df_drop(df):7980test_cases = [81{82"name": "df.alcohol[0]_check",83"result": df.alcohol[0],84"expected": 9.4,85"error_message": f'Value is not as expected. Please check quality interval.'86},87{88"name": "df.alcohol[100]_check",89"result": df.alcohol[100],90"expected": 10.9,91"error_message": f'Value is not as expected. Please check quality interval.'92}93]9495test_loop(test_cases)9697def test_data_sizes(train_size, test_size, val_size):9899test_cases = [100{101"name": "train_test_size_check",102"result": train_size > test_size,103"expected": True,104"error_message": f'train.size is too small. Please check implementation.'105},106{107"name": "train_val_size_check",108"result": train_size > val_size,109"expected": True,110"error_message": f'train.size is too small. Please check implementation.'111},112{113"name": "test_val_size_check",114"result": test_size > val_size,115"expected": True,116"error_message": f'test.size is too small. Please check implementation.'117}118]119120test_loop(test_cases)121122def test_format_output(df, train_Y, val_Y, test_Y):123124train, test = train_test_split(df, test_size=0.2, random_state=1)125train, val = train_test_split(train, test_size=0.2, random_state=1)126127test_cases = [128{129"name": "train_Y[0]_check",130"result": np.all(train_Y[0] == np.array(train.quality)),131"expected": True,132"error_message": f'train_Y[0] is not equal to train.quality. Please check implementation.'133},134{135"name": "train_Y[1]_check",136"result": np.all(train_Y[1] == np.array(train.is_red)),137"expected": True,138"error_message": f'train_Y[1] is not equal to train.is_red. Please check implementation.'139},140{141"name": "val_Y[0]_check",142"result": np.all(val_Y[0] == np.array(val.quality)),143"expected": True,144"error_message": f'train_Y[0] is not equal to val.quality. Please check implementation.'145},146{147"name": "val_Y[1]_check",148"result": np.all(val_Y[1] == np.array(val.is_red)),149"expected": True,150"error_message": f'train_Y[1] is not equal to val.is_red. Please check implementation.'151},152{153"name": "test_Y[0]_check",154"result": np.all(test_Y[0] == np.array(test.quality)),155"expected": True,156"error_message": f'test_Y[0] is not equal to test.quality. Please check implementation.'157},158{159"name": "test_Y[1]_check",160"result": np.all(test_Y[1] == np.array(test.is_red)),161"expected": True,162"error_message": f'test_Y[1] is not equal to test.is_red. Please check implementation.'163}164]165166test_loop(test_cases)167168def test_norm(norm_train_X, norm_val_X, norm_test_X, train, val, test):169170from pandas.core.frame import DataFrame171172test_cases = [173{174"name": "norm_train_X_type_check",175"result": type(norm_train_X),176"expected": DataFrame,177"error_message": f'norm_train_X has an incorrect type.'178},179{180"name": "norm_val_X_type_check",181"result": type(norm_val_X),182"expected": DataFrame,183"error_message": f'norm_val_X has an incorrect type.'184},185{186"name": "norm_test_X_type_check",187"result": type(norm_test_X),188"expected": DataFrame,189"error_message": f'norm_test_X has an incorrect type.'190},191{192"name": "norm_train_X_length_check",193"result": len(norm_train_X),194"expected": len(train),195"error_message": f'norm_train_X has an incorrect length.'196},197{198"name": "norm_val_X_length_check",199"result": len(norm_val_X),200"expected": len(val),201"error_message": f'norm_val_X has an incorrect length.'202},203{204"name": "norm_test_X_length_check",205"result": len(norm_test_X),206"expected": len(test),207"error_message": f'norm_test_X has an incorrect length.'208},209]210211test_loop(test_cases)212213def test_base_model(base_model):214215test_inputs = tf.keras.layers.Input(shape=(11,))216test_output = base_model(test_inputs)217test_model = Model(inputs=test_inputs, outputs=test_output)218219test_cases = [220{221"name": "return_type_check",222"result": type(test_output),223"expected": tf.Tensor,224"error_message": 'Return type is incorrect. Please check implementation.'225},226{227"name": "return_shape_check",228"result": str(test_output.shape),229"expected": '(None, 128)',230"error_message": 'Return shape is incorrect. Please check implementation.'231},232{233"name": "tensor_dtype_check",234"result": str(test_output.dtype),235"expected": "<dtype: 'float32'>",236"error_message": 'model dtype is incorrect. Please check implementation.'237},238{239"name": "base_model_num_layers_check",240"result": len(test_model.layers),241"expected": 3,242"error_message": 'There are too many layers. Please check implementation.'243},244{245"name": "base_model_layer1_check",246"result": type(test_model.layers[-2]),247"expected": Dense,248"error_message": 'First layer type is incorrect. Please check implementation.'249},250{251"name": "base_model_layer2_check",252"result": type(test_model.layers[-1]),253"expected": Dense,254"error_message": 'Output layer type is incorrect. Please check implementation.'255},256]257258test_loop(test_cases)259260def test_final_model(final_model):261262test_inputs = tf.keras.layers.Input(shape=(11,))263test_output = final_model(test_inputs)264265test_cases = [266{267"name": "return_type_check",268"result": type(test_output),269"expected": tf.keras.Model,270"error_message": 'Return type is incorrect. Please check implementation.'271},272{273"name": "layer_3_activation_check",274"result": test_output.layers[4].activation,275"expected": tf.keras.activations.sigmoid,276"error_message": 'wine_quality layer has an incorrect activation. Please check implementation.'277},278]279280test_loop(test_cases)281282def test_model_compile(model):283284from tensorflow.python.keras.metrics import MeanMetricWrapper285286test_cases = [287{288"name": "metrics_0_check",289"result": type(model.metrics[0]),290"expected": tf.keras.metrics.RootMeanSquaredError,291"error_message": 'wine quality metrics is incorrect. Please check implementation.'292},293{294"name": "metrics_1_check",295"result": (model.metrics[1].name == 'wine_type_accuracy') or296(model.metrics[1].name == 'wine_type_binary_accuracy'),297"expected": True,298"error_message": f'wine type metrics: {model.metrics[1].name} is incorrect. Please check implementation.'299},300{301"name": "wine_type_loss_check",302"result": (model.loss['wine_type'] == 'binary_crossentropy') or303(model.loss['wine_type'].name == 'binary_crossentropy') or304(str(model.loss['wine_type']).split()[1] == 'binary_crossentropy'),305"expected": True,306"error_message": f'wine type loss: {model.loss["wine_type"]} is incorrect. Please check implementation.'307},308{309"name": "wine_quality_loss_check",310"result": (model.loss['wine_quality'] in ['mse', 'mean_squared_error']) or311(str(model.loss['wine_quality']).split()[1] == 'mean_squared_error') or312(model.loss['wine_quality'].name == 'mean_squared_error'),313"expected": True,314"error_message": f'wine quality loss: {model.loss["wine_type"]} is incorrect. Please check implementation.'315},316]317318test_loop(test_cases)319320def test_history(history):321322vars_history = vars(history)323324test_cases = [325{326"name": "type_check",327"result": type(history),328"expected": tf.keras.callbacks.History,329"error_message": 'history type is incorrect. Please check model.fit().'330},331{332"name": "params_samples_check",333"result": vars_history['params']['samples'],334"expected": 3155,335"error_message": 'Training samples is incorrect. Please check arguments to model.fit().'336},337{338"name": "params_do_validation_check",339"result": vars_history['params']['do_validation'],340"expected": True,341"error_message": 'No validation data is present. Please check arguments to model.fit().'342},343]344345test_loop(test_cases)346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383