### Install PMML4S via SBT
Source: https://github.com/autodeployai/pmml4s/blob/master/README.md
Add the PMML4S dependency to your build.sbt file.
```scala
libraryDependencies += "org.pmml4s" %% "pmml4s" % pmml4sVersion
```
--------------------------------
### Install PMML4S via Maven
Source: https://github.com/autodeployai/pmml4s/blob/master/README.md
Add the PMML4S dependency to your pom.xml file.
```xml
org.pmml4s
pmml4s_${scala.version}
${pmml4s.version}
```
--------------------------------
### Load PMML Model in Java
Source: https://github.com/autodeployai/pmml4s/blob/master/README.md
Load a PMML model from a file using the Model.fromFile() method. Ensure the model file path is correct.
```java
import org.pmml4s.model.Model;
Model model = Model.fromFile("single_iris_dectree.xml");
```
--------------------------------
### Load PMML Model from File Path
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Loads a PMML model from a specified file path. Ensure the path points to a valid PMML file.
```scala
import org.pmml4s.model.Model
import scala.io.Source
// Load from a file path
val model = Model.fromFile("path/to/model.pmml")
```
--------------------------------
### Load PMML Model
Source: https://github.com/autodeployai/pmml4s/blob/master/README.md
Load a model from a URL or a local file path.
```scala
import org.pmml4s.model.Model
import scala.io.Source
// load a model from an IO source that supports various sources, e.g. from a URL locates a PMML model.
val model = Model(Source.fromURL(new java.net.URL("http://dmg.org/pmml/pmml_examples/KNIME_PMML_4.1_Examples/single_iris_dectree.xml")))
```
```scala
import org.pmml4s.model.Model
// load a model from those help methods, e.g. pathname, file object, a string, an array of bytes, or an input stream.
val model = Model.fromFile("single_iris_dectree.xml")
```
--------------------------------
### Load PMML Model from URL
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Loads a PMML model directly from a URL. The library handles fetching the model from the specified web address.
```scala
// Load from a URL
val model = Model(Source.fromURL(new java.net.URL("http://example.com/model.pmml")))
```
--------------------------------
### Load and Predict with Java Map
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Load a PMML model and perform predictions using a Java Map for input. Handles classification and probability outputs.
```java
import org.pmml4s.model.Model;
import org.pmml4s.data.Series;
import org.pmml4s.common.StructType;
import org.pmml4s.common.StructField;
import org.pmml4s.util.Utils;
import java.util.Map;
import java.util.HashMap;
public class PmmlExample {
public static void main(String[] args) {
// Load model
Model model = Model.fromFile("iris_tree.pmml");
// Predict using Java Map
Map input = new HashMap<>();
input.put("sepal_length", 5.1);
input.put("sepal_width", 3.5);
input.put("petal_length", 1.4);
input.put("petal_width", 0.2);
Map result = model.predict(input);
System.out.println("Predicted: " + result.get("predicted_class"));
System.out.println("Probability: " + result.get("probability"));
// Predict using Array
String[] inputNames = model.inputNames();
Object[] arrayResult = model.predict(new Double[]{5.1, 3.5, 1.4, 0.2});
// Predict using Series with schema
StructType inputSchema = model.inputSchema();
Object[] values = new Object[inputSchema.size()];
for (int i = 0; i < values.length; i++) {
StructField sf = inputSchema.apply(i);
values[i] = Utils.toDataVal(input.get(sf.name()), sf.dataType());
}
Series seriesResult = model.predict(Series.fromArray(values, inputSchema));
// Access Series results
System.out.println("Result: " + seriesResult.get(0));
}
}
```
--------------------------------
### Load PMML Model from Input Stream
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Loads a PMML model from an input stream. This is useful when the model data is available as a stream.
```scala
// Load from an input stream
val model = Model.fromInputStream(new java.io.FileInputStream("model.pmml"))
```
--------------------------------
### Predict with Array Input in Java
Source: https://github.com/autodeployai/pmml4s/blob/master/README.md
Predict using an array of values. The order of values must match the model's input field order. Results are returned in the order of output fields.
```java
String[] inputNames = model.inputNames();
Object[] result = model.predict(new Double[]{5.1, 3.5, 1.4, 0.2});
```
--------------------------------
### Load PMML Model from String
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Loads a PMML model from a string containing the PMML XML content. Ensure the string is well-formed XML.
```scala
// Load from a string containing PMML XML
val pmmlString = """
...
"""
val model = Model.fromString(pmmlString)
```
--------------------------------
### Configure PMML4S Model Output Fields
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Examine and understand the output field definitions of a PMML model, including predicted values, probabilities, and other result features.
```scala
import org.pmml4s.model.Model
import org.pmml4s.metadata.OutputField
import org.pmml4s.common.ResultFeature
val model = Model.fromFile("iris_tree.pmml")
// Examine output field definitions
val outputFields: Array[OutputField] = model.outputFields
outputFields.foreach {
of =>
println(s"Name: ${of.name}")
println(s" Display Name: ${of.displayName.getOrElse("N/A")}")
println(s" Data Type: ${of.dataType}")
println(s" Feature: ${of.feature}")
println(s" Is Final Result: ${of.isFinalResult}")
println()
}
// Common output features:
// - predictedValue: The predicted target value
// - probability: Probability of predicted class
// - probability_: Probability of specific class
// - confidence: Confidence of prediction
// - entityId/nodeId: ID of matched entity (tree node, cluster, etc.)
// - reasonCode: Reason codes for scorecard models
// - affinity: Distance/similarity for clustering models
// Example output for classification tree:
// predicted_class -> predictedValue
// probability -> probability
// probability_Iris-setosa -> probability(Iris-setosa)
// probability_Iris-versicolor -> probability(Iris-versicolor)
// probability_Iris-virginica -> probability(Iris-virginica)
// node_id -> entityId
// For regression models
if (model.isRegression) {
val result = model.predict(Map("x1" -> 1.0, "x2" -> 2.0))
println(s"Predicted value: ${result("predicted_value")}")
}
// For clustering models
// result contains: cluster, cluster_name, distance/similarity
```
--------------------------------
### Load PMML Model from Java Path Object
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Loads a PMML model from a Java Path object, providing another way to specify the model's location.
```scala
// Load from a Java Path object
val model = Model.fromPath(java.nio.file.Paths.get("model.pmml"))
```
--------------------------------
### PMML4S Automatic Data Transformations
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Demonstrates how PMML4S automatically applies data transformations defined in the PMML model during prediction, including normalization, discretization, and derived fields.
```scala
import org.pmml4s.model.Model
val model = Model.fromFile("model_with_transforms.pmml")
// Transformations are applied automatically during prediction
// The model handles:
// - NormContinuous: Normalize numeric values
// - NormDiscrete: One-hot encoding for categorical values
// - Discretize: Bin continuous values into categories
// - MapValues: Map values using lookup tables
// - TextIndex: Text indexing for text mining
// - Apply: Apply built-in functions (math, string, date operations)
// - FieldRef: Reference to other fields
// - Constant: Constant values
// Missing value handling is also automatic:
// - missingValueReplacement: Replace missing with specified value
// - missingValueTreatment: returnInvalid, asMissing, etc.
// - outlierTreatment: asMissingValues, asExtremeValues
// Example with missing value
val resultWithMissing = model.predict(Map(
"feature1" -> 1.0,
"feature2" -> null // Missing value handled per model spec
))
// Invalid value handling
val resultWithInvalid = model.predict(Map(
"feature1" -> 1.0,
"category" -> "unknown_value" // Invalid categorical value
))
```
--------------------------------
### Load PMML Model from Java File Object
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Loads a PMML model using a Java File object. This is an alternative to using a file path string.
```scala
// Load from a Java File object
val model = Model.fromFile(new java.io.File("model.pmml"))
```
--------------------------------
### Predict with Series Input (Map-based Schema) in Java
Source: https://github.com/autodeployai/pmml4s/blob/master/README.md
Prepare data based on the model's input schema. Convert external data to the types defined by PMML and maintain the order specified in the input schema. This method uses a Series created from an array of values and an input schema.
```java
import org.pmml4s.data.Series;
import org.pmml4s.util.Utils;
import org.pmml4s.common.StructType;
import org.pmml4s.common.StructField;
import java.util.Map;
import java.util.HashMap;
StructType inputSchema = model.inputSchema();
Map row = new HashMap() {{
put("sepal_length", "5.1");
put("sepal_width", "3.5");
put("petal_length", "1.4");
put("petal_width", "0.2");
}};
Object[] values = new Object[inputSchema.size()];
for (int i = 0; i < values.length; i++) {
StructField sf = inputSchema.apply(i);
values[i] = Utils.toDataVal(row.get(sf.name()), sf.dataType());
}
Series result = model.predict(Series.fromArray(values, inputSchema));
```
--------------------------------
### Score Scorecard Model with PMML4S
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Loads a Scorecard model from PMML and calculates a score based on input attributes like age and income. Output includes score and reason codes.
```scala
// Scorecard Model
val scorecardModel = Model.fromFile("scorecard.pmml")
val scoreResult = scorecardModel.predict(Map("age" -> 35, "income" -> 50000))
// Returns: score, reason_code_1, reason_code_2, etc.
```
--------------------------------
### Load PMML Model from Byte Array
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Loads a PMML model from a byte array. This is useful when the model is stored or transmitted as binary data.
```scala
// Load from byte array
val bytes: Array[Byte] = ...
val model = Model.fromBytes(bytes)
```
--------------------------------
### Predicting with Map and Array inputs
Source: https://github.com/autodeployai/pmml4s/blob/master/README.md
Demonstrates direct prediction using Map or Array structures, where automatic type conversion is applied.
```scala
val result = model.predict(Map("sepal_length" -> "5.1", "sepal_width" -> "3.5", "petal_length" -> "1.4", "petal_width" -> "0.2"))
val result = model.predict(Array("5.1", "3.5", "1.4", "0.2"))
```
--------------------------------
### Inspect Model Metadata and Schema
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Retrieve detailed information about input/output fields, target variables, and model properties. This is useful for validating model compatibility and understanding classification or regression outputs.
```scala
import org.pmml4s.model.Model
val model = Model.fromFile("iris_tree.pmml")
// Input field information
val inputNames: Array[String] = model.inputNames
val inputFields = model.inputFields
val inputSchema = model.inputSchema
inputSchema.foreach { field =>
println(s"Input: ${field.name}, Type: ${field.dataType}")
}
// Output field information
val outputNames: Array[String] = model.outputNames
val outputFields = model.outputFields
val outputSchema = model.outputSchema
outputFields.foreach { field =>
println(s"Output: ${field.name}, Feature: ${field.feature}")
}
// Target field information
val targetNames: Array[String] = model.targetNames
val targetField = model.targetField
// For classification models
if (model.isClassification) {
val classes = model.classes
val numClasses = model.numClasses
println(s"Classes: ${classes.mkString(", ")}")
println(s"Number of classes: $numClasses")
}
// For regression models
if (model.isRegression) {
println("This is a regression model")
}
// Model properties
val modelName = model.modelName
val functionName = model.functionName // classification, regression, clustering, etc.
val isScorable = model.isScorable
// Feature importances (if available)
val importances: Map[String, Double] = model.importances
importances.foreach { case (field, importance) =>
println(s"$field: $importance")
}
```
--------------------------------
### Score Neural Network Model with PMML4S
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Loads a Neural Network model from a PMML file and predicts using input features. Supports various activation functions like logistic, tanh, identity, rectifier, and softmax.
```scala
// Neural Network Model
val nnModel = Model.fromFile("neural_network.pmml")
val nnResult = nnModel.predict(Map("input1" -> 0.5, "input2" -> 0.8))
// Supports: logistic, tanh, identity, rectifier, softmax activations
```
--------------------------------
### Score Ensemble Model with PMML4S
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Loads an Ensemble model (e.g., Random Forest, Gradient Boosting) from PMML and predicts. Supports strategies like selectFirst, selectAll, modelChain, and segmentation.
```scala
// Ensemble/Mining Model (Random Forest, Gradient Boosting, etc.)
val ensembleModel = Model.fromFile("random_forest.pmml")
val ensembleResult = ensembleModel.predict(Map("feature1" -> 1.0, "feature2" -> 2.0))
// Supports: selectFirst, selectAll, modelChain, segmentation
```
--------------------------------
### Score Clustering Model with PMML4S
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Loads a Clustering model (e.g., K-Means) from PMML and predicts cluster assignments. The output includes the cluster ID, name, and distance/similarity.
```scala
// Clustering Model (K-Means, etc.)
val clusterModel = Model.fromFile("clustering.pmml")
val clusterResult = clusterModel.predict(Map("dim1" -> 1.5, "dim2" -> 2.3))
// Returns: cluster (ID), cluster_name, distance/similarity
```
--------------------------------
### Predict with Java Map Input
Source: https://github.com/autodeployai/pmml4s/blob/master/README.md
Predict using a HashMap where keys are input field names and values are the corresponding data. The result type matches the input types.
```java
import java.util.Map;
import java.util.HashMap;
Map result = model.predict(new HashMap() {{
put("sepal_length", 5.1);
put("sepal_width", 3.5);
put("petal_length", 1.4);
put("petal_width", 0.2);
}});
```
--------------------------------
### Score Regression Model with PMML4S
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Loads a Regression model (Linear, Logistic, Polynomial) from PMML and scores it. For classification tasks, it returns probabilities with softmax or logit normalization.
```scala
// Regression Model (Linear, Logistic, Polynomial)
val regModel = Model.fromFile("regression.pmml")
val regResult = regModel.predict(Map("x1" -> 10.0, "x2" -> 20.0))
// For classification: returns probabilities with softmax/logit normalization
```
--------------------------------
### Perform Batch Predictions with JSON Input
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Use JSON strings in either records or split format to perform batch predictions. The result can be parsed using libraries like spray-json.
```scala
import org.pmml4s.model.Model
val model = Model.fromFile("iris_tree.pmml")
// Records format: array of JSON objects
val recordsJson = """[
{"sepal_length": 5.1, "sepal_width": 3.5, "petal_length": 1.4, "petal_width": 0.2},
{"sepal_length": 7.0, "sepal_width": 3.2, "petal_length": 4.7, "petal_width": 1.4},
{"sepal_length": 6.3, "sepal_width": 3.3, "petal_length": 6.0, "petal_width": 2.5}
]"""
val recordsResult: String = model.predict(recordsJson)
// Returns: [{"predicted_class":"Iris-setosa","probability":1.0,...},{"predicted_class":"Iris-versicolor",...},...]
// Split format: columns with data arrays
val splitJson = """{
"columns": ["sepal_length", "sepal_width", "petal_length", "petal_width"],
"data": [
[5.1, 3.5, 1.4, 0.2],
[7.0, 3.2, 4.7, 1.4],
[6.3, 3.3, 6.0, 2.5]
]
}"""
val splitResult: String = model.predict(splitJson)
// Returns: {"columns":["predicted_class","probability",...], "data":[["Iris-setosa",1.0,...],["Iris-versicolor",...],["Iris-virginica",...]]}
// Parse the JSON result
import spray.json._
val parsedResult = recordsResult.parseJson.asInstanceOf[JsArray]
parsedResult.elements.foreach { record =>
val obj = record.asJsObject
println(s"Class: ${obj.fields("predicted_class")}")
}
```
--------------------------------
### Score Naive Bayes Model with PMML4S
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Loads a Naive Bayes model from PMML and predicts based on provided features. Handles both numerical and categorical features.
```scala
// Naive Bayes Model
val nbModel = Model.fromFile("naive_bayes.pmml")
val nbResult = nbModel.predict(Map("feature1" -> "value1", "feature2" -> 5))
```
--------------------------------
### Score K-Nearest Neighbors Model with PMML4S
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Loads a K-Nearest Neighbors (KNN) model from PMML and performs prediction using input features.
```scala
// K-Nearest Neighbors Model
val knnModel = Model.fromFile("knn.pmml")
val knnResult = knnModel.predict(Map("x1" -> 1.0, "x2" -> 2.0))
```
--------------------------------
### Score Anomaly Detection Model with PMML4S
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Loads an Anomaly Detection model from PMML and predicts an anomaly score based on input features.
```scala
// Anomaly Detection Model
val anomalyModel = Model.fromFile("anomaly_detection.pmml")
val anomalyResult = anomalyModel.predict(Map("x1" -> 100.0, "x2" -> -50.0))
// Returns: anomalyScore
```
--------------------------------
### Load Association Rules Model with PMML4S
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Loads an Association Rules model from PMML. This model type is designed for transaction-based scoring.
```scala
// Association Rules Model
val assocModel = Model.fromFile("association.pmml")
// For transaction-based scoring
```
--------------------------------
### Score Decision Tree Model with PMML4S
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Loads a Decision Tree model from a PMML file and performs prediction using a Map of features. The result includes predicted class, probability, confidence, and node ID.
```scala
import org.pmml4s.model._
// Decision Tree Model
val treeModel = Model.fromFile("decision_tree.pmml")
val treeResult = treeModel.predict(Map("feature1" -> 1.0, "feature2" -> "A"))
// Returns: predicted_class, probability, confidence, node_id
```
--------------------------------
### Score Support Vector Machine Model with PMML4S
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Loads a Support Vector Machine (SVM) model from PMML and performs prediction using input features.
```scala
// Support Vector Machine Model
val svmModel = Model.fromFile("svm.pmml")
val svmResult = svmModel.predict(Map("x" -> 1.0, "y" -> 2.0))
```
--------------------------------
### Predict with Array Input
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Performs prediction using an array of values, ordered according to the model's input fields. This method is optimized for performance-critical scenarios. String arrays are also supported.
```scala
import org.pmml4s.model.Model
val model = Model.fromFile("iris_tree.pmml")
// Get the expected input field order
val inputNames: Array[String] = model.inputNames
// Array(sepal_length, sepal_width, petal_length, petal_width)
// Predict using an array (order must match inputNames)
val input = Array(5.1, 3.5, 1.4, 0.2)
val result: Array[Any] = model.predict(input)
// Get output field names to interpret results
val outputNames: Array[String] = model.outputNames
// Array(predicted_class, probability, probability_Iris-setosa, ...)
// Result array: Array(Iris-setosa, 1.0, 1.0, 0.0, 0.0, 1)
// Arrays of strings also work
val stringInput = Array("5.1", "3.5", "1.4", "0.2")
val stringResult = model.predict(stringInput)
// Create a map from results
val resultMap = outputNames.zip(result).toMap
println(s"Predicted: ${resultMap("predicted_class")}")
```
--------------------------------
### Predict with Array
Source: https://github.com/autodeployai/pmml4s/blob/master/README.md
Perform predictions using an Array, where the order must match the model's input fields.
```scala
scala> val inputNames = model.inputNames
inputNames: Array[String] = Array(sepal_length, sepal_width, petal_length, petal_width)
scala> val result = model.predict(Array(5.1, 3.5, 1.4, 0.2))
result: Array[Any] = Array(Iris-setosa, 1.0, 1.0, 0.0, 0.0, 1)
scala> val outputNames = model.outputNames
outputNames: Array[String] = Array(predicted_class, probability, probability_Iris-setosa, probability_Iris-versicolor, probability_Iris-virginica, node_id)
```
--------------------------------
### Retrieving model output fields
Source: https://github.com/autodeployai/pmml4s/blob/master/README.md
Accesses the model's output fields to understand the structure and metadata of prediction results.
```scala
val outputFields = model.outputFields
outputFields.foreach(println)
```
--------------------------------
### Predict with List of Pairs
Source: https://github.com/autodeployai/pmml4s/blob/master/README.md
Perform predictions using a sequence of key-value pairs.
```scala
scala> val result = model.predict("sepal_length" -> 5.1, "sepal_width" -> 3.5, "petal_length" -> 1.4, "petal_width" -> 0.2)
result: Seq[(String, Any)] = ArraySeq((predicted_class,Iris-setosa), (probability,1.0), (probability_Iris-setosa,1.0), (probability_Iris-versicolor,0.0), (probability_Iris-virginica,0.0), (node_id,1))
```
--------------------------------
### Predicting with Seq and DataVal conversion
Source: https://github.com/autodeployai/pmml4s/blob/master/README.md
Converts external data to PMML-compatible types using Utils.toDataVal before creating a Series for prediction.
```scala
val row = Map("sepal_length" -> "5.1", "sepal_width" -> "3.5", "petal_length" -> "1.4", "petal_width" -> "0.2")
val values = inputSchema.map(x => Utils.toDataVal(row(x.name), x.dataType))
val result = model.predict(Series.fromSeq(values))
```
--------------------------------
### Predict with Map
Source: https://github.com/autodeployai/pmml4s/blob/master/README.md
Perform predictions using a Map of input field names and values.
```scala
scala> val result = model.predict(Map("sepal_length" -> 5.1, "sepal_width" -> 3.5, "petal_length" -> 1.4, "petal_width" -> 0.2))
result: Map[String,Any] = Map(probability -> 1.0, probability_Iris-versicolor -> 0.0, probability_Iris-setosa -> 1.0, probability_Iris-virginica -> 0.0, predicted_class -> Iris-setosa, node_id -> 1)
```
--------------------------------
### Predict with Scala Map Input
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Performs prediction using a Scala Map where keys are field names and values are input data. Handles automatic type conversion for string inputs.
```scala
import org.pmml4s.model.Model
val model = Model.fromFile("iris_tree.pmml")
// Predict using a Scala Map
val input = Map(
"sepal_length" -> 5.1,
"sepal_width" -> 3.5,
"petal_length" -> 1.4,
"petal_width" -> 0.2
)
val result: Map[String, Any] = model.predict(input)
// Result contains prediction outputs like:
// Map(
// predicted_class -> Iris-setosa,
// probability -> 1.0,
// probability_Iris-setosa -> 1.0,
// probability_Iris-versicolor -> 0.0,
// probability_Iris-virginica -> 0.0,
// node_id -> 1
// )
println(s"Predicted class: ${result("predicted_class")}")
println(s"Probability: ${result("probability")}")
// String values are automatically converted to appropriate types
val inputWithStrings = Map(
"sepal_length" -> "5.1",
"sepal_width" -> "3.5",
"petal_length" -> "1.4",
"petal_width" -> "0.2"
)
val resultFromStrings = model.predict(inputWithStrings)
```
--------------------------------
### Predict with Series Input
Source: https://context7.com/autodeployai/pmml4s/llms.txt
The Series class provides a type-safe container for model inputs. It can be constructed from Maps, Arrays, or sequences of DataVal objects using the model's input schema.
```scala
import org.pmml4s.model.Model
import org.pmml4s.data.Series
import org.pmml4s.common.StructType
import org.pmml4s.util.Utils
val model = Model.fromFile("iris_tree.pmml")
// Get input schema for type information
val inputSchema: StructType = model.inputSchema
// StructType(StructField(sepal_length,double), StructField(sepal_width,double), ...)
// Create Series from a Map with schema
val mapData = Map(
"sepal_length" -> "5.1",
"sepal_width" -> "3.5",
"petal_length" -> "1.4",
"petal_width" -> "0.2"
)
val seriesFromMap = Series.fromMap(mapData, inputSchema)
val result1: Series = model.predict(seriesFromMap)
// Create Series from an Array with schema
val arrayData = Array(5.1, 3.5, 1.4, 0.2)
val seriesFromArray = Series.fromArray(arrayData, inputSchema)
val result2: Series = model.predict(seriesFromArray)
// Access results by index
println(s"Predicted value: ${result1.get(0)}")
println(s"Probability: ${result1.getDouble(1)}")
// Convert results to different formats
val resultAsMap: Map[String, Any] = result1.asMap
val resultAsArray: Array[Any] = result1.asArray
val resultAsPairs: Seq[(String, Any)] = result1.asPairSeq
// Create Series from DataVal sequence (for advanced use)
val values = inputSchema.map { field =>
Utils.toDataVal(mapData(field.name), field.dataType)
}
val seriesFromSeq = Series.fromSeq(values, inputSchema)
```
--------------------------------
### Batch Predictions with Scala Iterator
Source: https://context7.com/autodeployai/pmml4s/llms.txt
Process large datasets efficiently using an iterator-based prediction method in Scala. Supports lazy evaluation for memory efficiency.
```scala
import org.pmml4s.model.Model
import org.pmml4s.data.Series
val model = Model.fromFile("iris_tree.pmml")
val inputSchema = model.inputSchema
// Create an iterator of input Series (e.g., from a file or database)
val inputData: Iterator[Series] = Iterator(
Series.fromArray(Array(5.1, 3.5, 1.4, 0.2), inputSchema),
Series.fromArray(Array(7.0, 3.2, 4.7, 1.4), inputSchema),
Series.fromArray(Array(6.3, 3.3, 6.0, 2.5), inputSchema)
)
// Get predictions as an iterator (lazy evaluation)
val predictions: Iterator[Series] = model.predict(inputData)
// Process results one at a time
predictions.foreach {
result =>
println(s"Predicted: ${result.get(0)}, Probability: ${result.getDouble(1)}")
}
```
```scala
import org.pmml4s.model.Model
import org.pmml4s.data.Series
import scala.io.Source
def processCsvFile(filePath: String, model: Model): Unit = {
val lines = Source.fromFile(filePath).getLines()
val header = lines.next().split(",")
val results = lines.map {
line =>
val values = line.split(",").map(_.toDouble)
val series = Series.fromArray(values, model.inputSchema)
model.predict(series)
}
results.foreach {
r =>
println(r.asMap)
}
}
```
--------------------------------
### Predict with JSON
Source: https://github.com/autodeployai/pmml4s/blob/master/README.md
Perform predictions using JSON strings in 'records' or 'split' format.
```scala
scala> val result = model.predict("""[{"sepal_length": 5.1, "sepal_width": 3.5, "petal_length": 1.4, "petal_width": 0.2}, {"sepal_length": 7, "sepal_width": 3.2, "petal_length": 4.7, "petal_width": 1.4}]""")
result: String = [{"probability":1.0,"probability_Iris-versicolor":0.0,"probability_Iris-setosa":1.0,"probability_Iris-virginica":0.0,"predicted_class":"Iris-setosa","node_id":"1"},{"probability":0.9074074074074074,"probability_Iris-versicolor":0.9074074074074074,"probability_Iris-setosa":0.0,"probability_Iris-virginica":0.09259259259259259,"predicted_class":"Iris-versicolor","node_id":"3"}]
scala> val result = model.predict("""{"columns": ["sepal_length", "sepal_width", "petal_length", "petal_width"], "data":[[5.1, 3.5, 1.4, 0.2], [7, 3.2, 4.7, 1.4]]}""")
result: String = {"columns":["predicted_class","probability","probability_Iris-setosa","probability_Iris-versicolor","probability_Iris-virginica","node_id"],"data":[["Iris-setosa",1.0,1.0,0.0,0.0,"1"],["Iris-versicolor",0.9074074074074074,0.0,0.9074074074074074,0.09259259259259259,"3"]]}
```
--------------------------------
### Predict with Series
Source: https://github.com/autodeployai/pmml4s/blob/master/README.md
Perform predictions using PMML4S Series objects constructed from Maps or Arrays.
```scala
import org.pmml4s.data.Series
import org.pmml4s.util.Utils
// The input schema contains a list of input fields with its name and data type, you can prepare data based on it.
scala> val inputSchema = model.inputSchema
inputSchema: org.pmml4s.common.StructType = StructType(StructField(sepal_length,double), StructField(sepal_width,double), StructField(petal_length,double), StructField(petal_width,double))
// There are several factory methods to construct a Series object.
// 1. values in a Map
scala> val result = model.predict(Series.fromMap(Map("sepal_length" -> "5.1", "sepal_width" -> "3.5", "petal_length" -> "1.4", "petal_width" -> "0.2"), inputSchema))
val result: org.pmml4s.data.Series = [Iris-setosa,1,1,0,0,1],[(predicted_class,string),(probability,real),(probability_Iris-setosa,real),(probability_Iris-versicolor,real),(probability_Iris-virginica,real),(node_id,string)]
// 2. values in an Array
scala> val result = model.predict(Series.fromArray(Array(5.1, 3.5, 1.4, 0.2), inputSchema))
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.