{"revision":"c10276e953456835cdbb1f3a60d58ae1980be353","document":{"id":1066,"path":"api-reference/server-api-reference/c_MLPredictorAPI.md","title":"MLPredictor - Global \\(deprecated\\)","bundle":null,"doc_type":null,"release":"australia","body":"\n# MLPredictor- Global \\(deprecated\\)\n\nThe MLPredictor API provides utility methods for Predictive Intelligence predictions.\n\n**Note:** This API has been deprecated and is intended to be removed in a future release. Refer to [Using ML APIs](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/intelligent-experiences/using-ml-apis.md) for the most recent guidelines.\n\nThe MLPredictor API requires the Predictive Intelligence plugin \\(com.glide.platform\\_ml\\) and is provided within the `sn_ml` namespace.\n\nThis class contains all methods necessary to get prediction results from input data.\n\n**Parent Topic:**[Server API reference](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/server-api-reference/api-server.md)\n\n## MLPredictor - MLPredictor\\(\\)\n\nInstantiates a new MLPredictor object.\n\n|Name|Type|Description|\n|----|----|-----------|\n|None| | |\n\nThe following example shows how to use an MLPredictor object in a business rule to record final values after a prediction.\n\n```\nfunction executeRule(current, previous /*null when async*/) {\n\tvar predictor = new MLPredictor();\n\tpredictor.recordFinalValuesInPredictionResults(current, \"On close\");\n\n}(current, previous);\n```\n\n## MLPredictor - applyPrediction\\(GlideRecord now\\_GR, Array solutions\\)\n\nSets predicted values from an array of specified solutions to a specified record.\n\n|Name|Type|Description|\n|----|----|-----------|\n|now\\_GR|GlideRecord|The record on which to apply the array of predicted solutions.|\n|solutions|Array|Specified solution objects associated with the GlideRecord.|\n\n|Type|Description|\n|----|-----------|\n|void| |\n\nThe following example demonstrates using the applyPrediction\\(\\) method in a business rule.\n\n```\n(function executeRule(current, previous /*null when async*/) {\n    var mlPredictor = new MLPredictor();\n    //Get the list of active solutions for the glide record table\n    var solutions = mlPredictor.findActiveSolutionsForRecord(current);\n    //Run prediction and apply predicted value to the record\n    mlPredictor.applyPrediction(current, solution);\n\n})(current, previous);\n```\n\n## MLPredictor - applyPredictionForSolution\\(GlideRecord now\\_GR, Object solution\\)\n\nApplies a predicted value from a specified classification solution to the specified GlideRecord.\n\nFor each solution in the GlideRecord, call this method to predict the results and set the field value on the incident to those results.\n\n|Name|Type|Description|\n|----|----|-----------|\n|now\\_GR|GlideRecord|GlideRecord object containing values on which to run a prediction and apply the results.|\n|solution|Object|Classification solution object to be executed.|\n\n|Type|Description|\n|----|-----------|\n|Boolean|True upon prediction success, error otherwise.|\n\nTo use this template, copy the Incident Based Prediction \\(Template\\) business rule, make the new record Active, and follow the commented instructions to initialize the solutionNames variable.\n\n```\n(function executeRule(current, previous /*null when async*/) {\n\tvar solutionNames = [\"solution1\", \"solution2\", ...];\n\n\t/* For domain separation (MSP) use case */\n//\tvar solutionNames;\n//\tif (current.sys_domain == \"A\")\n//\t\tsolutionNames = [\"solution_A1\", \"solution_A2\", ...];\n//\telse if (current.sys_domain == \"B\")\n//\t\tsolutionNames = [\"solution_B1\", \"solution_B2\", ...];\n//\telse\n//\t\t...\n\n\tvar predictor = new MLPredictor();\n\tvar info = \"\";\n\tsolutionNames.forEach(function(solutionName) {\n\t\tvar solution = predictor.findActiveSolution(solutionName);\n\t\tif (!solution)\n\t\t\treturn;\n\n\t\t/* The next line of code does the prediction and updates the current record. */\n\t\tpredictor.applyPredictionForSolution(current, solution);\n\n\t\t/* If no prediction is done, do not build the prediction info message. */\n\t\tif (!predictor.applyPredictionForSolution(current, solution))\n\t\t\treturn;\n\n\t\t/* If user doesn't have 'itil' role, we don't build prediction info message. */\n\t\tif (!gs.hasRole('itil'))\n\t\t\treturn;\n\n\t\t/* Building prediction info message */\n\t\tvar fieldName = solution.getPredictedField();\n\t\tvar fieldLabel = current.getElement(fieldName).getED().getLabel();\n\t\tvar predictedDisplayValue = current.getDisplayValue(fieldName);\n\t\tvar msg = gs.getMessage(\"Predicted {0} for {1}.\", [predictedDisplayValue, fieldLabel]);\n\t\tif (info.length > 0)\n\t\t\tinfo += \" \";\n\t\tinfo += msg;\n\t});\n\t/* Print out prediction info message on screen. */\n\tif (info.length > 0) {\n\t\tvar incidentUrl = \"<a href='\"+current.getLink()+\"'>\"+current.number+\":</a>\";\n\t\tgs.addInfoMessage(incidentUrl + \" \" + info);\n\t}\n})(current, previous);\n```\n\n## MLPredictor - findActiveSolution\\(String solutionName\\)\n\nGets the solution object.\n\nThis method only returns the solutions if the ml\\_solution definition and solution are active.\n\n|Name|Type|Description|\n|----|----|-----------|\n|solutionName|String|Name of the ml\\_solution record.|\n\n|Type|Description|\n|----|-----------|\n|Object|Solution object for the specified `solutionName` if the ml\\_solution definition and solution is active, null otherwise.|\n\nThis example takes a hard-coded value and passes it to a specified Machine Learning model. You can use the outcome and confidence variables to set values or other business logic.\n\n```\nvar solutionName = 'ml_incident_assignment';\n  var shortDescriptionValue = \"Unable to connect!\"\n  var input = {\n  short_description : shortDescriptionValue\n  };\n  var MLP = new MLPredictor();\n  var solution = MLP.findActiveSolution(solutionName);\n  var predictedOutcome = solution.predictText(input);\n  var outcome = predictedOutcome.predictedValue();\n  var confidence = predictedOutcome.confidence();\n  gs.info(\"Predicted value: \" + outcome)\n  gs.info(\"Confidence: \" + confidence)\n        \n```\n\nOutput:\n\n```\nDxC_ML:\n        ******* Finished Prediction********* *** Script: Predicted value: Software *** Script:\n        Confidence: 80.78079080096245\n```\n\n## MLPredictor - findActiveSolutionsForRecord\\(GlideRecord now\\_GR\\)\n\nGets active solutions for a table in a specified GlideRecord.\n\n|Name|Type|Description|\n|----|----|-----------|\n|now\\_GR|GlideRecord|GlideRecord from which to collect active solution objects.|\n\n|Type|Description|\n|----|-----------|\n|Array|Array of active solution objects associated with the table that the specified record is for.|\n\nThis script passes a GlideRecord \\(such as an incident\\), and processes all solutions for the GlideRecord, returning the values for each.\n\n```\n/* This is only to get a hard-coded GR */\n     var current = new GlideRecord('incident');\n     current.get('965c9e5347c12200e0ef563dbb9a7156');\n     var predictor = new MLPredictor();\n     var solutions = predictor.findActiveSolutionsForRecord(current);\n     solutions.forEach(function(solution) {\n         var outcome = solution.predict(current);\n         /* Use this to set the field to the predicted value in the GlideRecord */\n         var fieldName = solution.getPredictedField();\n         current[fieldName] = outcome.predictedValue();\n         current.update();\n\n         gs.info(\"Predicted value: \" + outcome.predictedValue())\n         gs.info(\"Confidence: \" + outcome.confidence())\n});\n```\n\nOutput \\(Assignment Group prediction\\):\n\n```\nDxC_ML: ******* Finished Prediction*********\n        *** Script: Predicted value: Software *** Script: Confidence:\n        99.74530683715315\n```\n\nOutput \\(Category prediction\\):\n\n```\nDxC_ML:\n        ******* Finished Prediction********* *** Script: Predicted value: Software *** Script:\n        Confidence: 98.7172805135524\n```\n\n## MLPredictor - getPredictedValue\\(Object solution, Object outcome\\)\n\nGets the predicted value for a specified solution based on the specified prediction outcome.\n\n|Name|Type|Description|\n|----|----|-----------|\n|solution|Object|Solution from which to get the predicted value.|\n|outcome|Object|Prediction outcome results for the specified solution \\(var outcome = solution.predict\\(now\\_GR\\)\\).|\n\n|Type|Description|\n|----|-----------|\n|String|Predicted value for specified solution based on the specified outcome of the prediction.|\n|Null|Returns null if the prediction confidence does not satisfy thresholds.|\n\n## MLPredictor - getPredictions\\(GlideRecord now\\_GR, Object solution, Object options\\)\n\nGets predictions for a specified solution.\n\n<table id=\"table_hqw_pbm_yfb\" class=\"parameters\"><thead><tr><th>\n\nName\n\n</th><th>\n\nType\n\n</th><th>\n\nDescription\n\n</th></tr></thead><tbody><tr><td>\n\nnow\\_GR\n\n</td><td>\n\nGlideRecord\n\n</td><td>\n\nGlideRecord to be predicted.\n\n</td></tr><tr><td>\n\nsolution\n\n</td><td>\n\nObject\n\n</td><td>\n\nSolution object to be executed.\n\n</td></tr><tr><td>\n\noptions\n\n</td><td>\n\nObject\n\n</td><td>\n\nOptional JSON object key value pair with the following properties:-   options.top\\_n: If provided, returns results up to the expected number of predictions, otherwise default is read from the `glide.platform_ml.max_num_predictions` system property.\n-   options.apply\\_threshold: Checks the threshold value \\(solution threshold for similarity, class level threshold for classification\\) for the solution and applies it to the result set. Default value is true.\n\n</td></tr></tbody>\n</table>|Type|Description|\n|----|-----------|\n|Array|Array of predicted outcome objects|\n\nThe following example calls a specified solution and executes predictions on it.\n\n```\nfunction printOutcomeArr(outcomeArr) {\ngs.print('################## Results ##################');\nfor (var i=0; i<outcomeArr.length; i++) {\n    var outcome = outcomeArr[i];\n    gs.print((i+1) + ' : ' + outcome.predictedValue() + ', ' + outcome.predictedValueSysId() + ', ' + outcome.confidence());\n}\n}\n\nvar solutionName = 'ml_x_snc_global_prop_flip_test';\nvar predictor = new MLPredictor();\nvar solution = predictor.findActiveSolution(solutionName);\n\nvar now_GR = new GlideRecord('incident');\nnow_GR.get('1c741bd70b2322007518478d83673af3');\n\nvar options = {};\noptions.top_n = '10';            // top_n is an integer between 1 and 1000\noptions.apply_threshold = false; // Value can be set to true or false\n\nprintOutcomeArr(predictor.getPredictions(now_GR, solution, options));\n```\n\n## MLPredictor - isClassificationSolution\\(Object solution\\)\n\nIdentifies if a solution object is a classification type.\n\n|Name|Type|Description|\n|----|----|-----------|\n|solution|Object|Name of the ML solution.|\n\n|Type|Description|\n|----|-----------|\n|Boolean|Returns true if the input solution is a classification type, false otherwise.|\n\n```\nvar isClassificationSolution = this.isClassificationSolution(solution);\n \n\t//classification solution each class has different threshold\n\t//therefore needs to get all the results from ml engine\n\tif (applyThreshold && isClassificationSolution) {\n\t\tvar maxClassificationTopN = 50;\n\t\toutcomeArr = solution.predictTopN(now_GR, maxClassificationTopN);\n\t}\n\telse  {\n\toutcomeArr = solution.predictTopN(now_GR, topN);\n\t}\n \n\tif (outcomeArr === null) {\n\t\t//instead of returning null returning empty array\n\t\treturn [];\n\t}\n```\n\n## MLPredictor - isSimilaritySolution\\(Object solution\\)\n\nIdentifies if a solution object is a similarity type.\n\n|Name|Type|Description|\n|----|----|-----------|\n|solution|Object|Name of the ML solution; for example, ml\\_incident\\_categorization.|\n\n|Type|Description|\n|----|-----------|\n|Boolean|Returns true if the input solution is a similarity type, false otherwise.|\n\n## MLPredictor - outcome.confidence\\(\\)\n\nGets the confidence of the predicted value.\n\n|Name|Type|Description|\n|----|----|-----------|\n|None| | |\n\n|Type|Description|\n|----|-----------|\n|String|The estimated precision of the prediction as a percentage. For example, **53.84615375762915**.|\n\n```\nvar MLP = new MLPredictor();\n  var solution = MLP.findActiveSolution(solutionName);\n  var predictedOutcome = solution.predictText(input);\n  var outcome = predictedOutcome.predictedValue();\n  var confidence = predictedOutcome.confidence();\n  gs.info(\"Predicted value: \" + outcome)\n  gs.info(\"Confidence: \" + confidence)\n```\n\n## MLPredictor - outcome.predictedValue\\(\\)\n\nGets the predicted value from the MLPredictor outcome object.\n\n|Name|Type|Description|\n|----|----|-----------|\n|None| | |\n\n|Type|Description|\n|----|-----------|\n|String|Predicted value from the Outcome object.|\n\n```\nvar MLP = new MLPredictor();\n  var solution = MLP.findActiveSolution(solutionName);\n  var predictedOutcome = solution.predictText(input);\n  var outcome = predictedOutcome.predictedValue();\n  var confidence = predictedOutcome.confidence();\n  gs.info(\"Predicted value: \" + outcome)\n  gs.info(\"Confidence: \" + confidence)\n```\n\n## MLPredictor - outcome.predictedValueSysId\\(\\)\n\nGets the sys\\_id of the predicted value.\n\n|Name|Type|Description|\n|----|----|-----------|\n|None| | |\n\n|Type|Description|\n|----|-----------|\n|String|Predicted value sys\\_id.|\n\n```\nfunction printOutcomeArr(outcomeArr) {\ngs.print('################## Results ##################');\nfor (var i=0; i<outcomeArr.length; i++) {\n    var outcome = outcomeArr[i];\n    gs.print((i+1) + ' : ' + outcome.predictedValue() + ', ' + outcome.predictedValueSysId() + ', ' + outcome.confidence());\n}\n```\n\n## MLPredictor - recordFinalValuesInPredictionResults\\(GlideRecord now\\_GR, String reason\\)\n\nSets final prediction result values to a specified GlideRecord with an optionally specified reason.\n\n|Name|Type|Description|\n|----|----|-----------|\n|now\\_GR|GlideRecord|GlideRecord on which to set the final prediction result values.|\n|reason|String|Optional. Reason for applying results.|\n\n|Type|Description|\n|----|-----------|\n|void| |\n\nIn following example, the recordFinalValuesInPredictionResults\\(\\) method is called when the incident is closed.\n\n```\n(function executeRule(current, previous /*null when async*/) {\n\tvar predictor = new MLPredictor();\n\tpredictor.recordFinalValuesInPredictionResults(current, \"On close\");\n\n})(current, previous);\n```\n\n## MLPredictor - solution.getCapability\\(\\)\n\nGets the capability information of a trained solution.\n\n|Name|Type|Description|\n|----|----|-----------|\n|None| | |\n\n|Type|Description|\n|----|-----------|\n|String|Definition ID and version of the trained solution, error message otherwise|\n\n## MLPredictor - solution.getName\\(\\)\n\nGets the name of the solution used for prediction.\n\n|Name|Type|Description|\n|----|----|-----------|\n|None| | |\n\n|Type|Description|\n|----|-----------|\n|String|The name of the solution to use for predictions; for example, `ml_incident_categorization`|\n\n## MLPredictor - solution.getPredictedField\\(\\)\n\nGets the predicted value of a solution.\n\n|Name|Type|Description|\n|----|----|-----------|\n|None| | |\n\n|Type|Description|\n|----|-----------|\n|String|Value of a solution's predicted output field|\n\n```\n/* Get a hard-coded GR */\n     var current = new GlideRecord('incident');\n     current.get('965c9e5347c12200e0ef563dbb9a7156');\n     var predictor = new MLPredictor();\n     var solutions = predictor.findActiveSolutionsForRecord(current);\n     solutions.forEach(function(solution) {\n         var outcome = solution.predict(current);\n         /* Use this to set the field to the predicted value in the GlideRecord */\n\n         var fieldName = solution.getPredictedField();\n         current[fieldName] = outcome.predictedValue();\n         current.update();\n         gs.info(\"Predicted value: \" + outcome.predictedValue())\n         gs.info(\"Confidence: \" + outcome.confidence())\n});\n```\n\n## MLPredictor - solution.getThreshold\\(String className\\)\n\nGets the solution threshold.\n\nThe threshold represents a percentage reflecting the minimum prediction accuracy.\n\n|Name|Type|Description|\n|----|----|-----------|\n|className|String|A specified categorical value of the solution output field|\n\n|Type|Description|\n|----|-----------|\n|Number|Value of the threshold represented as a percentage between 0 and 100.|\n\n## MLPredictor - solution.getVersion\\(\\)\n\nGets the version of the active solution.\n\n|Name|Type|Description|\n|----|----|-----------|\n|None| | |\n\n|Type|Description|\n|----|-----------|\n|String|Version of the active solution|\n\n## MLPredictor - solution.isActive\\(\\)\n\nDetermines if the specified solution is active.\n\n|Name|Type|Description|\n|----|----|-----------|\n|None| | |\n\n|Type|Description|\n|----|-----------|\n|Boolean|True if the solution is active, false otherwise|\n\n## MLPredictor - solution.predict\\(GlideRecord now\\_GR, Object threshold\\)\n\nGets solution prediction results as an Outcome object.\n\n|Name|Type|Description|\n|----|----|-----------|\n|now\\_GR|GlideRecord|GlideRecord of the solution input table|\n|threshold|Object|Threshold value \\(solution level threshold for similarity, class level threshold for classification\\)|\n\n|Type|Description|\n|----|-----------|\n|Object|Prediction outcome result of the specified solution \\(var outcome = solution.predict\\(now\\_GR\\)\\)|\n\n```\nsolutions.forEach(function(solution) {\n         var outcome = solution.predict(current);\n         /* Use this to set the field to the predicted value in the GlideRecord\n         var fieldName = solution.getPredictedField();\n         current[fieldName] = outcome.predictedValue();\n         current.update();\n         */\n         gs.info(\"Predicted value: \" + outcome.predictedValue())\n         gs.info(\"Confidence: \" + outcome.confidence())\n});\n```\n\n## MLPredictor - solution.predictTopN\\(GlideRecord now\\_GR, Object topN\\)\n\nReturns a list of outcome objects up to the expected number of predictions. Maximum number 1000 predictions.\n\n|Name|Type|Description|\n|----|----|-----------|\n|now\\_GR|GlideRecord|GlideRecord of the solution|\n|topN|Object|Expected number of predictions, any number over 1000 returns 1000 results|\n\n|Type|Description|\n|----|-----------|\n|Array|List of outcome objects in an array including GlideRecord, threshold, system ID, and expected number of predictions \\(topN object\\)|\n\n```\nvar isClassificationSolution = this.isClassificationSolution(solution);\n \n\t//classification solution each class has different threshold\n\t//therefore needs to get all the results from ml engine\n\tif (applyThreshold && isClassificationSolution) {\n\t\tvar maxClassificationTopN = 50;\n\t\toutcomeArr = solution.predictTopN(now_GR, maxClassificationTopN);\n\t}\n\telse  {\n\t\toutcomeArr = solution.predictTopN(now_GR, topN);\n\t}\n \n\tif (outcomeArr === null) {\n\t\t//instead of returning null returning empty array\n\t\treturn [];\n\t}\n```\n\n"}}