Sample code: Identify the context of natural language with the Watson Natural Language Classifier service


Interactive code: When you see Run at the top of a code sample, you can run the code, check the results, make changes, and run it again. When you see Deploy, you can deploy the code into the developerWorks IBM Cloud account.

About this code

This code shows you how to use the node.js API for the Watson natural language classification service. Given some text and a context, Watson analyzes the text and returns a list of categories relevant to that text.

The code has two basic sections:

  1. The main() method. This is the entry point to the code. It creates the NaturalLanguageClassifierV1 object and then invokes the classify() method.
  2. A set of default parameters and the code that runs this module if it is invoked by itself (as opposed to being invoked by a require() statement). See the node.js documentation for more information on the implications of the require.main === module statement.
Show result

This code takes a string as input and classifies it based on the ID of a classification context previously defined in Bluemix. The call to the Watson Natural Language Classifier service is wrapped in a JavaScript Promise to handle the asynchronous nature of the service. See the overview of the Natural Language Classifier service or the github repo for the Watson node.js API for more information.

Try changing the text to see what happens.

Using this code once deployed

To use this code once you've deployed it, you must create an instance of the Watson Natural Language Classifier service:

To invoke the code, pass a JSON structure that matches the defaultParameters object as shown above with the following changes:

  1. The classifier_id field must contain the ID of a context you defined as part of the Natural Language Classifier service. This code will not work without a valid context ID. See the Natural Language Classifier documentation for details on how to create your own context.
  2. The username, password, and url fields must be filled in with the credentials for your Natural Language Classifier service instance.
  3. The use_unauthenticated field must be false.

For more information, see the developerWorks tutorial Invoking actions on the IBM Cloud Functions platform.

Related topics


Sign in or register to add and subscribe to comments.

Zone=Cognitive computing, Java development
ArticleTitle=Sample code: Identify the context of natural language with the Watson Natural Language Classifier service