NLModel
A custom model trained to classify or tag natural language text.
Declaration
class NLModelOverview
With Natural Language, you can create text classifier (MLTextClassifier) or word tagger (MLWordTagger) models. Use NLModel to integrate those models into your app. This integration ensures that your tokenization and tagger configurations are identical when you train your model and use it in your app.
If you create a text classifier as described in doc:creating-a-text-classifier-model, you can integrate that model into your app and use it to make predictions like this:
let text = "I am very happy."
do {
let mlModel = try SentimentClassifier(configuration: MLModelConfiguration()).model
let customModel = try NLModel(mlModel: mlModel)
// Use the text classifier model to get the most likely label.
if let label = customModel.predictedLabel(for: text) {
print("Most likely label: \(label)")
}
// Get multiple possible labels with their associated confidence scores.
let labelHypotheses = customModel.predictedLabelHypotheses(for: text, maximumCount: 3)
print("Label confidence scores: \(labelHypotheses)")
} catch {
print(error)
}If you create a custom word tagger as described in doc:creating-a-word-tagger-model, you can integrate that model into your app and generate tags for new text input like this:
let text = "The iPad is my favorite Apple product."
do {
let mlModel = try AppleTagger(configuration: MLModelConfiguration()).model
let customModel = try NLModel(mlModel: mlModel)
let customTagScheme = NLTagScheme("Apple")
let tagger = NLTagger(tagSchemes: [.nameType, customTagScheme])
tagger.string = text
tagger.setModels([customModel], forTagScheme: customTagScheme)
tagger.enumerateTags(in: text.startIndex..<text.endIndex, unit: .word,
scheme: customTagScheme, options: .omitWhitespace) { tag, tokenRange in
if let tag = tag {
print("\(text[tokenRange]): \(tag.rawValue)")
}
return true
}
} catch {
print(error)
}Topics
Creating a model
Making predictions
predictedLabel(for:)predictedLabels(forTokens:)predictedLabelHypotheses(for:maximumCount:)predictedLabelHypotheses(forTokens:maximumCount:)