Created
January 21, 2015 08:25
-
-
Save bmurzeau/d178d60b9f962d090350 to your computer and use it in GitHub Desktop.
Google Prediction Script for Kaggle Give Me Some Credit challenge (PredicSis API vs Google Prediction)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# | |
# Copyright (C) 2013 Google Inc. | |
# | |
# Licensed under the Apache License, Version 2.0 (the "License"); | |
# you may not use this file except in compliance with the License. | |
# You may obtain a copy of the License at | |
# | |
# http://www.apache.org/licenses/LICENSE-2.0 | |
# | |
# Unless required by applicable law or agreed to in writing, software | |
# distributed under the License is distributed on an "AS IS" BASIS, | |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
# See the License for the specific language governing permissions and | |
# limitations under the License. | |
"""Command-line skeleton application for Prediction API. | |
Usage: | |
$ python score.py | |
You can also get help on all the command-line flags the program understands | |
by running: | |
$ python score.py --help | |
""" | |
import argparse | |
import pprint | |
import httplib2 | |
import os | |
import sys | |
import json | |
import time | |
import errno | |
import socket | |
import threading | |
import thread | |
from apiclient import discovery | |
from oauth2client import file | |
from oauth2client import client | |
from oauth2client import tools | |
# Parser for command-line arguments. | |
parser = argparse.ArgumentParser( | |
description=__doc__, | |
formatter_class=argparse.RawDescriptionHelpFormatter, | |
parents=[tools.argparser]) | |
parser.add_argument('input_file', help='Local path of csv input data (ex test.csv)') | |
parser.add_argument('output_file', help='Local path of csv output data (ex result.csv)') | |
# CLIENT_SECRETS is name of a file containing the OAuth 2.0 information for this | |
# application, including client_id and client_secret. You can see the Client ID | |
# and Client secret on the APIs page in the Cloud Console: | |
# <https://cloud.google.com/console#/project/55732917986/apiui> | |
CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json') | |
# Set up a Flow object to be used for authentication. | |
# Add one or more of the following scopes. PLEASE ONLY ADD THE SCOPES YOU | |
# NEED. For more information on using scopes please see | |
# <https://developers.google.com/+/best-practices>. | |
FLOW = client.flow_from_clientsecrets(CLIENT_SECRETS, | |
scope=[ | |
'https://www.googleapis.com/auth/devstorage.full_control', | |
'https://www.googleapis.com/auth/devstorage.read_only', | |
'https://www.googleapis.com/auth/devstorage.read_write', | |
'https://www.googleapis.com/auth/prediction', | |
], | |
message=tools.message_if_missing(CLIENT_SECRETS)) | |
def print_header(line): | |
'''Format and print header block sized to length of line''' | |
header_str = '=' | |
header_line = header_str * len(line) | |
print '\n' + header_line | |
print line | |
print header_line | |
class Printdot(threading.Thread): | |
def __init__(self, nom = ''): | |
threading.Thread.__init__(self) | |
self.nom = nom | |
self._stopevent = threading.Event() | |
def run(self): | |
while not self._stopevent.isSet(): | |
sys.stdout.flush() | |
sys.stdout.write('.') | |
time.sleep(1) | |
def stop(self): | |
self._stopevent.set() | |
def main(argv): | |
# Parse the command-line flags. | |
flags = parser.parse_args(argv[1:]) | |
# If the credentials don't exist or are invalid run through the native client | |
# flow. The Storage object will ensure that if successful the good | |
# credentials will get written back to the file. | |
storage = file.Storage('sample.dat') | |
credentials = storage.get() | |
if credentials is None or credentials.invalid: | |
credentials = tools.run_flow(FLOW, storage, flags) | |
# Create an httplib2.Http object to handle our HTTP requests and authorize it | |
# with our good Credentials. | |
http = httplib2.Http() | |
http = credentials.authorize(http) | |
# Construct the service object for the interacting with the Prediction API. | |
service = discovery.build('prediction', 'v1.6', http=http) | |
try: | |
prj = 'XYZ' | |
papi = service.trainedmodels() | |
print """ | |
____ _ ____ _ _ _ _ | |
/ ___| ___ ___ __ _| | ___ | _ \ _ __ ___ __| (_) ___| |_(_) ___ _ __ | |
| | _ / _ \ / _ \ / _` | |/ _ \\ | |_) | '__/ _ \/ _` | |/ __| __| |/ _ \| '_ \ | |
| |_| | (_) | (_) | (_| | | __/ | __/| | | __/ (_| | | (__| |_| | (_) | | | | | |
\____|\___/ \___/ \__, |_|\___| |_| |_| \___|\__,_|_|\___|\__|_|\___/|_| |_| | |
|___/ """ | |
print '\n' + "Data source: https://www.kaggle.com/c/GiveMeSomeCredit" | |
print '\n' + "Building model" | |
start_model = time.time() | |
thrd = Printdot() | |
thrd.start() | |
model_body = { 'id': '5', 'storageDataLocation': 'genesys/D0009_GoogleTrain.txt' } | |
model = papi.insert(project=prj,body=model_body).execute() | |
model = papi.get(project=prj, id='5').execute() | |
while (model['trainingStatus'] == 'RUNNING'): | |
time.sleep(1) | |
model = papi.get(project=prj, id='5').execute() | |
thrd.stop() | |
end_model = time.time() | |
print '\n' + "Completed in %.2f seconds" % (end_model - start_model) + '\n' | |
# Make a prediction using the newly trained model. | |
print 'Generating predictions' | |
fin = open(flags.input_file, 'r') | |
fout = open(flags.output_file, 'w') | |
nbLines = 0 | |
start_predictions = time.time() | |
thrd = Printdot() | |
thrd.start() | |
try: | |
for line in fin: | |
lineItems = line.split('\n')[0].replace('"','').split(',') | |
body = {'input': {'csvInstance': lineItems[1:]}} | |
result = papi.predict(project=prj, id='5', body=body).execute() | |
print result | |
scoreOui = next(score['score'] for score in result['outputMulti'] if score['label'] == 'True') | |
scoreNon = next(score['score'] for score in result['outputMulti'] if score['label'] == 'False') | |
fout.write(scoreOui+','+scoreNon+'\n') | |
nbLines+=1 | |
if not nbLines%10: | |
fout.flush() | |
os.fsync(fout) | |
except socket.error, v: | |
errorcode=v[0] | |
print 'error code '+errorcode+'' | |
thrd.stop() | |
end_predictions = time.time() | |
print '\n' + "Completed in %.2f seconds" % (end_predictions - start_predictions) + '\n' | |
print "Google Prediction terminated in %.2f seconds" % (end_predictions - start_model) + '\n' | |
except client.AccessTokenRefreshError: | |
print ("The credentials have been revoked or expired, please re-run" | |
"the application to re-authorize") | |
if __name__ == '__main__': | |
main(sys.argv) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment