An engine template is an almost-complete implementation of an engine. In this Engine Template, we have integrated Apache Spark MLlib's Linear Regression algorithm by default.
In statistics, linear regression is an approach for modeling the relationship between a scalar dependent variable and one or more explanatory variables (or independent variables). Linear Regression is widely used in practice, to learn real-valued outputs. The linear regression model of this template is trained using "Stochastic Gradient Descent", an on-line version of gradient descent where the true gradient is approximated by the gradient at a single training point.
The default use case of this Prediction Engine Template is to predict the level of prostate specific antigen from a number of clinical measures in men who were about to receive a radical prostatectomy. There are 8 measures that are a part of the clinical measures. This is based on the dataset that is publicly available.
You can customize it easily to fit your specific use case and needs.
We are going to show you how to create your own prediction engine for production use based on this template.
By default, the template requires the following events to be collected ( we can check this at TemplateFolder/data/import_eventserver.py ):
- user $set event, which set the attributes of the user
- array of features values ( 8 features)
{"features": [-1,-2, -1 , -3, 0, 0, -1, 0]}
- the predicted label
{"prediction": 0.7915352224221848}
We will be using the sample data set from https://github.com/apache/spark/blob/master/data/mllib/ridge-data/lpsa.data The training sample events have the following format (Generated by data/import_eventserver.py):
client.create_event(
event="$set",
entity_type="user",
entity_id=str(count), # use the count num as user ID
properties= {
"attr0" : int(attr[0]),
"attr1" : int(attr[1]),
"attr2" : int(attr[2]),
"attr3" : int(attr[3]),
"attr4" : int(attr[4]),
"attr5" : int(attr[5]),
"attr6" : int(attr[6]),
"plan" : int(plan)
}
First you need to install PredictionIO 0.12.1 (if you haven't done it). Let's say you have installed PredictionIO at /home/yourname/PredictionIO/. For convenience, add PredictionIO's binary command path to your PATH, i.e. /home/yourname/PredictionIO/bin
$ PATH=$PATH:/home/yourname/PredictionIO/bin; export PATH
Once you have completed the installation process, please make sure all the components (PredictionIO Event Server, Elasticsearch, and HBase) are up and running.
$ pio-start-all
For versions before 0.9.1, you need to individually get the PredictionIO Event Server, Elasticsearch, and HBase up and running.
You can check the status by running:
$ pio status
Clone the current repository by executing the following command in the directory where you want the code to reside:
git clone https://github.com/gzilt/pio-regression.git
cd pio-regression
Let's assume you want to use this engine in an application named "MyApp1". You will need to collect some training data for machine learning modeling. You can generate an App ID and Access Key that represent "MyApp1" on the Event Server easily:
$ pio app new MyApp1
You should find the following in the console output:
...
[INFO] [App$] Initialized Event Store for this app ID: 1.
[INFO] [App$] Created new app:
[INFO] [App$] Name: MyApp1
[INFO] [App$] ID: 1
[INFO] [App$] Access Key: 3mZWDzci2D5YsqAnqNnXH9SB6Rg3dsTBs8iHkK6X2i54IQsIZI1eEeQQyMfs7b3F
Take note of the Access Key and App ID. You will need the Access Key to refer to "MyApp1" when you collect data. At the same time, you will use App ID to refer to "MyApp1" in engine code.
$ pio app list will return a list of names and IDs of apps created in the Event Server.
$ pio app list
[INFO] [App$] Name | ID | Access Key | Allowed Event(s)
[INFO] [App$] MyApp1 | 1 | 3mZWDzci2D5YsqAnqNnXH9SB6Rg3dsTBs8iHkK6X2i54IQsIZI1eEeQQyMfs7b3F | (all)
[INFO] [App$] MyApp2 | 2 | io5lz6Eg4m3Xe4JZTBFE13GMAf1dhFl6ZteuJfrO84XpdOz9wRCrDU44EUaYuXq5 | (all)
[INFO] [App$] Finished listing 2 app(s).
Next, let's collect some training data. By default, the Prediction Engine Template reads 9 properties of a user record: attr0, attr1, attr2, attr3, attr4, attr5, attr6, attr7 and plan.
You can send these data to PredictionIO Event Server in real-time easily by making a HTTP request or through the EventClient of an SDK.
Although you can integrate your app with PredictionIO and collect training data in real-time, we are going to import a sample dataset with the provided scripts for demonstration purpose.
Execute the following command in the Engine directory to get the sample public dataset.
curl https://raw.githubusercontent.com/apache/spark/master/data/mllib/ridge-data/lpsa.data --create-dirs -o data/sample_data.txt
A Python import script import_eventserver.py is provided in the template to import the data to Event Server using Python SDK. Replace the value of access_key parameter by your Access Key and run:
$ cd MyRecomendation
$ python data/import_eventserver.py --access_key 3mZWDzci2D5YsqAnqNnXH9SB6Rg3dsTBs8iHkK6X2i54IQsIZI1eEeQQyMfs7b3F
You should see the following output:
Importing data...
67 events are imported.
This python script converts the data file to proper events formats as needed by the event server. Now the training data (the record of the clinical data downloaded above)is stored as events inside the Event Store.
Now you can build, train, and deploy the engine. First, make sure you are under the PredictionIO-MLLib-LinReg-Template.
Under the directory, you should find an engine.json file; this is where you specify parameters for the engine. Make sure the appId defined in the file match your App ID. (This links the template engine with the App)
Parameters for the Linear Regression model are to be set here. If the "intercept" parameter is set to 1, then the linear regression model is trained allowing for an intercept/bias (the constant term in the expression of the target variable as a linear combination of the explanatory variables). If the intercept parameter is 0, the bias term of the linear model is set to 0.
{
"id": "default",
"description": "Default settings",
"engineFactory": "com.github.gzilt.regression.RegressionEngine",
"datasource": {
"params": {
"appId": 1
}
},
"algorithms": [
{
"name": "sgd",
"params": {
"iterations": 100,
"stepSize": 0.01
}
}
]
}
Start with building your pio-regression engine.
$ pio build
This command should take few minutes for the first time; all subsequent builds should be less than a minute. You can also run it with --verbose to see all log messages.
Upon successful build, you should see a console message similar to the following.
[INFO] [Console$] Your engine is ready for training.
Train your engine.
$ pio train
When your engine is trained successfully, you should see a console message similar to the following.
[INFO] [CoreWorkflow$] Training completed successfully.
Now your engine is ready to deploy.
$ pio deploy
This will deploy an engine that binds to http://localhost:8000. You can visit that page in your web browser to check its status.
Now, You can try to retrieve predicted results. For example, to predict the target variable(i.e. prostate specific antigen) of a patient with attr0 = -1 attr1 = -2 attr2 = -1 attr3 = -3 attr4 = 0 attr5 = 0 attr6 = -1 attr7 = 0 (with the attributes here being integers for convenience. They can take float values) you send this JSON { "features": [-1, -2, -1, -3, 0, 0, -1] } to the deployed engine and it will return a JSON of the predicted level of prostate specific antigen. Simply send a query by making a HTTP request or through the EngineClient of an SDK:
import predictionio
engine_client = predictionio.EngineClient(url="http://localhost:8000")
print engine_client.send_query({"features" :[-1, -2, -1, -3, 0, 0, -1, 0]})
The following is sample JSON response:
{"prediction": 0.7915352224221848}