-
Notifications
You must be signed in to change notification settings - Fork 4
/
utilities.py
179 lines (158 loc) · 7.1 KB
/
utilities.py
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
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# This code snippet is lightly modified from that provided by AWS Secrets Manager during secrets creation.
import boto3
import base64
from botocore.exceptions import ClientError
import json
import matplotlib.pyplot as plt
def get_secret(secret_name, region_name):
# Create a Secrets Manager client
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=region_name
)
# In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
# See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
# We rethrow the exception by default.
try:
get_secret_value_response = client.get_secret_value(
SecretId=secret_name
)
return get_secret_value_response
except ClientError as e:
print(e)
if e.response['Error']['Code'] == 'DecryptionFailureException':
# Secrets Manager can't decrypt the protected secret text using the provided KMS key.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'InternalServiceErrorException':
# An error occurred on the server side.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'InvalidParameterException':
# You provided an invalid value for a parameter.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'InvalidRequestException':
# You provided a parameter value that is not valid for the current state of the resource.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'ResourceNotFoundException':
# We can't find the resource that you asked for.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
else:
raise e
else:
# Decrypts secret using the associated KMS CMK.
# Depending on whether the secret is a string or binary, one of these fields will be populated.
print('now in else')
if 'SecretString' in get_secret_value_response:
secret = get_secret_value_response['SecretString']
print(secret)
else:
decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary'])
# Extract training and validation AUC values from the results returned by
# method describe_training_job()
def get_auc_from_metrics(response, metric_type):
for x in range(len(response['FinalMetricDataList'])):
if metric_type in response['FinalMetricDataList'][x].values():
return x
# Functions for model feature exploration
def plot_feature_importance(booster, f, maxfeats = 15):
from xgboost import plot_importance
res = {k:round(v, 2) for k, v in booster.get_score(importance_type = f).items()}
gain_plot = plot_importance(res,
max_num_features = maxfeats,
importance_type = f,
title = 'Feature Importance: ' + f,
color = "#4daf4a")
plt.show()
# Calculate tree depth. Adapted the code from here
# https://stackoverflow.com/questions/29005959/depth-of-a-json-tree to Python 3.
def calculate_tree_depth(tree_dict):
# input: single tree as a dictionary
# output: depth of the tree
if 'children' in tree_dict:
return 1 + max([0] + list(map(calculate_tree_depth, tree_dict['children'])))
else:
return 1
def get_depths_as_list(all_trees):
# input: list of all trees, generated by xgboost's get_dump in json format
# output: list of the same length as all_trees where each element contains
# the depth of a tree
# list to store the depth of each tree
tree_depth = []
for i in range(len(all_trees)):
tree = json.loads(all_trees[i])
tree_depth.append(calculate_tree_depth(tree))
return tree_depth
def calculate_list_unique_elements(input_list):
# calculate number of unique elements in a list
# input: list
# output: dictionary. Keys: unique elements, values: their count
res = dict()
for i in input_list:
if i in res:
res[i] += 1
else:
res[i] = 1
return res
def find_feature(tree_dict, feature):
# input:
# tree_dict: single tree as a dictionary
# feature: feature name, str
# output: 0 if a feature is not a split, 1 if the feature is a split at any node
if "split" in tree_dict:
if tree_dict["split"] == feature:
return 1
else:
for child in tree_dict["children"]:
res = find_feature(child, feature)
if res != 0:
return res
return 0
else:
return 0
# find all trees that have a feature
def find_all_trees_with_feature(all_trees, feature):
# input:
# all_trees: list of all trees, generated by xgboost's get_dump in json format
# feature: feature name, str
# output: indices of trees where a feature has been found at any node
trees_with_features = []
for i in range(len(all_trees)):
tree = json.loads(all_trees[i])
if find_feature(tree, feature) == 1:
trees_with_features.append(i)
return trees_with_features
# given a list of features find how many trees have it
def count_trees_with_features(all_trees, feature_list):
# input:
# all_trees: list of all trees, generated by xgboost's get_dump in json format
# feature_list: list of features
# output: dictionary, keys = feature_list, values = number of trees where a feature has been found
tree_count = dict()
for i in feature_list:
tree_count[i] = 0
for i in feature_list:
for j in range(len(all_trees)):
tree = json.loads(all_trees[j])
if find_feature(tree, i) == 1:
tree_count[i] += 1
return tree_count