aimodelshare 0.3.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. aimodelshare/README.md +26 -0
  2. aimodelshare/__init__.py +100 -0
  3. aimodelshare/aimsonnx.py +2381 -0
  4. aimodelshare/api.py +836 -0
  5. aimodelshare/auth.py +163 -0
  6. aimodelshare/aws.py +511 -0
  7. aimodelshare/aws_client.py +173 -0
  8. aimodelshare/base_image.py +154 -0
  9. aimodelshare/bucketpolicy.py +106 -0
  10. aimodelshare/color_mappings/color_mapping_keras.csv +121 -0
  11. aimodelshare/color_mappings/color_mapping_pytorch.csv +117 -0
  12. aimodelshare/containerisation.py +244 -0
  13. aimodelshare/containerization.py +712 -0
  14. aimodelshare/containerization_templates/Dockerfile.txt +8 -0
  15. aimodelshare/containerization_templates/Dockerfile_PySpark.txt +23 -0
  16. aimodelshare/containerization_templates/buildspec.txt +14 -0
  17. aimodelshare/containerization_templates/lambda_function.txt +40 -0
  18. aimodelshare/custom_approach/__init__.py +1 -0
  19. aimodelshare/custom_approach/lambda_function.py +17 -0
  20. aimodelshare/custom_eval_metrics.py +103 -0
  21. aimodelshare/data_sharing/__init__.py +0 -0
  22. aimodelshare/data_sharing/data_sharing_templates/Dockerfile.txt +3 -0
  23. aimodelshare/data_sharing/data_sharing_templates/__init__.py +1 -0
  24. aimodelshare/data_sharing/data_sharing_templates/buildspec.txt +15 -0
  25. aimodelshare/data_sharing/data_sharing_templates/codebuild_policies.txt +129 -0
  26. aimodelshare/data_sharing/data_sharing_templates/codebuild_trust_relationship.txt +12 -0
  27. aimodelshare/data_sharing/download_data.py +620 -0
  28. aimodelshare/data_sharing/share_data.py +373 -0
  29. aimodelshare/data_sharing/utils.py +8 -0
  30. aimodelshare/deploy_custom_lambda.py +246 -0
  31. aimodelshare/documentation/Makefile +20 -0
  32. aimodelshare/documentation/karma_sphinx_theme/__init__.py +28 -0
  33. aimodelshare/documentation/karma_sphinx_theme/_version.py +2 -0
  34. aimodelshare/documentation/karma_sphinx_theme/breadcrumbs.html +70 -0
  35. aimodelshare/documentation/karma_sphinx_theme/layout.html +172 -0
  36. aimodelshare/documentation/karma_sphinx_theme/search.html +50 -0
  37. aimodelshare/documentation/karma_sphinx_theme/searchbox.html +14 -0
  38. aimodelshare/documentation/karma_sphinx_theme/static/css/custom.css +2 -0
  39. aimodelshare/documentation/karma_sphinx_theme/static/css/custom.css.map +1 -0
  40. aimodelshare/documentation/karma_sphinx_theme/static/css/theme.css +2751 -0
  41. aimodelshare/documentation/karma_sphinx_theme/static/css/theme.css.map +1 -0
  42. aimodelshare/documentation/karma_sphinx_theme/static/css/theme.min.css +2 -0
  43. aimodelshare/documentation/karma_sphinx_theme/static/css/theme.min.css.map +1 -0
  44. aimodelshare/documentation/karma_sphinx_theme/static/font/fontello.eot +0 -0
  45. aimodelshare/documentation/karma_sphinx_theme/static/font/fontello.svg +32 -0
  46. aimodelshare/documentation/karma_sphinx_theme/static/font/fontello.ttf +0 -0
  47. aimodelshare/documentation/karma_sphinx_theme/static/font/fontello.woff +0 -0
  48. aimodelshare/documentation/karma_sphinx_theme/static/font/fontello.woff2 +0 -0
  49. aimodelshare/documentation/karma_sphinx_theme/static/js/theme.js +68 -0
  50. aimodelshare/documentation/karma_sphinx_theme/theme.conf +9 -0
  51. aimodelshare/documentation/make.bat +35 -0
  52. aimodelshare/documentation/requirements.txt +2 -0
  53. aimodelshare/documentation/source/about.rst +18 -0
  54. aimodelshare/documentation/source/advanced_features.rst +137 -0
  55. aimodelshare/documentation/source/competition.rst +218 -0
  56. aimodelshare/documentation/source/conf.py +58 -0
  57. aimodelshare/documentation/source/create_credentials.rst +86 -0
  58. aimodelshare/documentation/source/example_notebooks.rst +132 -0
  59. aimodelshare/documentation/source/functions.rst +151 -0
  60. aimodelshare/documentation/source/gettingstarted.rst +390 -0
  61. aimodelshare/documentation/source/images/creds1.png +0 -0
  62. aimodelshare/documentation/source/images/creds2.png +0 -0
  63. aimodelshare/documentation/source/images/creds3.png +0 -0
  64. aimodelshare/documentation/source/images/creds4.png +0 -0
  65. aimodelshare/documentation/source/images/creds5.png +0 -0
  66. aimodelshare/documentation/source/images/creds_file_example.png +0 -0
  67. aimodelshare/documentation/source/images/predict_tab.png +0 -0
  68. aimodelshare/documentation/source/index.rst +110 -0
  69. aimodelshare/documentation/source/modelplayground.rst +132 -0
  70. aimodelshare/exceptions.py +11 -0
  71. aimodelshare/generatemodelapi.py +1270 -0
  72. aimodelshare/iam/codebuild_policy.txt +129 -0
  73. aimodelshare/iam/codebuild_trust_relationship.txt +12 -0
  74. aimodelshare/iam/lambda_policy.txt +15 -0
  75. aimodelshare/iam/lambda_trust_relationship.txt +12 -0
  76. aimodelshare/json_templates/__init__.py +1 -0
  77. aimodelshare/json_templates/api_json.txt +155 -0
  78. aimodelshare/json_templates/auth/policy.txt +1 -0
  79. aimodelshare/json_templates/auth/role.txt +1 -0
  80. aimodelshare/json_templates/eval/policy.txt +1 -0
  81. aimodelshare/json_templates/eval/role.txt +1 -0
  82. aimodelshare/json_templates/function/policy.txt +1 -0
  83. aimodelshare/json_templates/function/role.txt +1 -0
  84. aimodelshare/json_templates/integration_response.txt +5 -0
  85. aimodelshare/json_templates/lambda_policy_1.txt +15 -0
  86. aimodelshare/json_templates/lambda_policy_2.txt +8 -0
  87. aimodelshare/json_templates/lambda_role_1.txt +12 -0
  88. aimodelshare/json_templates/lambda_role_2.txt +16 -0
  89. aimodelshare/leaderboard.py +174 -0
  90. aimodelshare/main/1.txt +132 -0
  91. aimodelshare/main/1B.txt +112 -0
  92. aimodelshare/main/2.txt +153 -0
  93. aimodelshare/main/3.txt +134 -0
  94. aimodelshare/main/4.txt +128 -0
  95. aimodelshare/main/5.txt +109 -0
  96. aimodelshare/main/6.txt +105 -0
  97. aimodelshare/main/7.txt +144 -0
  98. aimodelshare/main/8.txt +142 -0
  99. aimodelshare/main/__init__.py +1 -0
  100. aimodelshare/main/authorization.txt +275 -0
  101. aimodelshare/main/eval_classification.txt +79 -0
  102. aimodelshare/main/eval_lambda.txt +1709 -0
  103. aimodelshare/main/eval_regression.txt +80 -0
  104. aimodelshare/main/lambda_function.txt +8 -0
  105. aimodelshare/main/nst.txt +149 -0
  106. aimodelshare/model.py +1543 -0
  107. aimodelshare/modeluser.py +215 -0
  108. aimodelshare/moral_compass/README.md +408 -0
  109. aimodelshare/moral_compass/__init__.py +65 -0
  110. aimodelshare/moral_compass/_version.py +3 -0
  111. aimodelshare/moral_compass/api_client.py +601 -0
  112. aimodelshare/moral_compass/apps/__init__.py +69 -0
  113. aimodelshare/moral_compass/apps/ai_consequences.py +540 -0
  114. aimodelshare/moral_compass/apps/bias_detective.py +714 -0
  115. aimodelshare/moral_compass/apps/ethical_revelation.py +898 -0
  116. aimodelshare/moral_compass/apps/fairness_fixer.py +889 -0
  117. aimodelshare/moral_compass/apps/judge.py +888 -0
  118. aimodelshare/moral_compass/apps/justice_equity_upgrade.py +853 -0
  119. aimodelshare/moral_compass/apps/mc_integration_helpers.py +820 -0
  120. aimodelshare/moral_compass/apps/model_building_game.py +1104 -0
  121. aimodelshare/moral_compass/apps/model_building_game_beginner.py +687 -0
  122. aimodelshare/moral_compass/apps/moral_compass_challenge.py +858 -0
  123. aimodelshare/moral_compass/apps/session_auth.py +254 -0
  124. aimodelshare/moral_compass/apps/shared_activity_styles.css +349 -0
  125. aimodelshare/moral_compass/apps/tutorial.py +481 -0
  126. aimodelshare/moral_compass/apps/what_is_ai.py +853 -0
  127. aimodelshare/moral_compass/challenge.py +365 -0
  128. aimodelshare/moral_compass/config.py +187 -0
  129. aimodelshare/placeholders/model.onnx +0 -0
  130. aimodelshare/placeholders/preprocessor.zip +0 -0
  131. aimodelshare/playground.py +1968 -0
  132. aimodelshare/postprocessormodules.py +157 -0
  133. aimodelshare/preprocessormodules.py +373 -0
  134. aimodelshare/pyspark/1.txt +195 -0
  135. aimodelshare/pyspark/1B.txt +181 -0
  136. aimodelshare/pyspark/2.txt +220 -0
  137. aimodelshare/pyspark/3.txt +204 -0
  138. aimodelshare/pyspark/4.txt +187 -0
  139. aimodelshare/pyspark/5.txt +178 -0
  140. aimodelshare/pyspark/6.txt +174 -0
  141. aimodelshare/pyspark/7.txt +211 -0
  142. aimodelshare/pyspark/8.txt +206 -0
  143. aimodelshare/pyspark/__init__.py +1 -0
  144. aimodelshare/pyspark/authorization.txt +258 -0
  145. aimodelshare/pyspark/eval_classification.txt +79 -0
  146. aimodelshare/pyspark/eval_lambda.txt +1441 -0
  147. aimodelshare/pyspark/eval_regression.txt +80 -0
  148. aimodelshare/pyspark/lambda_function.txt +8 -0
  149. aimodelshare/pyspark/nst.txt +213 -0
  150. aimodelshare/python/my_preprocessor.py +58 -0
  151. aimodelshare/readme.md +26 -0
  152. aimodelshare/reproducibility.py +181 -0
  153. aimodelshare/sam/Dockerfile.txt +8 -0
  154. aimodelshare/sam/Dockerfile_PySpark.txt +24 -0
  155. aimodelshare/sam/__init__.py +1 -0
  156. aimodelshare/sam/buildspec.txt +11 -0
  157. aimodelshare/sam/codebuild_policies.txt +129 -0
  158. aimodelshare/sam/codebuild_trust_relationship.txt +12 -0
  159. aimodelshare/sam/codepipeline_policies.txt +173 -0
  160. aimodelshare/sam/codepipeline_trust_relationship.txt +12 -0
  161. aimodelshare/sam/spark-class.txt +2 -0
  162. aimodelshare/sam/template.txt +54 -0
  163. aimodelshare/tools.py +103 -0
  164. aimodelshare/utils/__init__.py +78 -0
  165. aimodelshare/utils/optional_deps.py +38 -0
  166. aimodelshare/utils.py +57 -0
  167. aimodelshare-0.3.7.dist-info/METADATA +298 -0
  168. aimodelshare-0.3.7.dist-info/RECORD +171 -0
  169. aimodelshare-0.3.7.dist-info/WHEEL +5 -0
  170. aimodelshare-0.3.7.dist-info/licenses/LICENSE +5 -0
  171. aimodelshare-0.3.7.dist-info/top_level.txt +1 -0
@@ -0,0 +1,275 @@
1
+ from __future__ import print_function
2
+
3
+ import re
4
+ import json
5
+
6
+
7
+ def handler(event, context):
8
+ print("Client token: " + event.get('authorizationToken','empty'))
9
+ print("Method ARN: " + event.get('methodArn','empty'))
10
+ '''
11
+ Validate the incoming token and produce the principal user identifier
12
+ associated with the token. This can be accomplished in a number of ways:
13
+
14
+ 1. Call out to the OAuth provider
15
+ 2. Decode a JWT token inline
16
+ 3. Lookup in a self-managed DB
17
+ '''
18
+ idtoken=event.get('authorizationToken','empty')
19
+ tokenlength=len(idtoken)
20
+ print(tokenlength)
21
+ print(event)
22
+ evaltrue="FALSE"
23
+ principalId = idtoken
24
+
25
+ if tokenlength>=40:
26
+ try:
27
+ tokenbodydata=json.loads(idtoken)
28
+ idtoken=tokenbodydata['token']
29
+ evaltrue=tokenbodydata['eval']
30
+ principalId = idtoken
31
+
32
+ except:
33
+ evaltrue="FALSE"
34
+
35
+ try:
36
+
37
+ import jwt
38
+ decoded = jwt.decode(idtoken, options={"verify_signature": False}) # works in PyJWT < v2.0
39
+ except:
40
+ pass
41
+ else:
42
+ pass
43
+
44
+ # Check token access with live rest api (with cognito auth activated) to ensure user isn't sending incorrect username
45
+ # 200 status indicates accept, 403 means unauthorized
46
+
47
+
48
+ #==============AIMODELSHARE Note: accept / deny languange located on line 67=======================================================
49
+
50
+ '''
51
+ You can send a 401 Unauthorized response to the client by failing like so:
52
+
53
+ raise Exception('Unauthorized')
54
+
55
+ If the token is valid, a policy must be generated which will allow or deny
56
+ access to the client. If access is denied, the client will receive a 403
57
+ Access Denied response. If access is allowed, API Gateway will proceed with
58
+ the backend integration configured on the method that was called.
59
+
60
+ This function must generate a policy that is associated with the recognized
61
+ principal user identifier. Depending on your use case, you might store
62
+ policies in a DB, or generate them on the fly.
63
+
64
+ Keep in mind, the policy is cached for 5 minutes by default (TTL is
65
+ configurable in the authorizer) and will apply to subsequent calls to any
66
+ method/resource in the RestApi made with the same token.
67
+
68
+ The example policy below denies access to all resources in the RestApi.
69
+ '''
70
+ tmp = event['methodArn'].split(':')
71
+ apiGatewayArnTmp = tmp[5].split('/')
72
+ awsAccountId = tmp[4]
73
+
74
+ policy = AuthPolicy(principalId, awsAccountId)
75
+ policy.restApiId = apiGatewayArnTmp[0]
76
+ policy.region = tmp[3]
77
+ policy.stage = apiGatewayArnTmp[1]
78
+
79
+
80
+ #====================Accept/Deny auth for AIMODELSHARE begins here===========================================
81
+
82
+ import requests
83
+
84
+
85
+ headers_with_authentication = {'Content-Type': 'application/json', 'Authorization': idtoken}
86
+
87
+ response=requests.post("https://1b861v14ne.execute-api.us-east-1.amazonaws.com/dev/redisusagetrackerembedded",
88
+ json={"apiid": str(policy.restApiId),"eval":evaltrue}, headers=headers_with_authentication)
89
+ print(response.status_code)
90
+ uniquemodversion=str(response.text)
91
+
92
+ print(response.text)
93
+
94
+ if idtoken=="$apikey":
95
+ policyresult="accept"
96
+
97
+ elif any([response.status_code!=200,response.text.find("Missing")>0,response.text.find("Monthly")>0,response.text.find("monthly")>0]):
98
+ policyresult="deny"
99
+ else:
100
+ policyresult="accept"
101
+
102
+ if policyresult=="deny":
103
+ policy.denyAllMethods()
104
+ else:
105
+ policy.allowAllMethods()
106
+
107
+ # Finally, build the policy
108
+ authResponse = policy.build()
109
+ authResponse['context']['uniquemodversion']=uniquemodversion
110
+
111
+ # new! -- add additional key-value pairs associated with the authenticated principal
112
+ # these are made available by APIGW like so: $context.authorizer.<key>
113
+ # additional context is cached
114
+
115
+
116
+
117
+ return authResponse
118
+
119
+
120
+ class HttpVerb:
121
+ GET = 'GET'
122
+ POST = 'POST'
123
+ PUT = 'PUT'
124
+ PATCH = 'PATCH'
125
+ HEAD = 'HEAD'
126
+ DELETE = 'DELETE'
127
+ OPTIONS = 'OPTIONS'
128
+ ALL = '*'
129
+
130
+
131
+ class AuthPolicy(object):
132
+ # The AWS account id the policy will be generated for. This is used to create the method ARNs.
133
+ awsAccountId = ''
134
+ # The principal used for the policy, this should be a unique identifier for the end user.
135
+ principalId = ''
136
+ # The policy version used for the evaluation. This should always be '2012-10-17'
137
+ version = '2012-10-17'
138
+ # The regular expression used to validate resource paths for the policy
139
+ pathRegex = '^[/.a-zA-Z0-9-\*]+$'
140
+
141
+ '''Internal lists of allowed and denied methods.
142
+
143
+ These are lists of objects and each object has 2 properties: A resource
144
+ ARN and a nullable conditions statement. The build method processes these
145
+ lists and generates the approriate statements for the final policy.
146
+ '''
147
+ allowMethods = []
148
+ denyMethods = []
149
+
150
+ # The API Gateway API id. By default this is set to '*'
151
+ restApiId = '*'
152
+ # The region where the API is deployed. By default this is set to '*'
153
+ region = '*'
154
+ # The name of the stage used in the policy. By default this is set to '*'
155
+ stage = '*'
156
+
157
+ def __init__(self, principal, awsAccountId):
158
+ self.awsAccountId = awsAccountId
159
+ self.principalId = principal
160
+ self.allowMethods = []
161
+ self.denyMethods = []
162
+
163
+ def _addMethod(self, effect, verb, resource, conditions):
164
+ '''Adds a method to the internal lists of allowed or denied methods. Each object in
165
+ the internal list contains a resource ARN and a condition statement. The condition
166
+ statement can be null.'''
167
+ if verb != '*' and not hasattr(HttpVerb, verb):
168
+ raise NameError('Invalid HTTP verb ' + verb + '. Allowed verbs in HttpVerb class')
169
+ resourcePattern = re.compile(self.pathRegex)
170
+ if not resourcePattern.match(resource):
171
+ raise NameError('Invalid resource path: ' + resource + '. Path should match ' + self.pathRegex)
172
+
173
+ if resource[:1] == '/':
174
+ resource = resource[1:]
175
+
176
+ resourceArn = 'arn:aws:execute-api:{}:{}:{}/{}/{}/{}'.format(self.region, self.awsAccountId, self.restApiId, self.stage, verb, resource)
177
+
178
+ if effect.lower() == 'allow':
179
+ self.allowMethods.append({
180
+ 'resourceArn': resourceArn,
181
+ 'conditions': conditions
182
+ })
183
+ elif effect.lower() == 'deny':
184
+ self.denyMethods.append({
185
+ 'resourceArn': resourceArn,
186
+ 'conditions': conditions
187
+ })
188
+
189
+ def _getEmptyStatement(self, effect):
190
+ '''Returns an empty statement object prepopulated with the correct action and the
191
+ desired effect.'''
192
+ statement = {
193
+ 'Action': 'execute-api:Invoke',
194
+ 'Effect': effect[:1].upper() + effect[1:].lower(),
195
+ 'Resource': []
196
+ }
197
+
198
+ return statement
199
+
200
+ def _getStatementForEffect(self, effect, methods):
201
+ '''This function loops over an array of objects containing a resourceArn and
202
+ conditions statement and generates the array of statements for the policy.'''
203
+ statements = []
204
+
205
+ if len(methods) > 0:
206
+ statement = self._getEmptyStatement(effect)
207
+
208
+ for curMethod in methods:
209
+ if curMethod['conditions'] is None or len(curMethod['conditions']) == 0:
210
+ statement['Resource'].append(curMethod['resourceArn'])
211
+ else:
212
+ conditionalStatement = self._getEmptyStatement(effect)
213
+ conditionalStatement['Resource'].append(curMethod['resourceArn'])
214
+ conditionalStatement['Condition'] = curMethod['conditions']
215
+ statements.append(conditionalStatement)
216
+
217
+ if statement['Resource']:
218
+ statements.append(statement)
219
+
220
+ return statements
221
+
222
+ def allowAllMethods(self):
223
+ '''Adds a '*' allow to the policy to authorize access to all methods of an API'''
224
+ self._addMethod('Allow', HttpVerb.ALL, '*', [])
225
+
226
+ def denyAllMethods(self):
227
+ '''Adds a '*' allow to the policy to deny access to all methods of an API'''
228
+ self._addMethod('Deny', HttpVerb.ALL, '*', [])
229
+
230
+ def allowMethod(self, verb, resource):
231
+ '''Adds an API Gateway method (Http verb + Resource path) to the list of allowed
232
+ methods for the policy'''
233
+ self._addMethod('Allow', verb, resource, [])
234
+
235
+ def denyMethod(self, verb, resource):
236
+ '''Adds an API Gateway method (Http verb + Resource path) to the list of denied
237
+ methods for the policy'''
238
+ self._addMethod('Deny', verb, resource, [])
239
+
240
+ def allowMethodWithConditions(self, verb, resource, conditions):
241
+ '''Adds an API Gateway method (Http verb + Resource path) to the list of allowed
242
+ methods and includes a condition for the policy statement. More on AWS policy
243
+ conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition'''
244
+ self._addMethod('Allow', verb, resource, conditions)
245
+
246
+ def denyMethodWithConditions(self, verb, resource, conditions):
247
+ '''Adds an API Gateway method (Http verb + Resource path) to the list of denied
248
+ methods and includes a condition for the policy statement. More on AWS policy
249
+ conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition'''
250
+ self._addMethod('Deny', verb, resource, conditions)
251
+
252
+ def build(self):
253
+ '''Generates the policy document based on the internal lists of allowed and denied
254
+ conditions. This will generate a policy with two main statements for the effect:
255
+ one statement for Allow and one statement for Deny.
256
+ Methods that includes conditions will have their own statement in the policy.'''
257
+ if ((self.allowMethods is None or len(self.allowMethods) == 0) and
258
+ (self.denyMethods is None or len(self.denyMethods) == 0)):
259
+ raise NameError('No statements defined for the policy')
260
+
261
+ policy = {
262
+ 'principalId': self.principalId,
263
+ 'policyDocument': {
264
+ 'Version': self.version,
265
+ 'Statement': []
266
+ },
267
+ "context": {
268
+ "uniquemodversion":"string"
269
+ }
270
+ }
271
+
272
+ policy['policyDocument']['Statement'].extend(self._getStatementForEffect('Allow', self.allowMethods))
273
+ policy['policyDocument']['Statement'].extend(self._getStatementForEffect('Deny', self.denyMethods))
274
+
275
+ return policy
@@ -0,0 +1,79 @@
1
+ import boto3
2
+ import pandas as pd
3
+ import os
4
+ import numpy as np
5
+ import onnxruntime as rt
6
+ import json
7
+ import sklearn
8
+ from sklearn.metrics import accuracy_score
9
+ from sklearn.metrics import f1_score
10
+ from sklearn.metrics import precision_score
11
+ from sklearn.metrics import recall_score
12
+ from sklearn.metrics import roc_auc_score
13
+ from sklearn.metrics import mean_squared_error
14
+ from sklearn.metrics import r2_score
15
+ from sklearn.metrics import mean_absolute_error
16
+ from math import sqrt
17
+ import pickle
18
+ import six
19
+
20
+ def get_ytestdata(ytest_s3_filename="ytest.pkl"):
21
+ s3 = boto3.resource("s3")
22
+ bucket = s3.Bucket("$bucket_name")
23
+
24
+ with open("/tmp/ytest.pkl", "wb") as ytestfo:
25
+ bucket.download_fileobj("$unique_model_id/ytest.pkl", ytestfo)
26
+ ytestdata = pickle.load(open("/tmp/ytest.pkl", "rb" ) )
27
+ return ytestdata
28
+
29
+ def model_eval_metrics(y_true, y_pred,classification="TRUE"):
30
+ if classification=="TRUE":
31
+ accuracy_eval = accuracy_score(y_true, y_pred)
32
+ f1_score_eval = f1_score(y_true, y_pred,average="macro",zero_division=0)
33
+ precision_eval = precision_score(y_true, y_pred,average="macro",zero_division=0)
34
+ recall_eval = recall_score(y_true, y_pred,average="macro",zero_division=0)
35
+ mse_eval = 0
36
+ rmse_eval = 0
37
+ mae_eval = 0
38
+ r2_eval = 0
39
+ metricdata = {'accuracy': [accuracy_eval], 'f1_score': [f1_score_eval], 'precision': [precision_eval], 'recall': [recall_eval], 'mse': [mse_eval], 'rmse': [rmse_eval], 'mae': [mae_eval], 'r2': [r2_eval]}
40
+ finalmetricdata = pd.DataFrame.from_dict(metricdata)
41
+ else:
42
+ accuracy_eval = 0
43
+ f1_score_eval = 0
44
+ precision_eval = 0
45
+ recall_eval = 0
46
+ mse_eval = mean_squared_error(y_true, y_pred)
47
+ rmse_eval = sqrt(mean_squared_error(y_true, y_pred))
48
+ mae_eval = mean_absolute_error(y_true, y_pred)
49
+ r2_eval = r2_score(y_true, y_pred)
50
+ metricdata = {'accuracy': [accuracy_eval], 'f1_score': [f1_score_eval], 'precision': [precision_eval], 'recall': [recall_eval], 'mse': [mse_eval], 'rmse': [rmse_eval], 'mae': [mae_eval], 'r2': [r2_eval]}
51
+ finalmetricdata = pd.DataFrame.from_dict(metricdata)
52
+ return finalmetricdata.to_dict('records')[0]
53
+
54
+ ytestdata=get_ytestdata(ytest_s3_filename="ytest.pkl")
55
+
56
+ def evaluate_model(event,ytestdata):
57
+ body = event["body"]
58
+
59
+ if isinstance(event["body"], six.string_types):
60
+ prediction_list = json.loads(event["body"])
61
+ print(prediction_list)
62
+ else:
63
+ prediction_list = event["body"]
64
+ print(prediction_list)
65
+
66
+ result=model_eval_metrics(ytestdata,prediction_list,classification="TRUE")
67
+ return result
68
+
69
+ def handler(event, context):
70
+ result = evaluate_model(event,ytestdata)
71
+ return {"statusCode": 200,
72
+ "headers": {
73
+ "Access-Control-Allow-Origin" : "*",
74
+ "Access-Control-Allow-Credentials": True,
75
+ "Allow" : "GET, OPTIONS, POST",
76
+ "Access-Control-Allow-Methods" : "GET, OPTIONS, POST",
77
+ "Access-Control-Allow-Headers" : "*"
78
+ },
79
+ "body": json.dumps(result)}