Overview


Nowadays, supermarkets have become popular amongst people to buy all their household needs. It has become quite convenient as they can get all the products they need at one place. But on the other hand, supermarket chain having multiple stores performing in uneven manner.


Problem Statement


To determine if sales will increase or decrease for the particular item.


Our Approach


To solve the problem, we use INTELLIHUB . Lets see how INTELLIHUB works:

  • First user needs to uploads the train as well as test data.
  • It is stored in the cloud.
  • Data from cloud then goes to ML (a Machine Learning Module in INTELLIHUB ). In ML, you have 3 ML Libraries (Weka, H2O & Scikit) to choose from.
  • Using ML, you train a model.
  • You can evaluate using RMSE, accuracy and other different metrics.
  • You can then use the above model for prediction.


Data Definition


The data set contains information about 4650 past transactions. The variables in the data set are:

  • Item_Identifier: Unique product ID
  • Item_Weight: Weight of product
  • Item_Fat_Content: Whether the product is low fat or regular
  • Item_Visibility: The % of total display area of all products in a store allocated to the particular product
  • Item_Type: The category to which the product belongs
  • Item_MRP: Maximum Retail Price (list price) of the product
  • Outlet_Identifier: Unique store ID
  • Outlet_Age: Age of store in years
  • Outlet_Size: The size of the store in terms of ground area covered
  • Outlet_Location_Type: The type of city in which the store is located
  • Outlet_Type: Whether the outlet is just a grocery store or some sort of supermarket
  • Item_Outlet_Sales: Sales of the product in the particular store (Label)

Intellihub gives the flexibility of choosing features upto 20 columns.



Model Building


  • We want to create a model in which it can predict sales.
  • This can help to understand the properties of products and stores which play a key role in increasing sales
  • We will be building regression models using Linear Regression on INTELLIHUB
  • We will then use the above model for our test dataset.

While doing our modeling with IntelliHubML we will be using some terminologies:

  • Training Data : The data you use for training your model. It contains all the information you have collected about the problem statement.
  • Test Data : The data you use for testing the model. You can make predictions on this data.
  • Features : These are all the columns in your dataset which you use for training your model.
  • Class/Label : This is the column which identifies the particular record and the one you want to predict.

First we need to create an App from console and enable API for IntelliHubML.In Intellihub, we can build model:

  • Using SDK (For Developer)


Using SDK


If you want to develop a model using SDK, just copy API key from INTELLIHUB Console.




Connect To IntelliHub

Description

You can access the services provided by enabling API for IntelliHubML. INTELLIHUB provides IntellihubClient where you have to pass your APP KEY as an argument.

Code


import intellihub

c = intellihub.IntellihubClient("YOUR API KEY")
 

import com.spotflock.IntellihubClient;

IntellihubClient c = new IntellihubClient("YOUR API KEY");
 

Upload Train And Test Files

Description

As Intellihub is a cloud platform, It stores Train and Test Files remotely. File upload API will return file storage locations from Cloud Storage in response.

Upload Train File


train_file_store_response = c.store("path/to/train/file")

train_data = train_file_store_response["fileUrl"]
 

JSONObject train_file_store_response = c.store("path/to/test/file");
JSONObject  train_data= train_file_store_response("fileUrl");
System.out.println(train_data.toString());
 

train_data file url

'/spotflock-studio-prod/xxxxx@xxxxxxxx.com/1551936734455-sales_train.csv'

Upload Test File


test_file_store_response = c.store("path/to/test/file")

test_data = test_file_store_response["fileUrl"]
 

JSONObject test_file_store_response = c.store("path/to/test/file");
JSONObject test_data = test_file_store_response("fileUrl");
System.out.println(test_data.toString());
 

test_data file url

'/spotflock-studio-prod/xxxxx@xxxxxxx.com/1551936725437-sales_test.csv'

Regression Model

Description

This API would enable you to train a regression model. The model takes some time to be trained and thus the job status has to be checked. Once the job is completed, the job output API would give you the model info.

Arguments

lib Library for training the model. Currently we are supporting spotflock and weka libraries.
service Valid parameter values are classification and regression.
model_name Model name and with this name model will be saved.
algorithm Algorithm by which model will be trained.
dataset_url Train dataset file location in Spotflock storage.
label Label of the column in train dataset file.
train_percentage % of data will be used for training and model will be tested against remaining % of data.
features Column names list which is used to train regression model.
save_model If True, model will be saved.

Code


train_response = c.train("regression", "LinearRegression", train_data, "Item_Outlet_Sales",
["Item_Weight","Item_Fat_Content","Item_Visibility", "Item_Type","Item_MRP","Outlet_Identifier","Outlet_Age","Outlet_Size",
"Outlet_Location_Type","Outlet_Type"],"Sales - Linear Regression","weka", 70, True)

train_response

{
    'code': 0,
    'data': {
        'jobId': 210,
        'name': 'weka_regression_train',
        'library': 'weka',
        'service': 'Regression',
        'task': 'TRAIN',
        'state': 'RUN',
        'startTime': '2019-03-07T05:34:15.851+0000',
        'endTime': None,
        'request': {
            'library': 'weka',
            'config': {
                'name': 'Sales Data Model',
                'label': 'Item_Outlet_Sales',
                'trainPercentage': 80,
                'algorithm': 'LinearRegression',
                'features': ['Item_Weight','Item_Fat_Content','Item_Visibility',
'Item_Type','Item_MRP','Outlet_Identifier','Outlet_Age','Outlet_Size','Outlet_Location_Type','Outlet_Type'],
                'saveModel': True,
                'params': {},
                'datasetUrl': '/spotflock-studio-prod/xxxxx@xxxxxxx.com/1551936734455-sales_train.csv'
            }
        }
    }
}
lib Library for training the model. Currently we are supporting spotflock and weka libraries.
service Valid parameter values are classification and regression.
modelName Model name and with this name model will be saved.
algorithm Algorithm by which model will be trained.
datasetUrl Train dataset file location in Spotflock storage.
label Label of the column in train dataset file.
trainPercentage % of data will be used for training and model will be tested against remaining % of data.
features Column names list which is used to train regression model.
saveModel If True, model will be saved.

Code


JSONArray features = new JSONArray();
features.put("Item_Weight");
features.put("Item_Fat_Content");
features.put("Item_Visibility");
features.put("Item_Type");
features.put("Item_MRP");
features.put("Outlet_Identifier");
features.put("Outlet_Age");
features.put("Outlet_Size");
features.put("Outlet_Location_Type");
features.put("Outlet_Type");

JSONObject params = new JSONObject();
params.put("lib","weka");
params.put("saveModel",true);
params.put("trainPercentage",70);
params.put("modelName","Sales - Linear Regression");

String response = c.train("regression","LinearRegression", trainData, 
"Item_Outlet_Sales", features, params); JSONObject trainResponse = new JSONObject(response);

trainResponse


{
    "code": 0,
    "data": {
        "jobId": 210,
        "name": "weka_regression_train",
        "library": "weka",
        "service": "Regression",
        "task": "TRAIN",
        "state": "RUN",
        "startTime": "2019-03-07T05:34:15.851+0000",
        "endTime": null,
        "request": {
            "library": "weka",
            "config": {
                "name": "Sales Data Model",
                "label": "Item_Outlet_Sales",
                "trainPercentage": 80,
                "algorithm": "AdditiveRegression",
                "features": ["Item_Weight","Item_Fat_Content","Item_Visibility",
"Item_Type","Item_MRP","Outlet_Identifier","Outlet_Age","Outlet_Size","Outlet_Location_Type","Outlet_Type"],
                "saveModel": true,
                "params": {},
                "datasetUrl": "/spotflock-studio-prod/xxxxx@xxxxxx.com/1551936734455-sales_train.csv"
            }
        }
    }
}

Get Train Job Status

Description

The train/predict jobs take some amount of time to be completed and so their status can be checked with this API.

Code


train_job_status_response = c.job_status(train_response["data"]["jobId"])
 

JSONObject trainJobStatusResponse = c.jobStatus(trainResponse.getJSONObject("data")
.get("jobId")); System.out.println(trainJobStatusResponse.toString());

train_job_status_response


{
  "jobId":438,
  "appId":1555944250593,
  "name":"weka_regression_train",
  "library":"weka",
  "service":"Regression",
  "task":"TRAIN",
  "state":"FINISH",
  "startTime":"2019-04-29T05:55:00.499+0000",
  "endTime":"2019-04-29T05:55:02.234+0000"
}

Get Train Job Output

Description

Once the job status is completed, the job output can be retrieved from this API.

Code


train_job_output_response = c.job_output(train_response["data"]["jobId"])
 

JSONObject trainJobOutputResponse = apiKey.jobOutput(trainResponse.getJSONObject("data")
.get("jobId")); System.out.println(trainJobOutputResponse.toString());

Evaluation Metrics

kappa The Kappa statistic (or value) is a metric that compares an Observed Accuracy with an Expected Accuracy (random chance).
recall Recall is also referred to as the true positive rate or sensitivity.
correct Correct is given by total number of correctly predicted values.
accuracy This is the ratio of the number of correct predictions out of all predictions made.
rocCurve ROC (Receiver Operating Characteristic) Curve is to examine the performance of a binary classifier, by creating a graph of the True Positives vs. False Positives.
errorRate Error Rate is the ratio of total number of incorrectly predicted instances to total number of instances.
inCorrect Incorrect is given by total number of incorrectly predicted values.
precision The precision for a class is the number of true positives divided by the total number of elements labeled as belonging to the positive class.
areaUnderPRC total area calculated under PRC (Precision Recall Curve) curve.
areaUnderROC total area calculated under ROC curve.
priorEntropy Entropy is a measure of the uncertainty associated with a random variable.
numTrueNegatives Total number of instances predicted correctly as Negative.
numTruePositives Total number of instances predicted correctly as Positive.
trueNegativeRate Ratio of number of True Negatives to total number of negatives.
truePositiveRate Ratio of number of True Positives to total number of positives.
falseNegativeRate Ratio of number of False Negatives to total number of negatives.
falsePositiveRate Ratio of number of False Positives to total number of positives.
numFalseNegatives Total number of instances where incorrectly predicted as Negatives instead of Positives.
numFalsePositives Total number of instances where incorrectly predicted as Positives instead of Negatives.
pearsonCorrelation Evaluates the worth of an attribute by measuring the pearsonCorrelation between it and the target.
confusionMatrixHeaders You can create confusion matrix in the order of confusion Matrix headers.
correlationCoefficient This parameter tells you how much true value and predicted value are related. It gives values between −1 and 1, where 0 is no relation, 1 is a very strong Linear Relation and −1 is an Inverse Linear Relation.
mathewsCorrelationCoefficient The Matthews Correlation Coefficient has a range of -1 to 1 where -1 indicates a completely wrong binary classifier while 1 indicates a completely correct binary classifier.

Response

{
    'id': 181,
    'jobId': 210,
    'output': {
        'eval': {
            'kappa': 0.0,
            'recall': {},
            'correct': 0.0,
            'accuracy': 0.0,
            'revision': '14755',
            'rocCurve': None,
            'errorRate': 1375.9288880135039,
            'inCorrect': 0.0,
            'precision': {},
            'areaUnderPRC': {},
            'areaUnderROC': {},
            'priorEntropy': 'NaN',
            'confusionMatrix': None,
            'numTrueNegatives': {},
            'numTruePositives': {},
            'trueNegativeRate': {},
            'truePositiveRate': {},
            'falseNegativeRate': {},
            'falsePositiveRate': {},
            'numFalseNegatives': {},
            'numFalsePositives': {},
            'pearsonCorrelation': {
                'Item_MRP': 0.5674370472214295,
                'Item_Weight': 0.008002590997112305,
                'Item_Visibility': -0.12586641928427866
            },
            'confusionMatrixHeaders': [],
            'correlationCoefficient': 0.0,
            'mathewsCorrelationCoefficient': {}
        },
        'modelUrl': '/spotflock-studio-prod/22/1552024436737-Sales_Data_Model_6647825745227784853.mdl'
    }
}

Get Model Url

Description

After Train job is finished, you can get the model url.

Code

`

model = train_job_output_response["output"]["modelUrl"]
 

String model = trainJobOutputResponse.getJSONObject("output").get("modelUrl");
 

By Printing model

'/spotflock-studio-prod/22/1552024436737-Sales_Data_Model_6647825745227784853.mdl'

Predict on Test Data

Description

The below code is to predict on test data by passing the model url that was obtained from previous response.

Code


predict_response = c.predict("weka", "regression", test_data, model)
 

predict_response


params = new JSONObject();
params.put("lib","weka");
JSONObject predictResponse = c.predict("regression", testData, model, params);
 

predictResponse

{
    'code': 0,
    'data': {
        'jobId': 211,
        'name': 'weka_regression_predict',
        'library': 'weka',
        'service': 'Regression',
        'task': 'PREDICT',
        'state': 'RUN',
        'startTime': '2019-03-06T11:53:02.722+0000',
        'endTime': None,
        'request': {
            'library': 'weka',
            'config': {
                'modelUrl': '/spotflock-studio-prod/22/1552024436737-Sales_Data_Model_6647825745227784853.mdl',
                'params': {},
                'datasetUrl': '/spotflock-studio-prod/anurag@spotflock.com/1551936725437-sales_test.csv'
            }
        }
    }
}

Get Prediction Job Status

Description

The train/predict jobs take some amount of time to be completed and so their status can be checked with this API.

Code


predict_job_status_response = c.job_status(predict_response["data"]["jobId"])
 

predict_job_status_response


JSONObject predictJobStatusResponse = c.jobStatus(predictResponse.getJSONObject("data")
.get("jobId"));

predictJobStatusResponse


{
  "jobId":439,
  "appId":1555944250593,
  "name":"weka_regression_predict",
  "library":"weka",
  "service":"Regression",
  "task":"PREDICT",
  "state":"FINISH",
  "startTime":"2019-04-29T05:55:27.324+0000",
  "endTime":"2019-04-29T05:55:33.962+0000"
}

Get Prediction Job Output

Description

Once the job status is completed, the job output can be retrieved from this API.

Code


predict_job_output_response = c.job_output(predict_response["data"]["jobId"])
 

predict_job_output_response


JSONObject predictJobOutputResponse = c.jobOutput(predictResponse.getJSONObject("data")
.get("jobId")); System.out.println(predictJobOutputResponse.toString());

predictJobOutputResponse

{
    'id': 182,
    'jobId': 211,
    'output': {
        'reqId': 211,
        'predFileUrl': '/spotflock-studio-prod/22/1552024447138-prediction.csv'
    }
}

Get Prediction File Url

Description

Once the Predict job is completed, get the prediction file url.

Code


pred_file = predict_job_output_response['output']['predFileUrl']
 

String pred_file = predictJobOutputResponse.getJSONObject("output").get("predFileUrl")
 

pred_file

'/spotflock-studio-prod/22/1552024447138-prediction.csv'

Download Prediction File

Description

You can download the predicted file as csv by using below code.

Code


prediction_response = c.download(pred_file)
 

prediction_response


JSONObject predictionResponse = c.download(pred_file);
FileWriter outputfile = new FileWriter(ENTER YOUR OUTPUT FILE PATH);
CSVWriter writer = new CSVWriter(outputfile);
writer.writeAll(prediction_response.toString());
writer.close();
 

predictionResponse

Item_Weight,Item_Visibility,Item_MRP,Item_Outlet_Sales,null
20.75,0.007564836,107.8622,1913.861388
8.3,0.038427677,87.3198,1463.930171
14.6,0.099574908,241.7538,3606.521849
7.315,0.015388393,155.034,2614.21968
...
...
                                

Summary


  • The model will forecast sales.
  • By looking at sales, we will able to determine if sales for the particular item will increase or decrease.
  • This will help us in understanding which item’s sales will decrease and in which outlet.
  • Accordingly we can plan promotion activities.