Curl Node Java Python

Natural Language Classifier

API Reference
IBM Watson Natural Language Classifier API reference

Introduction

The IBM Watson™ Natural Language Classifier service uses machine learning algorithms to return the top matching predefined classes for short text input. You create and train a classifier to connect predefined classes to example texts so that the service can apply those classes to new inputs.

API Endpoint

https://gateway.watsonplatform.net/natural-language-classifier/api

npm

npm install watson-developer-cloud

Maven

<dependency>
  <groupId>com.ibm.watson.developer_cloud</groupId>
  <artifactId>java-sdk</artifactId>
  <version>3.7.1</version>
</dependency>

Gradle

compile 'com.ibm.watson.developer_cloud:java-sdk:3.7.1'

pip

pip install --upgrade watson-developer-cloud

API explorer

In addition to reading this API reference, you can interact with the methods in the API explorer. To get familiar with the API, use the explorer to test your calls to the API and view live responses from the server.

Authentication

You authenticate to the Natural Language Classifier API by providing the username and password that are provided in the service credentials for the service instance that you want to use. The API uses basic authentication.

After you create an instance of the Natural Language Classifier service, you can view the username and password by selecting Service Credentials from the left pane of the service dashboard.

Replace {username} and {password} with your credentials

Replace YOUR SERVICE USERNAME and YOUR SERVICE PASSWORD with your credentials

var watson = require('watson-developer-cloud')({
  username: '{username}',
  password: '{password}',
  version: 'v1'
});
NaturalLanguageClassifier service = new NaturalLanguageClassifier();
service.setUsernameAndPassword("{username}","{password}");
from watson_developer_cloud import NaturalLanguageClassifierV1

natural_language_classifier = NaturalLanguageClassifierV1(
  username='YOUR SERVICE USERNAME',
  password='YOUR SERVICE PASSWORD')

Methods

Create classifier

Sends data to create and train a classifier and returns information about the new classifier.

When the operation is successful, the status of the classifier is set to "Training". The status must be "Available" before you can use the classifier.

POST /v1/classifiers

Request

Parameter Type Description
training_data File (Required) Training data. Each text value must have at least one class. The data can include up to 15,000 records. For details, see "Using your own data."
training_metadata File

Metadata in JSON format.

The metadata identifies the required language of the data and an optional name to identify the classifier. Specify the language with the 2-letter primary language code as assigned in ISO standard 639. Supported languages are English (en), Arabic (ar), French (fr), German, (de), Italian (it), Japanese (ja), Brazilian Portuguese (pt), and Spanish (es).

Parameter Type Description
name String User-supplied name for the classifier
language String (Required) The language of the training data. Specify the language with the 2-letter primary language code as assigned in ISO standard 639. Supported languages are English (en), Arabic (ar), French (fr), German, (de), Italian (it), Japanese (ja), Brazilian Portuguese (pt), and Spanish (es).
trainingData File (Required) Training data. Each text value must have at least one class. The data can include up to 15,000 records. For details, see "Using your own data."
Parameter Type Description
name String User-supplied name for the classifier
language String (Required) The language of the training data. Default value is "en". Specify the language with the 2-letter primary language code as assigned in ISO standard 639. Supported languages are English (en), Arabic (ar), French (fr), German, (de), Italian (it), Japanese (ja), Brazilian Portuguese (pt), and Spanish (es).
training_data File (Required) Training data. Each text value must have at least one class. The data can include up to 15,000 records. For details, see "Using your own data."

Example request

curl -u "{username}":"{password}" -F training_data=@train.csv -F training_metadata="{\"language\":\"en\",\"name\":\"My Classifier\"}" "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers"
var watson = require('watson-developer-cloud');
var fs     = require('fs');

var natural_language_classifier = watson.natural_language_classifier({
  username: '{username}',
  password: '{password}',
  version: 'v1'
});

var params = {
  language: 'en',
  name: 'My Classifier',
  training_data: fs.createReadStream('./train.csv')
};

natural_language_classifier.create(params, function(err, response) {
  if (err)
    console.log(err);
  else
    console.log(JSON.stringify(response, null, 2));
});
NaturalLanguageClassifier service = new NaturalLanguageClassifier();
service.setUsernameAndPassword("{username}", "{password}");

Classifier classifier = service.createClassifier("My Classifier", "en",
  new File("./train.csv")).execute();
System.out.println(classifier);
import json
from watson_developer_cloud import NaturalLanguageClassifierV1

natural_language_classifier = NaturalLanguageClassifierV1(
  username='YOUR SERVICE USERNAME',
  password='YOUR SERVICE PASSWORD')

with open('../resources/weather_data_train.csv', 'rb') as training_data:
  classifier = natural_language_classifier.create(
    training_data=training_data,
    name='My Classfier',
    language='en'
  )
print(json.dumps(classifier, indent=2))

Response

Name Description
classifier_id Unique identifier for this classifier
name User-supplied name for the classifier
language The language that was used to train the classifier
created Date and time in Coordinated Universal Time that the classifier was created
url Link to the classifer
status The state of the classifier: ("Non Existent" or "Training" or "Failed" or "Available" or "Unavailable")
status_description Additional detail about the status

Example response

{
  "classifier_id": "10D41B-nlc-1",
  "name": "My Classifier",
  "language": "en"
  "created": "2015-05-28T18:01:57.393Z",
  "url": "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/10D41B-nlc-1",
  "status": "Training",
  "status_description": "The classifier instance is in its training phase, not yet ready to accept classify requests"
}

List classifiers

Retrieves the list of classifiers for the service instance. Returns an empty array if no classifiers are available.

GET /v1/classifiers

Request

No arguments.

Example request

curl -u "{username}":"{password}" "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers"
var watson = require('watson-developer-cloud');

var natural_language_classifier = watson.natural_language_classifier({
  username: '{username}',
  password: '{password}',
  version: 'v1'
});

natural_language_classifier.list({},
  function(err, response) {
    if (err)
        console.log('error:', err);
      else
        console.log(JSON.stringify(response, null, 2));
});
NaturalLanguageClassifier service = new NaturalLanguageClassifier();
service.setUsernameAndPassword("{username}", "{password}");

Classifiers classifiers = service.getClassifiers().execute();
System.out.println(classifiers);
import json
from watson_developer_cloud import NaturalLanguageClassifierV1 as NaturalLanguageClassifier

natural_language_classifier = NaturalLanguageClassifier(
  username='YOUR SERVICE USERNAME',
  password='YOUR SERVICE PASSWORD')

classifiers = natural_language_classifier.list()
print(json.dumps(classifiers, indent=2))

Response

Name Description
classifiers An array [ClassifierInfoPayload] of classifiers that are available for the service instance. Returns an empty array if no classifiers are available.
ClassifierInfoPayload
Name Description
classifier_id Unique identifier for this classifier
url Link to the classifer
name User-supplied name for the classifier
language The language that is used for the classifier
created Date and time in Coordinated Universal Time that the classifier was created

Example response

{
  "classifiers": [
    {
      "classifier_id": "10D41B-nlc-1",
      "url": "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/10D41B-nlc-1",
      "name": "My Classifier",
      "language": "en",
      "created": "2015-05-28T18:01:57.393Z"
    }
  ]
}

Get information about a classifier

Returns status and other information about a classifier

GET /v1/classifiers/{classifier_id}

Request

Parameter Type Description
classifier_id Path (Required) Classifier ID to query
Parameter Type Description
classifier_id String (Required) Classifier ID to query

Example request

curl -u "{username}":"{password}"  "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/10D41B-nlc-1"
var watson = require('watson-developer-cloud');

var natural_language_classifier = watson.natural_language_classifier({
  username: '{username}',
  password: '{password}',
  version: 'v1'
});

natural_language_classifier.status({
  classifier_id: '10D41B-nlc-1' },
  function(err, response) {
    if (err)
      console.log('error:', err);
    else
      console.log(JSON.stringify(response, null, 2));
});
NaturalLanguageClassifier service = new NaturalLanguageClassifier();
service.setUsernameAndPassword("{username}", "{password}");

Classifier classifier = service.getClassifier("10D41B-nlc-1").execute();
System.out.println(classifier);
import json
from watson_developer_cloud import NaturalLanguageClassifierV1 as NaturalLanguageClassifier

natural_language_classifier = NaturalLanguageClassifier(
  username='YOUR SERVICE USERNAME',
  password='YOUR SERVICE PASSWORD')

status = natural_language_classifier.status('10D41B-nlc-1')
print (json.dumps(status, indent=2))

Response

Name Description
classifier_id Unique identifier for this classifier
name User-supplied name for the classifier
language The language that is used for the classifier
created Date and time in Coordinated Universal Time that the classifier was created
url Link to the classifer
status The state of the classifier: ("Non Existent" or "Training" or "Failed" or "Available" or "Unavailable")
status_description Additional detail about the status

Example response

{
  "classifier_id": "10D41B-nlc-1",
  "name": "My Classifier",
  "language": "en",
  "created": "2015-05-28T18:01:57.393Z",
  "url": "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/10D41B-nlc-1",
  "status": "Available",
  "status_description": "The classifier instance is now available and is ready to take classifier requests.",
}

Delete classifier

Deletes a classifier.

DELETE /v1/classifiers/{classifier_id}

Request

Parameter Type Description
classifier_id Path (Required) Classifier ID to delete
Parameter Type Description
classifier_id String (Required) Classifier ID to delete
Parameter Type Description
classifierId String (Required) Classifier ID to delete

Example request

curl -X DELETE -u "{username}":"{password}" "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/10D41B-nlc-1"
var watson = require('watson-developer-cloud');

var natural_language_classifier = watson.natural_language_classifier({
  username: '{username}',
  password: '{password}',
  version: 'v1'
});

natural_language_classifier.remove({
  classifier_id: '10D41B-nlc-1' },
  function(err, response) {
    if (err)
      console.log('error:', err);
    else
      console.log(JSON.stringify(response, null, 2));
});
NaturalLanguageClassifier service = new NaturalLanguageClassifier();
service.setUsernameAndPassword("{username}", "{password}");

service.deleteClassifier("10D41B-nlc-1").execute();
from watson_developer_cloud import NaturalLanguageClassifierV1

natural_language_classifier = NaturalLanguageClassifierV1(
  username='YOUR SERVICE USERNAME',
  password='YOUR SERVICE PASSWORD')

classes = natural_language_classifier.remove('10D41B-nlc-1')
print(json.dumps(classes, indent=2))

Response

Empty array

No response body

Example response

{}

Classify

Returns label information for the input. The status must be "Available" before you can classify calls. Use the Get information about a classifier method to retrieve the status.

GET /v1/classifiers/{classifier_id}/classify
POST /v1/classifiers/{classifier_id}/classify

Request

Parameter Type Description
classifier_id Path (Required) Classifier ID to use
text Query (Required) Phrase to classify
Parameter Type Description
classifier_id String (Required) Classifier ID to use
text String (Required) Phrase to classify
Parameter Type Description
classifierId String (Required) Classifier ID to use
text String (Required) Phrase to classify

Example GET request

curl -G -u "{username}":"{password}" "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/10D41B-nlc-1/classify?text=How%20hot%20will%20it%20be%20today%3F"

Example POST request

curl -X POST -u "{username}":"{password}" -H "Content-Type:application/json" -d "{\"text\":\"How hot will it be today?\"}" "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/10D41B-nlc-1/classify"

Example request

var watson = require('watson-developer-cloud');

var natural_language_classifier = watson.natural_language_classifier({
  username: '{username}',
  password: '{password}',
  version: 'v1'
});

natural_language_classifier.classify({
  text: 'How hot will it be today?',
  classifier_id: '10D41B-nlc-1' },
  function(err, response) {
    if (err)
      console.log('error:', err);
    else
      console.log(JSON.stringify(response, null, 2));
});
NaturalLanguageClassifier service = new NaturalLanguageClassifier();
service.setUsernameAndPassword("{username}", "{password}");

Classification classification = service.classify("10D41B-nlc-1",
  "How hot will it be today?").execute();
System.out.println(classification);
from watson_developer_cloud import NaturalLanguageClassifierV1

natural_language_classifier = NaturalLanguageClassifierV1(
  username='YOUR SERVICE USERNAME',
  password='YOUR SERVICE PASSWORD')

classes = natural_language_classifier.classify('10D41B-nlc-1', 'How hot will it be today?')
print(json.dumps(classes, indent=2))

Response

Name Description
classifier_id Unique identifier for this classifier
url Link to the classifer
text The submitted phrase
top_class The class with the highest confidence
classes An array [Classes] of up to ten class_name-confidence pairs that are sorted in descending order of confidence. If there are fewer than 10 classes, the sum of the confidence values is 100%.
Classes
Name Description
class_name Class label
confidence A decimal percentage that represents the confidence that Watson has in this class. Higher values represent higher confidences.

Example response

{
  "classifier_id": "10D41B-nlc-1",
  "url": "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/10D41B-nlc-1/classify?text=How%20hot%20wil/10D41B-nlc-1",
  "text": "How hot will it be today?",
  "top_class": "temperature",
  "classes": [
    {
      "class_name": "temperature",
      "confidence": 0.9998201258549781
    },
    {
      "class_name": "conditions",
      "confidence": 0.00017987414502176904
    }
  ]
}

Data collection

By default, all Watson services log requests and their results. Logging is done only to improve the services for future users. The logged data is not shared or made public. To prevent IBM from accessing your data for general service improvements, set the X-Watson-Learning-Opt-Out header parameter to true for all requests. (Any value other than false or 0 disables request logging for that call.) You must set the header on each request that you do not want IBM to access. set the X-Watson-Learning-Opt-Out header parameter to true when you create the service instance. (Any value other than false or 0 disables request logging for that call.) You must set the header when you create the service for any any call that you do not want IBM to access. set the x-watson-learning-opt-out header parameter to true when you create the service instance. (Any value other than false or 0 disables request logging for that call.) You must set the header when you create the service for any any call that you do not want IBM to access.

Error handling

The Natural Language Classifier service uses standard HTTP response codes to display whether a method completed successfully. A 200 response always indicates success. A 400 type response is some sort of failure, and a 500 type response usually indicates an internal system error.

Error information

Status Description
400 - Bad Request Missing or malformed data or the set of data is too small. Likely caused by missing training data or malformed CSV.
401 - Unauthorized No API key provided, or the API key provided was not valid.
403 - Forbidden The request is not allowed, which might be caused by an incorrect endpoint. When you see this response, the request has not reached the Natural Language Classifier service.
404 - Not Found The requested item or parameter doesn't exist.
405 - Method not allowed The request method is not supported. Check the Allow response header for the HTTP methods that the method supports. When you see this response, the request has not reached the Natural Language Classifier service.
406 - Not acceptable The request includes too many restrictions. When you see this response, the request has not reached the Natural Language Classifier service.
409 - Conflict Likely caused by a temporary server issue or invalid training data. Make sure that your training data adheres to the format and data requirements and resubmit the request to try again.
415 - Unsupported media type The request is in a media type that the server doesn’t understand. When you see this response, the request has not reached the Natural Language Classifier service.
500 - Internal server error Something is wrong on our end. Resubmit the request later.

Error format

Name Description
description Error description
error Error name
code HTTP status code

Example error request

|| Missing training_metadata
curl -u "{username}":"{password}" -F training_data=@train.csv "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers"
var params = {
// Missing language
  language: '',
  name: 'My Classifier',
  training_data: fs.createReadStream('./train.csv')
};

natural_language_classifier.create(params, function(err, response) {
  if (err)
    console.log(err);
  else
    console.log(JSON.stringify(response, null, 2));
});
// Missing training file
Classifier classifier = service.createClassifier("My Classifier", "en", new File("./notfound.csv"));
# Not enough training data
with open('./not_enough_td.csv', 'rb') as training_data:
  classifier = natural_language_classifier.create(
    training_data=training_data,
    name='Does not work'
  )
print(json.dumps(classifier, indent=2))

Example error response

{
  "description": "No training data is specified. The form field 'training_data' should contain the training CSV and 'training_metadata' should contain a JSON metadata string.",
  "error": "Missing training data",
  "code": 400
}
Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
  File "/Library/Python/2.7/site-packages/watson_developer_cloud/natural_language_classifier_v1.py", line 41, in create
    ('training_data', training_data)])
  File "/Library/Python/2.7/site-packages/watson_developer_cloud/watson_developer_cloud_service.py", line 251, in request
    raise WatsonException('Error: ' + error_message + ', Code: ' + str(response.status_code))
  watson_developer_cloud.watson_developer_cloud_service.WatsonException: Error: Data too small, Description: The number of training entries received = 3, which is smaller than the required minimum of 5, Code: 400