forked from udacity/nd0821-c3-starter-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_model.py
More file actions
189 lines (156 loc) · 4.92 KB
/
test_model.py
File metadata and controls
189 lines (156 loc) · 4.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import pytest, os, logging, pickle
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.exceptions import NotFittedError
from ml.model import inference, compute_model_metrics, compute_confusion_matrix
from ml.data import process_data
"""
Fixture - The test functions will
use the return of data() as an argument
"""
@pytest.fixture(scope="module")
def data():
# code to load in the data.
datapath = "./data/census.csv"
return pd.read_csv(datapath)
@pytest.fixture(scope="module")
def path():
return "./data/census.csv"
@pytest.fixture(scope="module")
def features():
"""
Fixture - will return the categorical features as argument
"""
cat_features = [ "workclass",
"education",
"marital-status",
"occupation",
"relationship",
"race",
"sex",
"native-country"]
return cat_features
@pytest.fixture(scope="module")
def train_dataset(data, features):
"""
Fixture - returns cleaned train dataset to be used for model testing
"""
train, test = train_test_split( data,
test_size=0.20,
random_state=10,
stratify=data['salary']
)
X_train, y_train, encoder, lb = process_data(
train,
categorical_features=features,
label="salary",
training=True
)
return X_train, y_train
"""
Test methods
"""
def test_import_data(path):
"""
Test presence and shape of dataset file
"""
try:
df = pd.read_csv(path)
except FileNotFoundError as err:
logging.error("File not found")
raise err
# Check the df shape
try:
assert df.shape[0] > 0
assert df.shape[1] > 0
except AssertionError as err:
logging.error(
"Testing import_data: The file doesn't appear to have rows and columns")
raise err
def test_features(data, features):
"""
Check that categorical features are in dataset
"""
try:
assert sorted(set(data.columns).intersection(features)) == sorted(features)
except AssertionError as err:
logging.error(
"Testing dataset: Features are missing in the data columns")
raise err
def test_is_model():
"""
Check saved model is present
"""
savepath = "./model/trained_model.pkl"
if os.path.isfile(savepath):
try:
_ = pickle.load(open(savepath, 'rb'))
except Exception as err:
logging.error(
"Testing saved model: Saved model does not appear to be valid")
raise err
else:
pass
def test_is_fitted_model(train_dataset):
"""
Check saved model is fitted
"""
X_train, y_train = train_dataset
savepath = "./model/trained_model.pkl"
model = pickle.load(open(savepath, 'rb'))
try:
model.predict(X_train)
except NotFittedError as err:
logging.error(
f"Model is not fit, error {err}")
raise err
def test_inference(train_dataset):
"""
Check inference function
"""
X_train, y_train = train_dataset
savepath = "./model/trained_model.pkl"
if os.path.isfile(savepath):
model = pickle.load(open(savepath, 'rb'))
try:
preds = inference(model, X_train)
except Exception as err:
logging.error(
"Inference cannot be performed on saved model and train data")
raise err
else:
pass
def test_compute_model_metrics(train_dataset):
"""
Check calculation of performance metrics function
"""
X_train, y_train = train_dataset
savepath = "./model/trained_model.pkl"
if os.path.isfile(savepath):
model = pickle.load(open(savepath, 'rb'))
preds = inference(model, X_train)
try:
precision, recall, fbeta = compute_model_metrics(y_train, preds)
except Exception as err:
logging.error(
"Performance metrics cannot be calculated on train data")
raise err
else:
pass
def test_compute_confusion_matrix(train_dataset):
"""
Check calculation of confusion matrix function
"""
X_train, y_train = train_dataset
savepath = "./model/trained_model.pkl"
if os.path.isfile(savepath):
model = pickle.load(open(savepath, 'rb'))
preds = inference(model, X_train)
try:
cm = compute_confusion_matrix(y_train, preds)
except Exception as err:
logging.error(
"Confusion matrix cannot be calculated on train data")
raise err
else:
pass