Invictus ai
  • Welcome to Invictus AI
  • Quick Start Guide
  • Natural Language Processing
  • API Reference Overview
  • Next Step
  • Authentication
  • Computer Vision
  • Healthcare Use Cases
  • General FAQ
Powered by GitBook
On this page
  • Step 7: Adding Multi-Label Classification
  • Step 8: Batch Processing
  • Conclusion
  • Next Steps
  • Introduction
  • Prerequisites
  • Step 1: Set Up Your Project
  • Step 2: Define Your Categories
  • Step 3: Create the Classification Endpoint
  • Step 4: Test Your Classifier
  • Step 5: Building a Simple Front-End (Optional)
  • Step 6: Enhancing the Classifier

Next Step

Step 7: Adding Multi-Label Classification

Sometimes text could belong to multiple categories. Let's update our classifier to support multi-label classification:

For JavaScript

app.post('/classify-multi', async (req, res) => {
  try {
    const { text } = req.body;
    
    if (!text) {
      return res.status(400).json({ error: 'Text is required' });
    }
    
    const result = await client.nlp.classify({
      text,
      categories: [
        'Positive Feedback',
        'Negative Feedback',
        'Feature Request',
        'Bug Report',
        'Question'
      ],
      advanced: {
        contextAwareness: true,
        sensitivityLevel: 0.7,
        minConfidence: 0.3,
        multiLabel: true
      }
    });
    
    return res.json(result);
  } catch (error) {
    console.error('Classification error:', error);
    return res.status(500).json({ error: 'Classification failed' });
  }
});

For Python

@app.route('/classify-multi', methods=['POST'])
def classify_multi():
    try:
        data = request.get_json()
        text = data.get('text')
        
        if not text:
            return jsonify({'error': 'Text is required'}), 400
        
        result = client.nlp.classify(
            text=text,
            categories=[
                'Positive Feedback',
                'Negative Feedback',
                'Feature Request',
                'Bug Report',
                'Question'
            ],
            advanced={
                'context_awareness': True,
                'sensitivity_level': 0.7,
                'min_confidence': 0.3,
                'multi_label': True
            }
        )
        
        return jsonify(result)
    except Exception as e:
        print(f"Classification error: {e}")
        return jsonify({'error': 'Classification failed'}), 500

Step 8: Batch Processing

For processing multiple texts at once:

For JavaScript

app.post('/classify-batch', async (req, res) => {
  try {
    const { texts } = req.body;
    
    if (!texts || !Array.isArray(texts) || texts.length === 0) {
      return res.status(400).json({ error: 'Texts array is required' });
    }
    
    const results = await client.nlp.classifyBatch({
      texts,
      categories: [
        'Positive Feedback',
        'Negative Feedback',
        'Feature Request',
        'Bug Report',
        'Question'
      ]
    });
    
    return res.json(results);
  } catch (error) {
    console.error('Batch classification error:', error);
    return res.status(500).json({ error: 'Batch classification failed' });
  }
});

For Python

@app.route('/classify-batch', methods=['POST'])
def classify_batch():
    try:
        data = request.get_json()
        texts = data.get('texts')
        
        if not texts or not isinstance(texts, list) or len(texts) == 0:
            return jsonify({'error': 'Texts array is required'}), 400
        
        results = client.nlp.classify_batch(
            texts=texts,
            categories=[
                'Positive Feedback',
                'Negative Feedback',
                'Feature Request',
                'Bug Report',
                'Question'
            ]
        )
        
        return jsonify(results)
    except Exception as e:
        print(f"Batch classification error: {e}")
        return jsonify({'error': 'Batch classification failed'}), 500

Conclusion

Congratulations! You've built a text classification system using Invictus AI. This system can automatically categorize customer feedback, which can help your team prioritize and respond to feedback more efficiently.

Next Steps

  • Explore Custom Models to train a classifier on your own data

  • Learn how to implement Sentiment Analysis alongside classification

  • Check out our API Reference for more advanced options# Text Classification Tutorial

Introduction

This tutorial will guide you through building a text classification system using Invictus AI. By the end, you'll have a working application that can automatically categorize text into predefined categories.

Prerequisites

  • An Invictus AI account with an API key

  • Basic understanding of JavaScript or Python

  • Installed the Invictus AI SDK (see Installation)

Step 1: Set Up Your Project

First, let's create a new project and install the required dependencies.

For JavaScript

mkdir invictus-text-classifier
cd invictus-text-classifier
npm init -y
npm install invictus-ai express

Create a new file called app.js:

const express = require('express');
const InvictusAI = require('invictus-ai');

const app = express();
app.use(express.json());

const client = new InvictusAI.Client('YOUR_API_KEY');

// We'll add our classifier code here

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

For Python

mkdir invictus-text-classifier
cd invictus-text-classifier
pip install invictus-ai flask

Create a new file called app.py:

from flask import Flask, request, jsonify
from invictus_ai import Client

app = Flask(__name__)
client = Client('YOUR_API_KEY')

# We'll add our classifier code here

if __name__ == '__main__':
    app.run(debug=True, port=3000)

Step 2: Define Your Categories

For this tutorial, we'll build a classifier that categorizes customer feedback into the following categories:

  • Positive Feedback

  • Negative Feedback

  • Feature Request

  • Bug Report

  • Question

Step 3: Create the Classification Endpoint

For JavaScript

Add the following code to your app.js file:

// Classification endpoint
app.post('/classify', async (req, res) => {
  try {
    const { text } = req.body;
    
    if (!text) {
      return res.status(400).json({ error: 'Text is required' });
    }
    
    const result = await client.nlp.classify({
      text,
      categories: [
        'Positive Feedback',
        'Negative Feedback',
        'Feature Request',
        'Bug Report',
        'Question'
      ]
    });
    
    return res.json(result);
  } catch (error) {
    console.error('Classification error:', error);
    return res.status(500).json({ error: 'Classification failed' });
  }
});

For Python

Add the following code to your app.py file:

@app.route('/classify', methods=['POST'])
def classify():
    try:
        data = request.get_json()
        text = data.get('text')
        
        if not text:
            return jsonify({'error': 'Text is required'}), 400
        
        result = client.nlp.classify(
            text=text,
            categories=[
                'Positive Feedback',
                'Negative Feedback',
                'Feature Request',
                'Bug Report',
                'Question'
            ]
        )
        
        return jsonify(result)
    except Exception as e:
        print(f"Classification error: {e}")
        return jsonify({'error': 'Classification failed'}), 500

Step 4: Test Your Classifier

Start your server:

For JavaScript

node app.js

For Python

python app.py

Now, let's test our classifier with some sample texts:

# For Positive Feedback
curl -X POST \
  http://localhost:3000/classify \
  -H 'Content-Type: application/json' \
  -d '{"text": "I love your product! It has made my life so much easier."}'

# For Feature Request
curl -X POST \
  http://localhost:3000/classify \
  -H 'Content-Type: application/json' \
  -d '{"text": "It would be great if you could add dark mode to the app."}'

# For Bug Report
curl -X POST \
  http://localhost:3000/classify \
  -H 'Content-Type: application/json' \
  -d '{"text": "The app crashes whenever I try to upload an image."}'

Step 5: Building a Simple Front-End (Optional)

Let's create a simple HTML form to test our classifier.

Create a new file called index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invictus Text Classifier</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        textarea {
            width: 100%;
            height: 150px;
            margin-bottom: 10px;
        }
        #result {
            margin-top: 20px;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            background-color: #f9f9f9;
        }
    </style>
</head>
<body>
    <h1>Invictus Text Classifier</h1>
    <p>Enter text below to classify it:</p>
    <textarea id="text" placeholder="Enter text here..."></textarea>
    <button onclick="classifyText()">Classify</button>
    <div id="result"></div>

    <script>
        async function classifyText() {
            const text = document.getElementById('text').value;
            const resultDiv = document.getElementById('result');
            
            if (!text) {
                resultDiv.innerHTML = '<p>Please enter some text.</p>';
                return;
            }
            
            resultDiv.innerHTML = '<p>Classifying...</p>';
            
            try {
                const response = await fetch('/classify', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ text })
                });
                
                const result = await response.json();
                
                if (response.ok) {
                    resultDiv.innerHTML = `
                        <h3>Classification Result:</h3>
                        <p><strong>Category:</strong> ${result.category}</p>
                        <p><strong>Confidence:</strong> ${(result.confidence * 100).toFixed(2)}%</p>
                    `;
                } else {
                    resultDiv.innerHTML = `<p>Error: ${result.error}</p>`;
                }
            } catch (error) {
                resultDiv.innerHTML = `<p>Error: ${error.message}</p>`;
            }
        }
    </script>
</body>
</html>

For JavaScript

Update your app.js to serve the HTML file:

const path = require('path');

// Add this before your routes
app.use(express.static(path.join(__dirname)));

// Add this after your routes
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
});

For Python

Update your app.py to serve the HTML file:

@app.route('/')
def index():
    return app.send_static_file('index.html')

# Make sure to create a 'static' folder and put your index.html there

Step 6: Enhancing the Classifier

For more accurate classification, you can use Invictus AI's advanced configuration options:

const result = await client.nlp.classify({
  text,
  categories: [
    'Positive Feedback',
    'Negative Feedback',
    'Feature Request',
    'Bug Report',
    'Question'
  ],
  advanced: {
    contextAwareness: true,
    sensitivityLevel: 0.7,
    minConfidence: 0.4,
    multiLabel: false
  }
});
PreviousAPI Reference OverviewNextAuthentication