분류

분류 (Classification)

이 페이지는 자바에서 LangChain4j를 사용한 분류 시스템 구현을 다뤄요. 분류는 텍스트를 미리 정의된 라벨로 분류하는 데 필수적이에요. 예를 들어 감정 분석(sentiment analysis), 의도 탐지(intent detection), 개체 인식(entity recognition) 같은 작업에서요.

출처: 공식문서

LangChain4j는 텍스트 분류의 두 가지 일반적인 접근 방식을 지원해요:

  • 라벨이 미묘한 자연어 추론에 의존할 때 AI Services를 통해 LLM을 사용
  • 각 범주에 대한 라벨링된 예시가 있고 의미적 유사성으로 분류하려 할 때 TextClassifierEmbeddingModelTextClassifier를 통해 embeddings를 사용

감정 분류 서비스 (Sentiment Classification Service)

감정 분류 시스템은 입력 텍스트를 다음 감정 범주 중 하나로 분류해요:

  • POSITIVE
  • NEUTRAL
  • NEGATIVE

구현 (Implementation)

import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.UserMessage;

public class SentimentClassification {

    // Initialize the chat model using OpenAI
    static ChatModel chatModel = OpenAiChatModel.withApiKey("YOUR_OPENAI_API_KEY");

    // Define the Sentiment enum
    enum Sentiment {
        POSITIVE, NEUTRAL, NEGATIVE
    }

    // Define the AI-powered Sentiment Analyzer interface
    interface SentimentAnalyzer {

        @UserMessage("Analyze sentiment of {{it}}")
        Sentiment analyzeSentimentOf(String text);

        @UserMessage("Does {{it}} have a positive sentiment?")
        boolean isPositive(String text);
    }

    public static void main(String[] args) {

        // Create an AI-powered Sentiment Analyzer instance
        SentimentAnalyzer sentimentAnalyzer = AiServices.create(SentimentAnalyzer.class, chatModel);

        // Example Sentiment Analysis
        Sentiment sentiment = sentimentAnalyzer.analyzeSentimentOf("I love this product!");
        System.out.println(sentiment); // Expected Output: POSITIVE

        boolean positive = sentimentAnalyzer.isPositive("This is a terrible experience.");
        System.out.println(positive); // Expected Output: false
    }
}

구성 요소 설명 (Explanation of Components)

1. Chat Model 초기화

static ChatModel chatModel = OpenAiChatModel.withApiKey("YOUR_OPENAI_API_KEY");
  • 자연어 텍스트를 처리할 OpenAI Chat Model을 초기화해요.
  • "YOUR_OPENAI_API_KEY"를 실제 OpenAI API 키로 바꿔요.

2. 감정 범주 정의

enum Sentiment {
    POSITIVE, NEUTRAL, NEGATIVE
}
  • Sentiment enum은 가능한 감정 분류를 나타내요.

3. AI 기반 감정 분석기 생성

interface SentimentAnalyzer {
    
    @UserMessage("Analyze sentiment of {{it}}")
    Sentiment analyzeSentimentOf(String text);

    @UserMessage("Does {{it}} have a positive sentiment?")
    boolean isPositive(String text);
}
  • 이 인터페이스는 두 개의 AI 기반 메서드를 정의해요:
    • analyzeSentimentOf(String text): 주어진 텍스트를 POSITIVE, NEUTRAL, 또는 NEGATIVE로 분류해요.
    • isPositive(String text): 텍스트가 긍정 감정이면 true, 아니면 false를 반환해요.

4. AI Service 인스턴스 생성

SentimentAnalyzer sentimentAnalyzer = AiServices.create(SentimentAnalyzer.class, chatModel);
  • AiServices.create()는 AI 모델을 사용해 SentimentAnalyzer 인터페이스를 동적으로 구현해요.

5. 감정 분석 실행

Sentiment sentiment = sentimentAnalyzer.analyzeSentimentOf("I love this product!");
System.out.println(sentiment); // Output: POSITIVE

boolean positive = sentimentAnalyzer.isPositive("This is a terrible experience.");
System.out.println(positive); // Output: false
  • AI 모델이 주어진 텍스트를 미리 정의된 감정 범주 중 하나로 분류해요.
  • isPositive() 메서드는 boolean 결과를 제공해요.

임베딩 기반 분류 (Embedding-Based Classification)

EmbeddingModelTextClassifier는 입력을 임베딩하고 각 라벨에 대한 임베딩된 예시와 비교해 텍스트를 분류해요. 이 접근 방식은 모든 클래스에 대해 대표적인 예시를 제공할 수 있고 각 분류 요청마다 LLM 호출이 필요 없을 때 유용해요.

import dev.langchain4j.classification.EmbeddingModelTextClassifier;
import dev.langchain4j.classification.TextClassifier;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.model.embedding.onnx.allminilml6v2q.AllMiniLmL6V2QuantizedEmbeddingModel;

import java.util.List;
import java.util.Map;

public class EmbeddingBasedSentimentClassification {

    enum Sentiment {
        POSITIVE, NEUTRAL, NEGATIVE
    }

    public static void main(String[] args) {

        Map<Sentiment, List<String>> examples = Map.of(
                Sentiment.POSITIVE, List.of("This is great!", "I love this product."),
                Sentiment.NEUTRAL, List.of("It is okay.", "This works as expected."),
                Sentiment.NEGATIVE, List.of("This is terrible.", "I am disappointed."));

        EmbeddingModel embeddingModel = new AllMiniLmL6V2QuantizedEmbeddingModel();

        TextClassifier<Sentiment> classifier = new EmbeddingModelTextClassifier<>(embeddingModel, examples);

        List<Sentiment> sentiments = classifier.classify("Awesome experience!");
        System.out.println(sentiments); // [POSITIVE]
    }
}

반환된 각 라벨에 대한 유사도 점수가 필요하면 classifyWithScores(...)를 쓸 수도 있어요. 분류기는 maxResults, minScore, meanToMaxScoreRatio 설정에 따라 라벨을 0개, 1개 또는 여러 개 반환할 수 있어요.

사용 사례 (Use Cases)

이 감정 분류 서비스는 다양한 애플리케이션에서 쓸 수 있어요:

고객 피드백 분석: 고객 리뷰를 긍정, 중립, 부정으로 분류. ✅ 소셜 미디어 모니터링: 소셜 미디어 댓글의 감정 추세 분석. ✅ 챗봇 응답: 사용자 감정을 이해해 더 나은 응답 제공.

예시 (Examples)

더 알아보기