Archiv für die Kategorie google

How to work with Google n-gram data sets in R using MySQL

How to work with Google n-gram data sets in R using MySQL. via R-Bloggers: I like really much about this blog the focus interesting things along with code examples to try it out on your own.

N-Grams datasets can also be created from your own texts using NTLK functions (see http://nltk.googlecode.com/svn/trunk/doc/howto/collocations.html ): in analytical use cases N-grams give you a better basis to have a machine ‘understand’ the meaning of a text (compared to looking at the words individually.

—Update from 2012-04-10:

Stefan Keller ( http://twitter.com/sfkeller  ) hinted me to a blog entry about how to use n-grams in a PostgreSQL based setting to optimize search functionality.

Hinterlasse einen Kommentar

(English) First steps with Google’s Prediction API – Part 1: Data Preparation, Upload & Training

This blog shows an example how to work with Google Prediction API on a standard classification example: it is based on the currently running “Give me some credit exercise”from kaggle.com. The example case wants to know (based on a set of defined input variables, how big the probability is that a certain person will go into insolvency during the next two years.

This first part covers data preparation, upload & training preparation, the second part will cover training & prediction with Google’s API and the third part will contain a summary & a recommendation on when & how Prediction API can be used.

Steps needed to use Prediction API

0) Prepare your infrastructure

You need access to two Google APIs: Prediction API & Cloud Storage: Cloud Storage is used to store the data, which are analyzed. There is no option to use another cloud storage provider.

Point your browser to the API Console at https://code.google.com/apis/console/ and create a “project”: the project is a container to cover all API, billing etc. needs for one application. The API Console Project also bundles all oAuth requirements for the Google APIs.

Under the menu item “Services” you can find the list off all available APIs for your project: make sure, that Prediction API and Google Cloud Storage are enabled. (Enabling of Google cloud storage requires you to enter billing information, however the free quota is 5GB (according to https://code.google.com/intl/de-DE/apis/storage/docs/pricingandterms.html )

For easier interaction with the cloud storage it makes sense to use Google’s GSUtil tool (http://code.google.com/intl/de-DE/apis/storage/docs/gsutil.html ): please put special attention to correct authentication setup, as detailed in http://code.google.com/intl/de-DE/apis/storage/docs/gsutil_install.html#authenticate .

The Storage manager web application is an alternative way to interact with the Cloud Storage: further details can be found at http://code.google.com/intl/de-DE/apis/storage/docs/gsmanager.html#using .

1) Methodology

In challenges like mentioned Kaggle challenge the methodology looks like the following:

  • Check which information should be predicted (Regression with a function-like outcome y= f(x) vs. classification (choose from a list of discrete values)
  • Classification/regression information is developed on a small training set. (normally based on a sample of 30% of the total rows)
  • The created algorithms are tested on validity with a separat test dataset (normally based on the other 70% of the rows of the dataset.
  • The prediction should match the value of the variable to be checked.

For this example I put the training & prediction part to Google prediction API in order to later test how good the prediction was.    

2) Prepare your data set

Many data sources have some documentation attached, like in the Kaggle example:

Variable Name Description Type
SeriousDlqin2yrs Person experienced 90 days past due delinquency or worse Y/N
RevolvingUtilizationOfUnsecuredLines Total balance on credit cards and personal lines of credit except real estate and no installment debt like car loans divided by the sum of credit limits percentage
age Age of borrower in years integer
NumberOfTime30-59DaysPastDueNotWorse Number of times borrower has been 30-59 days past due but no worse in the last 2 years. integer
DebtRatio Monthly debt payments, alimony,living costs divided by monthy gross income percentage
MonthlyIncome Monthly income real
NumberOfOpenCreditLinesAndLoans Number of Open loans (installment like car loan or mortgage) and Lines of credit (e.g. credit cards) integer
NumberOfTimes90DaysLate Number of times borrower has been 90 days or more past due. integer
NumberRealEstateLoansOrLines Number of mortgage and real estate loans including home equity lines of credit integer
NumberOfTime60-89DaysPastDueNotWorse Number of times borrower has been 60-89 days past due but no worse in the last 2 years. integer
NumberOfDependents Number of dependents in family excluding themselves (spouse, children etc.) integer
 (original file at http://www.kaggle.com/c/GiveMeSomeCredit/Download/Data%20Dictionary.xls )

The documentation is the start point for the data scientist to see, on what basis he works: likely he will need further explanation & information from the business process owners to get the complete picture of both the task ahead and the information available right now: sometimes more information is needed.

The file cs-training.csv contains 150k rows of data in the structure also described above:

One important precondition to be met for working Prediction API is to have the value to be predicted in the first column: the first column is automatically seen as the only variable, which is to be predicted.

3) Upload your data

Google Cloud Storage can be seen as a large file storage, which organizes groups of related files in buckets: so we need first to create a bucket:

Daniel-Kollers-MacBook-Pro:~ daniel$ gsutil mb -l eu gs://kaggle-exercise
Creating gs://kaggle-exercise/...
Daniel-Kollers-MacBook-Pro:~ daniel$

In this example I named the bucket kaggle-exercise, the “-l eu” to gsutil that I want to have the bucket stored in a EU data center. “gs://” is the standard prefix used to create URL-like bucket names.

“gsutil ls” gives us all existing buckets:

Daniel-Kollers-MacBook-Pro:~ daniel$ gsutil ls
gs://cs-training/
gs://kaggle-exercise/

Now let’s upload the CSV file to cloud storage (with “gsutil cp cs-training.csv gs://kaggle-exercise”):

Daniel-Kollers-MacBook-Pro:Downloads daniel$ gsutil cp cs-training.csv gs://kaggle-exercise
Copying file://cs-training.csv...
Uploading: 7.21 MB/7.21 MB

“gsutil ls gs://kaggle-exercise” gives us a kind of directory listing of the bucket:

Daniel-Kollers-MacBook-Pro:Downloads daniel$ gsutil ls gs://kaggle-exercise
gs://kaggle-exercise/cs-training.csv

So we can see: the csv file is now uploaded.

3) Initiate the training process

The training process can be started on command line interface or a web interface: the web interface is handy for this task and can be seen at http://code.google.com/apis/explorer/#_s=prediction&_v=v1.4 .

As we are not going to use a public dataset we need to “switch to private access”: an authorization dialog checks the user account we want to use.

The main interface of the API explorer shows the available methods:

We select the insert call and need to provide further information in the request body:

The training ID is “credit-training” and th edataStorageLocation is “kaggle-exercise/cs-training.csv” (without the leading “gs://”).

The lower part of the window contains the call result after the click on the “Execute”-button.

Response

200 OK
- Show headers -
{
“kind”: “prediction#training”,
“id”: “credit-training”,
“storageDataLocation”: “kaggle-exercise/cs-training.csv”,
}
Now the training process started… the status can be checked with the trainedmodels.get call:
The result reveals that the training is still running …hold on to the next part, where training process is monitored and predictions can be made.

 

Hinterlasse einen Kommentar

Neues von Google: Cloud Storage & BigQuery v2

Am letzten Samstag fand in Berlin der Google Developer Day Germany statt (nachzulesen unter #gddde  z.B.auf Google+ und Twitter). Dieses Event war das achte der weltweiten Developer Day Tour, bei der Google jährlich seine Neuerungen dem geneigten und technisch interessierten Publikum offenbart.

(Eine Zusammenfassung aller Talks, Slides und vieler Fotosammlungen zum #GDDDE findet Ihr unter https://plus.google.com/104005370658696101293/posts/fp1uRtfH54p )

Thema dieses Blogbeitrags ist neue Produkt BigQuery v2: ein Betriag zur Prediction API folgt in Kürze.

Michael Manoochehri, Developer Advocate für die beiden Themen hatte beide Themen in Berlin vorgestellt, aber auch am Mittwoch vorher im Rahmen einer Veranstaltung bei der Google Technology User Group in München. ( Seine Originalfolien findet Ihr unter http://gdd-2011-cloud-presentation.appspot.com/#1 )

Zu BigQuery:

Mit BigQuery gibt Google Entwickler Werkzeuge in die Hand, große Datenmengen schnell (d.h. mit Antwortzeiten im Sekundenbereich) auswerten zu können. Als technische Schnittstelle steht eine SQL-artige Abfragesprache bereit.

Um Daten mit Hilfe von BigQuery abfragen zu können, muß Google sie erstmal bereitgestellt bekommen: der einzige Weg, um das zu erreichen, führt über den Google Cloud Storage.

Google Cloud Storage

Er ist als großer No-SQL-artiger Datenspeicher implementiert, der die Speicherung von bis zu TB-großen Dateien ermöglicht. Der Zugriff auf die Daten kann dan via Kommandozeile, Web-Interface oder REST-API erfolgen. Zur Authentifizierung von Benutzern steht OAuth 2.0 zur Verfügung: Access Control Lists erlauben die Einschränkung des Zugriffs auf den eigenen Nutzer (private), ausgewählte weitere Nutzer (shared) und den öffentlichen Zugang (public). Die Aktivierung des Speicherplatzes erfolgt über die Google API Console: obwohl eine kostenfreie “Free Tier” (von bis 5GB) vorgesehen ist, müssen bei der Anmeldung Zahlungsdaten angegeben werden.

Mindestens für Entwicklungszwecke ist das Python-basierte GSUtil-Werkzeug hilfreich: es erlaubt die einfache Interaktion mit dem Cloud Storage auf der Kommandozeile z.B. um Daten hochzuladen)

Weiter mit BigQuery…

Das neue ist im Moment, daß BigQuery in einer Version 2 bereitgestellt wird (d.h. eine reduzierte V1-Version lief auch vorher schon): interessierte Nutzer können sich unter https://docs.google.com/spreadsheet/viewform?formkey=dGl4TUlob1RDRndMWVpIb21ORmJPZWc6MA bei Google um Zugang bewerben: das ist auch notwendig, weil das ganze bisher im Rahmen eines Private Beta gezeigt wird. (mal schauen, wie lange es braucht, um Zugang zu bekommen).

Die Objekte & Datenstrukturen innerhalb von BigQuery sehen wie folgt aus:

  • Projekte enthalten 1-n Datensätze, steuern den Datenzugriff (via ACLs) un sind die Basis für die Abrechnung des Services.
  • Datensätze enthalten 1-n Tabellen und können noch granularere ACLs festlegen.
  • Tabellen sind in BigQuery zwei-dimensional definiert (Feldtypen etc. siehe http://code.google.com/intl/de-DE/apis/bigquery/docs/developers_guide.html#tables ).
  • Jobs steuern langlaufende Transaktionen wie Datenimporte, und -exporte.

Die wichtigsten technischen Spezifikationen von BigQuery sind:

  • der Zugang ist über JSON-RPC, REST und Google Apps Script möglich. (eine gute Intro zu Google Apps Script von Ryan Boyd findet sich unter http://bit.ly/tGKPKN )
  • und die Infrastruktur eignet sich zur AdHoc-Abfrage von strukturierten Daten, die im Google Cloud Storage abgelegt sind.

Das ganze ist nützlich, um im BigData-Stil Daten auszuwerten, die die Kapazität des eigenen Notebooks übersteigen: das bedeutet aber auch, daß BigQuery nur eine Lösung für die Ablage und Abfrage von Daten ist: die Logik und das Tooling der Auswertung muß man selbst mitbringen.

Die Logik der Auswertung kann z.B. in Werkzeugen wie R abgelegt sein und auch ablaufen: dafür arbeitet Google an einer Erweiterung zu R (http://code.google.com/p/google-bigquery-r-client/ ), mit der man den BigQuery-Service direkt aufrufen kann.

Neu an der v2 von BigQuery ist, daß die SQL-artige Abfragesprache nun SQL-Joins zwischen Tabellen unterstützt, wobei Michael Manoochehri klar darauf hinweist, dass optimale Antwortzeiten weiterhin bei Abfragen in einer Tabelle zu erwarten sind.

Mit ‘bq‘ existiert auch hier ein Kommandozeilen-Werkzeug, um sehr unkompliziert mit BigQuery kommunizieren zu können.

Hilfreich ist auch noch unter http://code.google.com/intl/de-DE/apis/bigquery/docs/developers_guide.html#csvformat die Beschreibung der CSV-Spezifikationen, damit BigQuery direkt damit arbeiten kann.

Hinterlasse einen Kommentar

Follow

Bekomme jeden neuen Artikel in deinen Posteingang.

Schließe dich 691 Followern an