Search code examples
iosswiftswift-playgroundcreateml

iOS Training model with CreateML MLTextClassifier class unable to filter from JSON


I’m facing an issue with MLTextClassifier class that is used to CreateML for text.

Below is code snippet:

import CreateML
import Foundation

let objURL = URL(fileURLWithPath: "/Users/jayprakashdubey/Desktop/headlines.json")

// 1. Load data from a JSON file
guard let newsJsonFileContent = try? MLDataTable(contentsOf: objURL) else {
    exit(0)
}

// 2. Make a train-test split
let (training, testing) = newsJsonFileContent.randomSplit(by: 0.8, seed: 5)

print("training: \(training.description)")

// 3. Create the model
if let objNewsClassifier = try? MLTextClassifier(trainingData: training, textColumn: "title", labelColumn: "category") {

   . . . 
}  else {
    print("Failed while classifying News - MLTextClassifier")
}

If condition always fails in above code snippet.

Below is console logs of playground.

Screenshot for console log

Tried with all solutions that were posted on Stackoverflow but none worked.

Note: I'm using Xcode v11.3.1.

Below is JSON file structure:

[
  {
    "text":"New 13-inch MacBook Pro comes with 6K monitor support, Dolby Atmos playback",
    "category":"Technology"
  },
     . . .
  {
    "text":"Apple Watch ECG detects signs of coronary ischemia missed by hospital ECG",
    "category":"Technology"
  }
]

Any fix?


Solution

  • There was an issue with incorrect textColumn and labelColumn values. Interchanged values of the two and it worked.

    Below is code snippet:

    // 3. Create the model
    if let objNewsClassifier = try? MLTextClassifier(trainingData: training, textColumn: "category", labelColumn: "title") {
    
       . . . 
    }