<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by oh9008@gmail.com on Medium]]></title>
        <description><![CDATA[Stories by oh9008@gmail.com on Medium]]></description>
        <link>https://medium.com/@noodle-ds?source=rss-43cf369de0eb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Bh5J-yFZ2q3dSOTLhbWtGg.jpeg</url>
            <title>Stories by oh9008@gmail.com on Medium</title>
            <link>https://medium.com/@noodle-ds?source=rss-43cf369de0eb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 12:22:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@noodle-ds/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From Local to Global: A GraphRAG Approach to Query-Focused Summarization]]></title>
            <link>https://medium.com/noodle-ds/graphrag-3d2b51f453e3?source=rss-43cf369de0eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d2b51f453e3</guid>
            <category><![CDATA[graphrag]]></category>
            <category><![CDATA[paper]]></category>
            <dc:creator><![CDATA[oh9008@gmail.com]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 12:29:46 GMT</pubDate>
            <atom:updated>2025-03-24T07:13:00.904Z</atom:updated>
            <content:encoded><![CDATA[<h4>GraphRAG</h4><p>기존 RAG는 외부 데이터(source, document, citation, passages, etc…)로부터 query와 관련있는 정보를 검색하여 참고함으로써 LLM이 생성하는 대답을 더 향상시킨다. 하지만 RAG는 query의 길이가 길어지고, 사용자가 원하는 대답이 외부 데이터 전체와 관련이 있을 때, 올바른 대답을 하는 것을 어려워 한다. 예를 들어, “What are the main themes in the dataset?”, ”What are the key trends in how scientific discoveries are influenced by interdisciplinary research over the past decade?”등의 질문을 받았을 때 RAG는 정확한 대답을 하는 것을 어려워한다. 이러한 점을 개선하기 위해 graphRAG가 제안되었다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*30VMk-A58QXyqOKFzS0iOQ.png" /><figcaption><strong>GraphRAG pipeline</strong></figcaption></figure><p>graphRAG의 pipeline 순서는 위 그림과 같다. 순차적으로 확인해보자. 먼저 Source Documents -&gt; Text Chunks 단계에서는 document를 특정한 길이 기준으로 chunking한다. 이후 Text Chunks -&gt; Entities &amp; Relationships 단계에서는 LLM모델을 이용해 chunk로부터 각 entity와 relationship을 파악한다. 또한, LLM 모델은 entity와 relationship에 대한 설명을 생성한다. 예를 들어 다음과 같은 text가 포함된 chunk를 LLM은 entity와 relationship을 파악하도록 prompt를 입력받는다.</p><blockquote>NeoChip’s (NC) shares surged in their first week of trading on the NewTech Exchange.However, market analysts caution that the chipmaker’s public debut may not reflect trends for other technology IPOs. NeoChip, previously a private entity, was acquired by Quantum Systems in 2016. The innovative semiconductor firm specializes in low-power processors for wearables and IoT devices.</blockquote><p>이후 추출된 정보들은 다음과 같다. 또한, 추출된 정보를 토대로 LLM은 claims를 추출하도록 다른 prompt를 입력받는다.</p><ul><li>The entity NeoChip, with description “NeoChip is a publicly traded company specializing in low-power processors for wearables and IoT devices.”</li><li>The entity Quantum Systems, with description “Quantum Systems is a firm that previously owned NeoChip.”</li><li>A relationship between NeoChip and Quantum Systems, with description “Quantum Systems owned NeoChip from 2016 until NeoChip became publicly traded.”</li></ul><p>마지막으로 추출된 claim은 다음과 같다. claim은 entity에 대한 중요한 정보를 포함하고 있다.</p><ul><li>NeoChip’s shares surged during their first week of trading on the NewTech Exchange.</li><li>NeoChip debuted as a publicly listed company on the NewTech Exchange.</li><li>Quantum Systems acquired NeoChip in 2016 and held ownership until NeoChip went public.</li></ul><p>이후 Entities &amp; Relationships -&gt; Knowledge Graph로 변경한다. entity/relationship/claim 추출 과정에서 생성된 문장들(instance)이 graph에서 node가 되고, number of duplicates가 weight가 된다. number of duplicates는 각 instance의 embedding 값에 대한 cosine similarity를 사용하거나, cosine similarity 값이 정해진 값(threshold)보다 클 경우에는 normalization 과정을 통해서 값을 구한다. normalization 수식은 다음과 같다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*cn5cK9I4OIiKNicWeZtOww.png" /></figure><p>예를 들어, LLM is so good이라는 문장과 LLM is so bad라는 문장이 있을 경우, 두 문장에서 겹치는 단어는 LLM, is, so가 된다. 겹치는 단어의 길이(3)를 두 개의 문장 중 짧은 길이(4)로 나눠준 값(3/4)가 norm 값이 된다. alpha, beta는 하이퍼파라미터이며, cosine similarity는 embedding을 적용한 값이다. 이러한 과정을 통해 node와 weight를 구한 후, 초기 knowledge graph를 만든다.</p><p>이제 생성된 knowledge Graph를 이용해 graph communities를 만든다(Knowledge Graph → Graph Communities<strong>)</strong>. 다양한 알고리즘 중 Leiden 알고리즘을 사용한다. 과정은 다음과 같다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*T0tQF89PuL1jCcD7u9BvgQ.png" /><figcaption>Leiden algorithm</figcaption></figure><p>Leiden 알고리즘은 community detection 알고리즘이다. groups of node를 확인하여 연결한다. modularity를 최대화 함으로써 확인된 communities들이 잘 형성되도록 한다. modularity는 같은 community 내에 node들이 무작위로 연결된 node와 비교했을 때 얼마나 더 좋은지 정량화하는 역할을 한다. 코드는 다음과 같다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0386ea29b859f256ab5f69d109a4c7e0/href">https://medium.com/media/0386ea29b859f256ab5f69d109a4c7e0/href</a></iframe><p>이렇게 생성된 graph communities를 요약해준다(graph communities -&gt;Communities Summaries). communities는 사용자의 prompt에 따라서 leaf-level과 Higher-level로 구분된다. leaf-level communities는 degree(number of edge)에 따라서 우선순위가 부여되며 우선순위에 따라서 LLM context window에 추가되어 요약된다. leaf-level communties가 요약이 다 되면 higher-level communities가 요약된다.</p><p>마지막 단계(Community Summaries → Community Answers → Global Answer)에서는 result answer을 생성한다. 이 때, community 구조의 hierarchical nature 특성에 의하여 다른 level의 정보도 이용하여 생성된다. communtity level이 정해지면, 최후 생성된 응답은 다음과 같은 절차에 의하여 생성된다.</p><ul><li><strong>Prepare community summaries</strong> : Community summaries는 무작위로 섞이고, 정해진 chunk size로 나뉜다. 이것은 관련 있는 정보가 여러 chunk를 통해서 분산되어 사용될 수 있도록 하고, 한 번에 context window에서 소멸되지 않도록 한다.</li><li><strong>Map community answers</strong> : LLM이 생성된 응답이 얼마나 유용한지에 따라서 0~100 사이에 점수를 부여한다.</li><li><strong>Reduce to global answer</strong> : community answer가 내림차순으로 정렬되고, 반복해서 context window에 추가된다.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d2b51f453e3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/noodle-ds/graphrag-3d2b51f453e3">From Local to Global: A GraphRAG Approach to Query-Focused Summarization</a> was originally published in <a href="https://medium.com/noodle-ds">noodle-ds</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[index-based RAG]]></title>
            <link>https://medium.com/noodle-ds/index-based-rag-6ae77f06b7cf?source=rss-43cf369de0eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ae77f06b7cf</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[llamaindex]]></category>
            <category><![CDATA[deep-lake]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[oh9008@gmail.com]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 05:44:29 GMT</pubDate>
            <atom:updated>2025-03-11T07:20:42.129Z</atom:updated>
            <content:encoded><![CDATA[<h4>LlamaIndex</h4><p>index는 precision과 모델의 속도를 증가시키지만 index의 장점은 단순히 이 뿐만이 아니다. index는 transparency를 추가하여 RAG AI를 변형시킨다. index를 이용하면 사용된 데이터와 정확한 위치에 대한 시각화를 가능하게 하여 RAG 모델을 통해 생성된 응답의 source를 추적가능하게 만들어준다. 이러한 장점은 bias나 hallucinations을 줄일 수 있도록 해주며, 저작권과 데이터 무결성에 관한 문제를 다룰 수 있게 만든다.</p><p>index가 data source를 추적 가능하게 만들기 때문에, 만약 생성된 output이 만족스럽지 못하면 오랫동안 고민할 필요가 없다. 이러한 능력은 data input, system configuration 등의 요소를 수정할 수 있게 만들며, 더 좋은 결과를 얻을 수 있도록 도와준다.</p><p>index를 이용한 검색은 RAG 기반의 생성형 AI가 한 차원 더 발전할 수 있도록 만든다. 이러한 방법은 수많은 데이터를 사용할 때 raw chunks of data에서 output에 영향을 주는 document와 위치에 대한 정보를 추적할 수 있는 indexed node로 이동시킴으로써 검색의 속도를 증가시킨다.</p><p>RAG에서 index를 이용한 검색은 직접 관련있는 데이터에 indices를 이용해 접근함으로써 모든 records에 대한 embedding을 비교하는 방법인 vector를 이용한 검색보다 속도가 빠르다.</p><p>이제 코드로 index-based RAG를 구현해보자. 먼저 deep lake에서 저장된 데이터를 불러온다. 이후 데이터를 document로 변환한다. document는 llama index에서 중요하게 쓰이는 abstraction이다. 또한, document는 pdf나 API output 등의 다양한 형태의 데이터를 저장하는 container 역할을 한다. document는 데이터와 추가적으로 몇 개의 attributes를 포함하는데 다음과 같다.</p><ul><li>metadata : 데이터와 관련한 정보</li><li>relationship : 다른 document나 node와의 관계</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6396e833f9ed062e054a873735b8c9da/href">https://medium.com/media/6396e833f9ed062e054a873735b8c9da/href</a></iframe><p>이제 생성 모델과 임베딩 모델을 포함하는 파이프라인을 구축해보자. huggingface와 llamacpp를 이용하여 모델을 불러온다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1621c6d9a735c38342e84df4b1aee9db/href">https://medium.com/media/1621c6d9a735c38342e84df4b1aee9db/href</a></iframe><p>VectorStoreIndex는 document를 나누어 node로 분할한 후 검색을 위한 vector embedding을 생성하여 query에 대한 준비를 한다. 이제 query를 해보자.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28635b9132cafff9374d0a07d36975bb/href">https://medium.com/media/28635b9132cafff9374d0a07d36975bb/href</a></iframe><p>as_query_engine은 인덱스 위에 query engine을 구축한다. query engine은 다양한 parameter를 포함하고 있으며 generation에 대한 영향을 준다.</p><ul><li>k : 몇 개의 source를 사용할 것인지</li><li>temp : precision(0.1)과 creative(0.9) 중 어떤 것을 주요하게 다룰 것인지</li><li>mt : token의 최대 개수</li></ul><p>engine을 구축한 후 query를 통해 입력을 받는다. 결과는 다음과 같다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*5p4hbqlel4z0yIArYvew8g.png" /><figcaption>generation result</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMJrTdvDiP10HyVdxfgNUQ.png" /><figcaption>source result</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*eZ0g_hr_MZz8byj1UQW5AA.png" /><figcaption>chunk size result</figcaption></figure><p>markdown 형식으로 출력했기 때문에 source가 id | score | text 형식으로 출력된 것을 확인할 수 있다. 또한, source 별로 id, score, text도 출력할 수 있다. 또한, chunk size를 지정하지 않을 경우 llamaindex는 chunk size를 최적화해준다. 이때, chunk size는 static한 값이 아닌 variable이 되어 각 node마다 최적의 chunk size를 적용할 수 있게 해준다. 결과적으로 llamaindex를 활용한 RAG pipeline 구조는 다음과 같다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_bdyfNzUcTylRxu2BeiORg.png" /><figcaption>RAG pipeline by llamaindex</figcaption></figure><p>이제 결과를 확인해보자.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abc769b0ed4a0e06b627d8b28e8e5ea2/href">https://medium.com/media/abc769b0ed4a0e06b627d8b28e8e5ea2/href</a></iframe><p>결과는 cosine similarity를 기반으로 구해진다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/1*Pyy2we8ZguKM7jxuCRD4wQ.png" /><figcaption>total result</figcaption></figure><p>또한, llamaindex는 vector store index 외에도 다양한 구조의 indexing을 지원한다. 지원하는 종류는 다음과 같다.</p><ul><li>tree index</li><li>list index</li><li>keyword index</li></ul><p>llamaindex에서 사용되는 tree index는 text document를 관리하기 쉽게 해주는 계층 구조를 만든다. tree index engine는 기존의 tree 구조와는 다르게 hierarchy, content, order of the node를 최적화한다.</p><p>tree index는 documents를 tree 구조로 만들고, 높은 단계의 노드에서는 더 많은 요약을 하며, 낮은 단계의 노드에서는 세심하게 정보를 다룬다. tree에서 각 노드는 text의 정보를 요약하는 역할을 한다. tree index는 큰 데이터셋과 document set을 최적화된 chunks로 나누어 빠르게 query하는 것을 효율적으로 만들어준다. tree index를 이용하여 pipeline을 구축하고, parameter(depth, etc…)를 설정하며, summary method를 정하는 것은 필요하다.</p><p>tree index를 이용하는 LLM 모델은 query에 대한 node를 선택할 때 복수의 선택이 필요한 질문에 대하여 대답하는 것처럼 행동한다. LLM은 query를 분석하고, query와 현재 node의 자식 node를 비교한 후, 가장 관련있는 정보를 발견하여 추적한다. tree index 구현은 다음과 같다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c66104f229d8756bdfd3cffc9893707/href">https://medium.com/media/5c66104f229d8756bdfd3cffc9893707/href</a></iframe><p>tree index를 만들 때에는 build_tree = True로 지정해줘야 하며, children의 숫자를 지정해야 한다. 또한, 결과 값은 기존 vector index와 다르게 결과에 대한 score를 제공하지 않고 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESHonAaYMoLPQK-Non6VKA.png" /><figcaption>generation result using tree index</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDhMUDlZYUcEAmaH9deiyQ.png" /><figcaption>source result using tree index</figcaption></figure><p>keyword index는 document에서 keyword를 추출하고, table 구조로 만든다. 이러한 구조는 특정한 keyword나 주제와 관련한 정보를 검색하는 것을 쉽게 해준다. 추출된 keyword는 table 형태의 구조로 만들어지며, 각 keyword는 관련있는 노드를 알려주는 ID와 연결된다. 코드로 구현하는 것은 다음과 같다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4466490a0f074659e4a47abfe09ea43/href">https://medium.com/media/f4466490a0f074659e4a47abfe09ea43/href</a></iframe><p>keyword index는 각각의 keyword를 table형식으로 볼 수 있다. 최종 결과는 다음과 같다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c33eaff28f132f831c2fb67bd1858742/href">https://medium.com/media/c33eaff28f132f831c2fb67bd1858742/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*ZRRneUB11HO1GZXvjYHqwQ.png" /><figcaption>keyword and id from dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2a85VbJ4RHm0QJpXULyZpg.png" /><figcaption>result using keyword index</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ae77f06b7cf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/noodle-ds/index-based-rag-6ae77f06b7cf">index-based RAG</a> was originally published in <a href="https://medium.com/noodle-ds">noodle-ds</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[embedding vector stores]]></title>
            <link>https://medium.com/noodle-ds/embedding-vector-stores-4097087d28c0?source=rss-43cf369de0eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4097087d28c0</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[activeloop]]></category>
            <category><![CDATA[deep-lake]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[oh9008@gmail.com]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 08:03:19 GMT</pubDate>
            <atom:updated>2025-03-07T11:11:03.992Z</atom:updated>
            <content:encoded><![CDATA[<h4>deeplake, activeloop</h4><p>embedding은 semantic content를 파악하기 위해 데이터를 고차원의 벡터로 변형하는 것을 뜻한다. 이러한 과정을 통해 representation을 얻을 수 있으며 거리에 기반하여 데이터들 사이의 유사도를 파악할 수 있다. 그러나, 최근 데이터의 수가 폭발적으로 증가하고 embedding 과정에서 고차원으로 변형하기 때문에 저장 공간이 부족할 수 있다. 이러한 상황에 따라서 Deep lake와 같은 DB가 등장하게 되었다.</p><p>embedding을 통한 vector를 얻으면 빠른 검색을 위해 저장하는 것을 필요로 한다. embedding 등의 고차원의 데이터를 다루는 것에 최적화 되어 있는 DB를 vector store라고 한다. Deep lake의 Activeloop와 같은 serverless 플랫폼으로 vector store를 만들 수 있다. 또한, vector store는 최적화된 방법을 통해서 데이터를 검색할 수 있다.</p><p>RAG pipeline은 데이터 수집과 준비 -&gt; cleaning -&gt; chunking-&gt; embedding -&gt; storing in vector store 순으로 진행된다. 하지만 3개의 과정으로 나누어서 pipeline을 구축하는 것이 권장된다.</p><ul><li>data collection and preparation</li><li>data embedding and loading into a vector store</li><li>querying the dataset</li></ul><p>Activeloop를 이용해 데이터를 저장하고 불러와보자. 먼저 <a href="https://app.activeloop.ai/">https://app.activeloop.ai/</a>에 접속하여 회원가입 후 API token을 얻어야 한다.sentence transformer를 이용하여 여러 개의 GPU가 지원되는 환경에서 데이터 저장 및 로드하는 code는 다음과 같다. 패키지를 설치할 때 3.9.16버전으로 지정해줘야 한다는 것을 잊지 말자. 버전을 특정해주지 않으면 4.x 버전으로 자동 설치된다. 4버전 이상은 아직 불안정해서 패키지 에러가 발생한다. 또한, 여러 개의 GPU를 사용할 경우 아래와 같이 device name과 pool을 지정해줘야 한다. langchain과 huggingface 등 다양한 패키지를 이용해서 multiple GPU 환경에서 실행하는 방법을 연구하였으나 sentencetransformer를 이용하여 GPU를 사용하는 것이 가장 간단한 방법인 것 같다. 이후 langchain을 이용하고 싶으면 chain을 이용해 연결하는 방법이 가장 효율적 인 것 같다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4750609f2dab42a82d28ce4e7bab4080/href">https://medium.com/media/4750609f2dab42a82d28ce4e7bab4080/href</a></iframe><p>설치 후 activeloop로 가서 확인하면 다음과 같이 데이터가 추가된 것을 볼 수 있다. 예시 코드대로 metadata를 추가하다 보니 같은 내용의 metadata가 추가되었다. 또한, text와 embedding 값을 모두 확인할 수 있으며 query도 지원하는 것을 알 수 있다. 그리고 많이 사용되고 있는 dataset들을 지원하고 있는 것도 확인할 수 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*X49IVywMZHGAZx9XHuHjIw.png" /><figcaption>activeloop data example</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*wYy559A86xzlOO6X2Mkx3Q.png" /><figcaption>activeloop web example</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nAprSbWHdkUGZSj5sOxRhA.png" /><figcaption>activeloop public datasets</figcaption></figure><p>이제 deeplake를 이용해 데이터를 load하고 search 해보자.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a5ef82eba3fe0ba4b0f41d7599e45ec/href">https://medium.com/media/1a5ef82eba3fe0ba4b0f41d7599e45ec/href</a></iframe><p>약 10만 개의 pubmed dataset을 vector DB에 저장하였으며 크기는 약 650MB이다. 이후 머신러닝에 대한 정보를 얻기 위해 검색 과정을 통해 정보를 얻었다. 결과는 다음과 같았으며 abstract만을 사용했기 때문에 score가 높지는 않은 모습을 나타낸다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7zl2XFL6m7k5aPJZJMvBrg.png" /><figcaption>searching result</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4097087d28c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/noodle-ds/embedding-vector-stores-4097087d28c0">embedding vector stores</a> was originally published in <a href="https://medium.com/noodle-ds">noodle-ds</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieval-Augmented Generation(RAG)]]></title>
            <link>https://medium.com/noodle-ds/retrieval-augmented-generation-05a9c125861d?source=rss-43cf369de0eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/05a9c125861d</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[oh9008@gmail.com]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 06:54:19 GMT</pubDate>
            <atom:updated>2025-02-25T06:56:35.638Z</atom:updated>
            <content:encoded><![CDATA[<p>AI가 질문을 받았을 때 하는 대답은 틀리거나 맞지 않는 대답을 하는 경우가 있다. 이러한 현상을 hallucination이라고 한다. hallucination을 줄일 수 있는 방법은 검색을 통해서 질문과 관련한 정보를 LLM에게 제공하여 올바른 대답을 하도록 만드는 것이다. 이러한 방법을 Retrieval-Augmented Generation(RAG)라고 한다.</p><h3>Semantic Search</h3><p>semantic search는 단순히 keyword만으로 일치하는 검색 결과를 제공하는 것이 아닌 사용자의 검색 의미를 파악하여 검색하는 방법을 뜻한다. semantic search에 사용되는 기술의 방향성은 크게 3가지로 나뉜다.</p><ul><li>dense retrieval</li><li>reranking</li><li>RAG</li></ul><p>dense retrieval은 embedding을 이용하여 사용자의 query와 관련 문서들의 가까운 정도를 파악하여 제공하는 방법을 말한다. 즉, embedding을 통해 데이터들을 numerical representation으로 변환 후 가까운 데이터인 nearest neighbor를 판단하여 query와 가까운 문서를 제공한다. 대체로 embedding에 index를 부여하여 빠른 검색이 이루어지도록 하는 방법이 많이 사용되고 있다. faiss 등의 라이브러리들이 embedding indexing을 제공하고 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*z6oqduPLV_PNQMSLlXNvmA.png" /><figcaption>dense retrieval</figcaption></figure><p>dense retrieval의 가장 큰 단점은 transformer의 context vector 크기가 제한되어 있기 때문에 문서를 쪼갤 때(chunking) 어떻게 나누어야 좋은 성능의 embedding이 이루어질 지 알 수 없어 도메인을 고려하여 다양한 실험을 통해 embedding이 이루어져야 한다는 것이다. 예를 들어, 문서 전체로 chunk를 만들지 않고 진행하거나 혹은 여러 chunk로 나누는 방법 등 다양한 방법이 사용 될 수 있다. 또한, dense retrieval은 거리에 기반하여 nearest neighbor를 찾는 방법이므로 데이터의 수가 많아질수록 faiss 등을 이용해 vector DB를 생성하여 속도를 증가시키는 방법을 적용하는 것이 필요하다.</p><p>reranking은 다른 모델에서 제공한 결과의 subset에 새로운 모델을 적용해 관련성을 개선하여 문서를 제공하는 방법을 뜻한다. reranking은 다양한 검색 파이프라인에서 사용될 수 있다. reranking의 장점은 기존의 구축된 시스템에 새로운 모델만 추가하면 되기 때문에 자원을 절약하여 성능을 향상시킬 수 있다는 점이다. 검색 뿐만 아니라 많은 LLM 분야에서 사용되고 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ueSoPdMXo3MThu5ivxg4hQ.png" /><figcaption>reranking</figcaption></figure><p>RAG는 query와 관련 정보를 제공하여 query에 대한 응답을 생성하는 기술을 뜻한다. 즉, 생성 능력과 검색 능력을 모두 갖춘 기술을 말한다. LLM은 제공하는 정보에 기반하여 query에 대한 text를 생성하기 때문에 생성 단계를 grounded generation이라고도 한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AXwav93lLMCNouAUqtSuyQ.png" /><figcaption>Retrieval-Augmented Generation(RAG)</figcaption></figure><p>RAG와 관련하여 아래와 같이 다양한 기술들이 등장하고 있다.</p><ul><li>Query rewriting</li><li>Multi-query RAG</li><li>Multi-hop RAG</li><li>Query routing</li><li>etc</li></ul><p>query rewriting은 query가 너무 길거나 혹은 이전 대화를 참고해야 하는 등의 상황에서 사용자의 query를 다른 query로 바꾸어서 모델의 성능을 향상시키는 방법이다. Cohere에서 query-rewriting mode를 지정할 수 있다.</p><p>Multi-query RAG는 query를 여러 개의 query로 나눌 수 있는 경우에 모델이 판단하기 쉽도록 여러 query로 나누어서 처리하는 기술이다. 만약 검색 과정에서 모든 query에 대하여 검색을 필요로 하지 않을 경우에 좋은 선택지가 될 수 있다.</p><p>Multi-hop RAG는 query가 순차적인 경우에 단계 별로 나아가며 검색하는 기술이다. 예를 들어 2025년에 가장 큰 차 제조 회사가 어디야?? 그 회사들은 전기차를 만들고 있어??라는 질문을 한다면 2가지 질문을 토대로 먼저 2025년에 가장 큰 차 제조 회사를 검색하고 그 회사가 전기차를 만들고 있는지 검색하여 모델은 답을 생성할 것이다.</p><p>Query routing은 모델에게 다양한 data를 검색할 수 있는 능력을 주는 기술이다. 주로 query를 받았을 때 query와 관련한 DB를 선택하거나, 또는 query를 embedding 한 후 가까운 query들 중 고르게 하는 등 다양한 방법이 존재한다. 예를 들어 질문이 현재 미국의 경제 상황에 관한 것이라면 미국 경제와 관련한 데이터를 검색하도록 하는 것이고 질문이 현재 한국 경제 상황에 관한 것이라면 한국 경제와 관련한 데이터를 검색하도록 만들어 모델이 올바른 대답을 하도록 만드는 것이다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*TY6ycMuhO8svTDjyai_BoQ.png" /><figcaption>출처 : RAG from scratch</figcaption></figure><p>또한, RAG를 평가하기 위한 다양한 연구가 진행되고 있는데 대체로 많이 사용되는 방법은 evaluating verifiability in generative search engines 논문에서 제시한 Ragas를 이용하는 것이다. ragas는 4개의 기준을 가지고 RAG를 평가한다.</p><ul><li>Fluency : 생성된 text가 query와 연관되어 있고 올바르게 대답했는가??</li><li>Perceived utility : 생성된 대답이 유용한가???</li><li>Citation recall : 검색된 문서가 생성한 답변의 비율</li><li>Citation precision : 답변과 관련있는 문서의 비율</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/0*koXT9rEYCd1IZdnm.png" /><figcaption>출처 : Evaluating Verifiability in Generative Search Engines</figcaption></figure><h3>RAG vs fine tuning</h3><p>RAG와 fine tuning은 서로 대체할 수 없는 기술이다. RAG dataset 안에 너무 많은 데이터가 포함되어 있으면 시스템을 관리하는 것은 어려워진다. 또한, model을 fine-tuning할 경우 실시간으로 생성되는 데이터(날씨 데이터, 주식 시장 데이터, 뉴스 데이터 등)를 학습하기 어렵다는 단점이 존재한다. RAG나 fine tuning을 선택하는 기준은 parametric과 non-parametric 정보의 차이에 따라서 나뉜다.</p><ul><li>parametric : parametric이란 학습 데이터를 통해서 학습된 모델의 parameter(weight)를 말한다. 즉, 학습된 weight와 bias 값에 저장된 모델의 지식을 말한다. 학습 데이터는 수학적인 공식을 통해서 변형되어 parametric representation으로 여겨진다. 특히, 모델은 데이터로부터 학습되는 것을 기억하는 것이며, 데이터는 원래 형태로 저장되지 않는다.</li><li>non-parametric : parametric과 다르게 데이터를 직접 접근할 수 있는 형태로 저장한다. 데이터는 필요할 때마다 query를 위해 이용할 수 있는 형태로 저장된다. parametric 모델과는 다르게 지식은 간접적으로 weight의 형태로 embedding된다. RAG에서 non-parametric data는 실제 데이터를 사용자가 볼 수 있고 사용할 수 있도록 한다.</li></ul><p>RAG와 fine-tuning의 차이는 모델이 처리해야 하는 static(parametric) data와 dynamic(non-parametric) data의 양의 차이에 달려있다. RAG가 비중이 큰 시스템은 관리하기 어렵고 과부하가 발생할 수 있다. fine-tuning의 비중이 더 큰 시스템은 실시간 정보를 받아들이는 것이 어렵다는 단점이 있다.</p><p>RAG 중심의 생성형 AI 관리자는 non-parametric RAG를 사용하기 전에 학습된 parametric AI 모델의 성능을 평가해야 한다. RAG의 잠재력 또한 많은 평가를 요구한다. RAG 중심의 생성형 ecosystem에서 retreiver와 generator 성능 향상의 균형은 프로젝트의 목표와 요구사항에 따라서 달라진다. RAG와 fine-tuning은 서로 배제할 수 없는 요소이다. RAG는 fine-tuning과 함께 사용될 때 모델의 전체적인 효율성을 증가시킬 수 있으며, RAG framework에 속한 검색과 생성의 성능을 향상시킬 수 있다.</p><h3>The RAG ecosystem</h3><p>RAG 중심의 생성형 AI는 많은 요소를 통해 실행되는 framework이다. RAG의 framework는 넓은 ecosystem 안에서 실행된다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o7XWyP5tGfJyQB09UhjAkQ.png" /><figcaption>RAG ecosystem example</figcaption></figure><ul><li>Retrieval(R) : data collection, processing, storage, retrieval</li><li>Generator(G) : input augmentation, prompt engineering, generation</li><li>Evaluator(E) : mathematical metrics, human evaluation, feedback</li><li>Trainer(T) : initial pre-trained model, fine-tuning model</li></ul><h3>types of RAG framework</h3><p>RAG framework는 프로젝트에 따라서 크게 3가지의 종류로 나눌 수 있다.</p><ul><li>Naive RAG : Naive RAG는 복잡한 embedding이나 indexing을 포함하지 않는다. 대체로 keyword search와 같이 적은 양의 데이터를 이용한 RAG framework를 뜻한다. 주로 특정 도메인 내에서 정의된 문서에 사용될 수 있다.</li><li>Advanced RAG : dataset의 크기가 커짐에 따라서 keyword에 기반하여 문서를 검색하는 것은 너무 오랜 시간이 소요된다. 따라서, index를 사용하여 검색하는 방법이 등장하였으며 데이터를 load하는 시간을 줄여주게 되었다. Advanced RAG는 vector search나 index-based search와 같이 naive RAG보다 복잡한 경우에 사용되는 RAG framework를 뜻한다.</li><li>Modular RAG: naive RAG나 advaned RAG, machine learning 등의 다양한 기술을 적용한 RAG framework를 뜻한다.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05a9c125861d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/noodle-ds/retrieval-augmented-generation-05a9c125861d">Retrieval-Augmented Generation(RAG)</a> was originally published in <a href="https://medium.com/noodle-ds">noodle-ds</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluating Verifiability in Generative Search Engines]]></title>
            <link>https://medium.com/noodle-ds/evaluating-verifiability-in-generative-search-engines-256aa28d8990?source=rss-43cf369de0eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/256aa28d8990</guid>
            <category><![CDATA[paper]]></category>
            <dc:creator><![CDATA[oh9008@gmail.com]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 06:51:36 GMT</pubDate>
            <atom:updated>2025-02-06T06:51:36.177Z</atom:updated>
            <content:encoded><![CDATA[<h3>abstract</h3><p>generative search engine은 user의 query와 in-line citation에 따라서 대답을 생성한다. generative search engine의 신뢰를 위한 필수적인 특성은 verifiability(검증가능성)이다. 즉, 종합적이고(high citation recall, 모든 응답은 인용과 관련이 있다). 정확하게(high citation precision, 모든 인용은 연관된 응답과 관련이 있다.) 인용해야 한다. 논문에서는 4개의 generative search engine을 감사하기 위하여 사람의 평가를 한다. 논문에서는 현재 존재하는 generative search engine 들이 유능하고 똑똑하지만, 부적절한 인용과 응답을 하는 것을 발견했다. 평균적으로, 생성된 문장의 51.5%가 인용한 문서와 관련이 있고 인용된 문서의 74.5%가 생성된 문장과 관련이 있다. 이러한 결과들은 정보를 검색하는 사용자들에게 primary tool로 사용되어지지만 그들의 신뢰성을 고려하면 낮은 성능을 나타낸다. 논문에서의 결과가 신뢰할 수 있는 generative search engine 개발의 계기가 되기를 바라고, 연구자들과 사용자들이 존재하는 시스템들의 단점을 이해할 수 있기를 바란다.</p><h3>Introduction</h3><p>generative search engine은 input query와 in-line citations에 대한 응답을 직접 생성함으로 사용자가 필요한 정보를 제공한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*HGQcksVmbJz_tXJ10cdu_Q.png" /><figcaption>Figure 1 : generative search engine은 사용자의 질문과 in-line citations를 이용해 대답한다. 그러나 모든 생성된 응답들은 citations과 연관되어 있지 않고(citation recall), 모든 citation은 대답과 연관되어 있지 않다(citation precision).</figcaption></figure><p>현재 개발된 generative search engine은 사용자들의 수가 폭발적으로 증가하고 있다. generative search engine은 사람들이 정보를 온라인으로 찾는 방법을 변화시킬 수 있는 잠재력을 가지지만, 현재 개발된 모델이 지원하는 generative search engines이 생성한 응답들은 항상 정확하지 않을 수도 있다. 모델의 잠재력과 빠른 발전을 생각하면, 모델의 한계를 이해하기 위해 모델을 평가하는 것은 중요하다.</p><p>신뢰할 수 있는 generative search engine의 필수적인 특성은 verifiability(검증가능)이다. 즉, 외부 세계(input)에 대해 생성된 응답들은 in-line citations과 큰 연관이 있어야 하고, 제공된 citation들은 생성된 응답과 큰 연관이 있어야 한다. verifiability는 생성된 응답이 cited source(citation)와 관련이 있는지 확인하는 것을 가능하게 한다.</p><p>본 논문에서는 4개의 인기있는 generative search engine을 감사하기 위해 다양한 query를 이용하여 사람이 평가한다. 각각의 query-response pair에 대해 다양한 요소를 기준으로 사람이 평가한다:</p><ul><li>fluency : 생성된 text가 유창하고 생각을 잘 나타내는지</li><li>perceived utility : 생성된 대답이 유용한지</li><li>citation recall : 외부 세계(input)에 대하여 citation과 관련이 있는 생성된 대답의 비율</li><li>citation precision : 생성된 대답과 관련이 있는 citation의 비율</li></ul><p>신뢰할 수 있는 generative search engine은 높은 citation recall, precision을 나타내야 한다.</p><p>현재 개발된 generative search engine은 뛰어난 유용성과 perceived utility을 나타내지만, 자주 연관이 없는 대답이나 부적절한 citation을 사용한다(low citation recall and precision). 평균적으로, 생성된 문장의 51.5%가 인용한 문서와 관련이 있고 인용된 문서의 74.5%가 생성된 문장과 관련이 있다. 게다가 citation precision은 perceived utility과 음의 상관관계(r = -0.96)를 나타낸다. 유용할지도 모르는 대답이 부적절한 citation과 연관이 있다. 신뢰성은 존재하는 generative search engine의 사용자에게 잘못된 응답을 할 가능성을 높인다. figure 1에서 적은 배경지식을 가진 사용자가 생성된 대답에 대해 판단하는 것은 어렵다. 논문의 저자는 generative search engine이 인용된 webpage를 복사하거나 다른 말로 표현하기 때문에 citation precision이 perceived utility과 음의 상관관계의 관계라는 가설을 세웠다. 복사된 text가 인용된 webpage와 연관이 있기 때문에 citation precision을 향상시켰지만, 복사된 text가 query와는 관련이 없기 때문에 perceived utility은 감소했다.</p><p>contribution:</p><ul><li>citation recall과 citation precision 평가 metrics 정의</li><li>4개의 모델에 대하여 평가 진행, 부적절한 응답과 citation 활용 포함</li><li>perceived utility와 citation precision 사이의 음의 상관관계 존재 발견</li></ul><h3>Human Evaluation of Fluency, Perceived Utility, and Verifiability</h3><h4>Task Formulation</h4><ul><li>input : q (query)</li><li>generative text : r (with embedded in-line citation)</li></ul><p>citation precision과 recall을 평가하기 위해 r을 n개의 statements(s)으로 나눈다(S = {s1, …, sn}). S는 r안의 문장으로 구성된 set이다. Ci는 statements(si)와 관련이 있고, c(i,j)는 i번째 statement와 관련이 있는 j번째 citation이다. 각각의 c(i,j)와 관련된 URL u(i,j)와 내용 p(i,j)를 가지고 있다. (즉, si = blueberries[1], cherries[2], and grapes[3] grow on trees.[4]라면 ci = {[1],[2],[3],[4]}). 실제로 문장은 많은 독립적으로 검증가능한 주장을 포함한다.</p><h4>Measuring Fluency and Perceived Utility</h4><p>response fluency를 측정하기 위해 annotator는 user의 query와 생성된 response과 “the response is fluent and cohesive”라는 주장을 볼 것이다. annotator는 Strongly Disagree ~ Strongly Agree의 5개 등급 중 1개를 부여할 것이다. perceived utility를 측정하기 위한 방법도 유사한 방법이 사용될 것이다.</p><h4>Measuring Citation Recall</h4><p>Citation recall은 관련된 citation에 의하여 검증될 수 있는 답변의 비율이다. 그러므로, citation recall 계산은 (1) 검증 가능한 (verification-worthy) 답변 확인 (2) 각각의 검증 가능한 답변이 관련된 citation과 큰 연관이 있는지 평가하는 것이다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*UKHeJNJ8TTXUmePjUXi4Ig.png" /><figcaption>FIgure 2: citation recall, citation precision 계산 예시. partially-supporting citation은 답변이 citation 전부와 관련이 있고, 다른 full support가 없을 때 citation precision만 향상시킨다.</figcaption></figure><p><strong>검증 가능한(verification-worthy) statements 확인.</strong></p><p>statements S가 r의 일부인 것을 고려하여 annotator에게 검증이 불가능하다면 statements를 제거할지 물어본다. 논문에서는 external world(input)에 대해 모든 생성된 statement는 검증가능하다는 입장을 취한다. 생성된 statements는 틀릴지도 모르고, 어떤 사람들에게 확실한 statements는 다른 사람에게는 확실하지 않을 수도 있다. systems은 statements를 사용하는 사람들이 쉽게 확인할 수 있도록 외부 세계(input)에 대하여 모든 생성된 statement들의 근거를 제공해야 한다.</p><p><strong>검증 가능한 statement가 관련된 citation과 완전히 관련이 있는지 평가.</strong></p><p>statements S가 r의 일부인 것을 고려하여 annotator는 각각의 statement가 관련된 citation과 연관이 있는지 없는지 평가한다(Figure 1 예시 확인). 맞는지 틀린지(binary) 판단을 위해서, Attributable to Identified Sources (AIS)를 사용한다. 특히, generic hearer가 statement(si)가 cited webpages(Ci)에 의한 것임을 확인한다면 statement(si)는 관련된 citations(Ci)와 큰 관련이 있고, 그렇지 않으면 관련이 없다는 것을 확인할 수 있다.</p><h4>Measuring Citation Precision</h4><p>Citation precision은 생성된 statements와 관련이 있는 citation의 비율이다(Figure 2). citation recall과 다르게 citation precision은 적절한 citing을 위해 system에게 보상을 준다. 각각의 생성된 statement를 위해 모든 internet webpage에서 인용된 응답은 높은 citation recall을 나타내지만, low citation precision을 나타낸다(인용된 정보들이 statement와 관련이 없기 때문에). r에 대한 citation precision을 측정하기 위해 annotator가 각각의 citation(c(i,k))가 statement(si)에 기여한 기여도를 full, partial, no로 평가한다(Figure 1 확인).</p><ul><li>Full support : statement와 관련된 모든 정보는 citation과 관련이 있다.</li><li>Partial support : statement와 관련된 일부 정보는 citation과 관련이 있지만, 일부 정보는 관련이 없다.</li><li>No support : citation은 statement의 어떤 부분과도 관련이 없다.</li></ul><p>많은 연관된 citation을 가지고 있는 statements를 위해 annotator에게 관련된 cited webpage들이 statement와 관련이 있는지 확인한다. citation precision도 AIS를 사용한다.</p><p>citation precision을 측정하기 위해 Tfs는 statement를 full support하는 citation의 수이고, Tps는 partially support하는 수이다. N은 전체 citation의 수이다. citation precision = (Tfs + Tps) / N.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=256aa28d8990" width="1" height="1" alt=""><hr><p><a href="https://medium.com/noodle-ds/evaluating-verifiability-in-generative-search-engines-256aa28d8990">Evaluating Verifiability in Generative Search Engines</a> was originally published in <a href="https://medium.com/noodle-ds">noodle-ds</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[scientific paper topic modeling]]></title>
            <link>https://medium.com/noodle-ds/scientific-paper-topic-modeling-e692ce5faa1a?source=rss-43cf369de0eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e692ce5faa1a</guid>
            <category><![CDATA[reranking]]></category>
            <category><![CDATA[bertopic]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[sentence-transformers]]></category>
            <category><![CDATA[keybert]]></category>
            <dc:creator><![CDATA[oh9008@gmail.com]]></dc:creator>
            <pubDate>Fri, 31 Jan 2025 11:32:44 GMT</pubDate>
            <atom:updated>2025-01-31T11:35:07.897Z</atom:updated>
            <content:encoded><![CDATA[<h4>(feat. runpod, sentence transformer, bertopic, reranking, keyBERT)</h4><p>topic modeling을 조금 더 심층적으로 알아보기 위해 과학 논문 데이터를 사용하여 topic modeling을 진행하고자 한다. 데이터는 huggingface에서 제공하는 armanc/scientific_papers 데이터를 사용한다. armanc/scientific_papers는 “A Discourse-Aware Attention Model for Abstractive Summarization of Long Documents” 논문에서 사용되었으며 많은 곳에서 연구용 데이터로 사용되고 있다. 또한, arxiv와 pubmed의 OpenAccess repositories를 통해서 제공하는 데이터로 구성되어 있다. 데이터를 먼저 load해준다. 데이터 구성은 다음과 같다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7f41b8e8dbeee024322d7082d8a4116/href">https://medium.com/media/d7f41b8e8dbeee024322d7082d8a4116/href</a></iframe><pre>/** arxiv dataset */<br> <br>DatasetDict({<br>    train: Dataset({<br>        features: [&#39;article&#39;, &#39;abstract&#39;, &#39;section_names&#39;],<br>        num_rows: 203037<br>    })<br>    validation: Dataset({<br>        features: [&#39;article&#39;, &#39;abstract&#39;, &#39;section_names&#39;],<br>        num_rows: 6436<br>    })<br>    test: Dataset({<br>        features: [&#39;article&#39;, &#39;abstract&#39;, &#39;section_names&#39;],<br>        num_rows: 6440<br>    })<br>})</pre><pre>/** pubmed dataset */<br><br>DatasetDict({<br>    train: Dataset({<br>        features: [&#39;article&#39;, &#39;abstract&#39;, &#39;section_names&#39;],<br>        num_rows: 119924<br>    })<br>    validation: Dataset({<br>        features: [&#39;article&#39;, &#39;abstract&#39;, &#39;section_names&#39;],<br>        num_rows: 6633<br>    })<br>    test: Dataset({<br>        features: [&#39;article&#39;, &#39;abstract&#39;, &#39;section_names&#39;],<br>        num_rows: 6658<br>    })<br>})</pre><p>데이터를 간단히 확인해보다가 arxiv dataset에서 의아한 태그를 발견했다. pubmed dataset은 이상이 없지만 arxiv에서는 @xcite라는 태그와 @xmath라는 태그가 있었다. 구글링을 통해서도 나오지 않길래 직접 실제 문서와 대조해봤다.</p><pre>&#39;additive models @xcite provide an important family of models for semiparametric regression or classification . some reasons for the success of additive models are their increased flexibility when compared to linear or generalized linear models and their increased interpretability when compared to fully nonparametric models .\nit is well - known that good estimators in additive models are in general less prone to the curse of high dimensionality than good estimators in fully nonparametric models .\nmany examples of such estimators belong to the large class of regularized kernel based methods over a reproducing kernel hilbert space @xmath0 , see e.g. @xcite . in the last years\nmany interesting results on learning rates of regularized kernel based models for additive models have been published when the focus is on sparsity and when the classical least squares loss function is used , see e.g. @xcite , @xcite , @xcite , @xcite , @xcite , @xcite and the references therein . of course , the least squares loss function is differentiable and has many nice mathematical properties , but it is only locally lipschitz continuous and therefore regularized kernel based methods based on this loss function typically suffer on bad statistical robustness properties , even if the kernel is bounded .\nthis is in sharp contrast to kernel methods based on a lipschitz continuous loss function and on a bounded loss function , where results on upper bounds for the maxbias bias and on a bounded influence function are known , see e.g. @xcite for the general case and @xcite for additive models .\ntherefore , we will here consider the case of regularized kernel based methods based on a general convex and lipschitz continuous loss function , on a general kernel , and on the classical regularizing term @xmath1 for some @xmath2 which is a smoothness penalty but not a sparsity penalty , see e.g. @xcite .</pre><blockquote>Additive models [30, 9, 10] provide an important family of models for semiparametric regression or classification. Some reasons for the success of addi† The work by A. Christmann described in this paper is partially supported by a grant of the Deutsche Forschungsgesellschaft [Project No. CH/291/2–1]. The work by D. X. Zhou described in this paper is supported by a grant from the Research Grants Council of Hong Kong [Project No. CityU 104710]. 1tive models are their increased flexibility when compared to linear or generalized linear models and their increased interpretability when compared to fully nonparametric models. It is well-known that good estimators in additive models are in general less prone to the curse of high dimensionality than good estimators in fully nonparametric models. Many examples of such estimators belong to the large class of regularized kernel based methods over a reproducing kernel Hilbert space H, see e.g. [21, 38]. In the last years many interesting results on learning rates of regularized kernel based models for additive models have been published when the focus is on sparsity and when the classical least squares loss function is used, see e.g. [18], [1], [17], [19], [22], [33]</blockquote><p>즉, @xcite는 레퍼런스 표기를 나타내는 것이고, @xmath는 수식을 나타내는 태그 역할을 한다. 여기서 2개의 데이터셋이 조금 다른데 학습이 원활하게 될지 생각을 하며 2개의 데이터를 결합해주었다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae710f502c0b0777a62fed38515e89a2/href">https://medium.com/media/ae710f502c0b0777a62fed38515e89a2/href</a></iframe><p>또한, runpod을 이용하여 클라우드 환경에서 실험을 진행하기 때문에 gpu를 사용하지 않을 때는 runpod을 멈춰주어야 한다. 하지만 멈출 때마다 jupyter notebook의 커널이 멈추므로 재시작 할 때마다 jupyter notebook이 다시 시작된다. 따라서 데이터를 매번 load하는 것은 시간이 오래 걸리므로 데이터를 저장한다. 데이터를 local에서 load하는 코드는 다음과 같다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55ed0963b9941ab3697f90850feb9c1d/href">https://medium.com/media/55ed0963b9941ab3697f90850feb9c1d/href</a></iframe><p>dataset은 크게 abstract, article, section_names로 구성된다. abstract는 논문의 abstract 부분을 나타내고, article은 나머지 부분을 나타낸다. 또한, section_names는 논문에서 각 섹션의 이름을 뜻한다. 각각의 데이터를 추출한다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa1e3cabc83da3325323cd790dbf5a43/href">https://medium.com/media/fa1e3cabc83da3325323cd790dbf5a43/href</a></iframe><p>이제 데이터를 이용하여 먼저 embedding을 시켜야 한다. V100 FHHL GPU 1대를 가지고 실험을 하는 입장으로써 직접 모델을 학습시키기에는 많은 제약이 따른다. 또한, 최근 출시되는 모델들의 파라미터 수가 많고 크기가 커짐에 따라서 sentence transformer를 이용하여 사전학습된 모델을 이용해 실험을 진행한다.</p><p>sentence transformer는 embedding을 위한 모델을 평가하고 학습하는 파이썬 모듈이다. 대체로 cross-encoder 방식과 bi-encoder 방식으로 나뉜다. cross-encoder 방식은 2개의 문장 쌍이 같은 네트워크로 들어가서 처리되는 방식으로 여러 문장 중 2개의 문장 조합을 만들어 full attention으로 학습하기 때문에 학습 시간이 오래 걸린다. 이와 반대로 bi-encoder는 문장을 다른 차원으로 mapping 시키는 방식을 학습하기 위해 네트워크(siamese network, triplet network, etc..)를 이용함으로 cross-encoder 방식에 비해서 빠르게 학습되지만 정확도 측면에서는 cross-encoder 방식이 더 높다. 최근에는 cross-encoder 방식과 bi-encoder 방식을 혼합한 구조를 사용한 방법들이 연구되고 있다.</p><p>여러 모델 중 MTEB leaderboard를 확인하여 성능이 좋고 상대적으로 가벼운 모델을 골라서 실험을 진행한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dTLxTXhWneshN0Lr_d1pWg.png" /><figcaption>clustering 성능 순위(MTEB leaderboard)</figcaption></figure><p>stella_en_1.5B_v5 모델과 stella_en_400M_v5 모델을 고민하던 중 2개 모델의 성능 차이가 파라미터 수 차이의 비해서 크지 않기 때문에 상대적으로 파라미터 수가 적은 stella_en_400M_v5 모델을 사용한다. 그 밖에 모델들은 embedding 과정에서 많은 GPU를 요구하기 때문에 사용이 어렵다. 다양한 모델을 적용해봤지만 모델을 상황에 맞게 고르는 것도 쉽지 않은 일이다.. GPU 갯수를 3개로 늘려서 sentence transformer에서 제공하는 start_multi_process_pool()을 사용하여 진행했다. device를 지정하는 부분에서 “GPU”, “GPU”, “GPU” 이런 식으로 사용하면 1개의 GPU만 사용하게 된다. “CUDA:0”, “CUDA:1”, “CUDA:2” 이렇게 사용해야 한다는 것을 기억하자. 또한, 사용 시에는 if __name__ == “__main__” 블럭 안에 있어야 한다.</p><p>322961개의 abstract 데이터를 1024차원으로 embedding 시켰다. 약 40분의 시간의 시간이 소요됐다. GPU 1개일 때는 약 5시간의 시간이 걸린다. 이후 embedding 데이터를 빠르게 load하기 위해 numpy 파일로 저장한다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f4800f761f1909fed1085ce4bc5d595/href">https://medium.com/media/8f4800f761f1909fed1085ce4bc5d595/href</a></iframe><p>이후 clustering 결과를 확인하기 위해 시각화를 진행한다. 시각화를 효율적으로 하기 위해 UMAP을 적용한다. UMAP은 t-sne처럼 시각화를 위해 사용되는 기술로써 최근 차원 축소 기술 중 가장 뛰어난 성능을 나타낸다. 또한, UMAP은 고차원 데이터의 graph representation을 저차원의 graph로 구조적으로 유사하게 최적화하는 기술이다. UMAP에 대한 구체적인 설명은 <a href="https://pair-code.github.io/understanding-umap/index.html">https://pair-code.github.io/understanding-umap/supplement.html</a>를 참고하자. 하이퍼파라미터는 top2vec 논문에서 추천하는 min_dist = 0.25와 n_neighbors = 15를 적용했으며, 효율적인 시각화를 위하여 2차원으로 축소하기 위해 n_components = 2로 설정했다. 1024차원의 데이터를 2차원으로 축소하는데 약 20분 정도가 걸렸다. 속도가 굉장히 빠르다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6e8bbe8e609bdb18b6dc2cff9cb558f/href">https://medium.com/media/b6e8bbe8e609bdb18b6dc2cff9cb558f/href</a></iframe><p>clustering 알고리즘은 hdbscan 알고리즘을 사용한다. clustering 알고리즘의 경우 하이퍼파라미터 값에 따라서 너무 많은 영향을 받는다. 현재 실험도 min_cluster_size가 15이나 100일 때는 적은 수의 cluster가 생성된다. 하지만 min_cluster_size가 50일 경우에는 84개의 cluster가 생성되고, 60일 때는 251개의 cluster가 생성된다. 필요에 따라서 실험을 통해 최적화 하는 것이 중요하다. 가장 많은 cluster가 생성된 60을 사용한다. cluster가 많은 것이 좋다고는 할 수 없지만 다양한 clustering을 생성함으로써 선택지가 넓어지기 때문에 좋은 topic을 생성할 수 있다고 생각한다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc1aa54f1ff7d31c13d997654be91f6e/href">https://medium.com/media/bc1aa54f1ff7d31c13d997654be91f6e/href</a></iframe><p>이후 outlier 처리와 시각화를 진행한다. HDBSCAN은 outlier의 cluster를 -1로 지정해준다. 회색 부분은 outlier를 나타내고, 색이 있는 부분은 의미있는 cluster가 형성된 것을 볼 수 있다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0840fee0c1ee792260fa885b418fdfb6/href">https://medium.com/media/0840fee0c1ee792260fa885b418fdfb6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*Xpr9vZBZy813GGc8PmAgog.png" /><figcaption>UMAP을 이용한 시각화</figcaption></figure><p>더 향상된 결과를 얻기 위해 bertopic을 사용한다. bertopic은 transformer와 c-TF-IDF를 이용하여 topic representations을 추출하는 모델이다. bertopic에 관한 설명은 <a href="https://medium.com/noodle-ds/text-clustering-and-topic-modeling-d6b1d77d4a22">https://medium.com/noodle-ds/text-clustering-and-topic-modeling-d6b1d77d4a22</a>를 참고하기 바란다. 또한, 시각화가 목적이 아니므로 UMAP의 차원을 5차원으로 변경한다. 그리고 outlier를 제거해준다. outlier는 the, of, in, and, to, is, for, with, we, that과 같이 많이 나오거나 큰 의미를 담고 있지 않은 단어들이 representation으로 나타난 문서들이다. outlier를 제거하는 과정에는 약 15분 정도가 걸린다. 이후 모델을 저장한다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2537147ccdc63d2e5431765885926f29/href">https://medium.com/media/2537147ccdc63d2e5431765885926f29/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4pf_Vx-4VE8FxsxhF_eHNA.png" /><figcaption>topic information (outlier 제거 전)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzbPcbbP27utyCOaW031cw.png" /><figcaption>topic information (outlier 제거 후)</figcaption></figure><p>모델이 약 12만 개의 데이터를 outlier로 처리했다.너무 많은 데이터를 outlier로 처리한 것 같다. 그러나 outlier 삭제 이후에도 일부 데이터가 outlier로 남아있는 것을 확인했다. 모든 outlier를 삭제하지는 않는 것 같다. outlier 처리 전에 데이터를 갖고 추가적인 실험을 진행해야겠다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*osQ4yxsbz_vYQ8sSCd1Hjw.png" /><figcaption>0번째 topic 정보</figcaption></figure><p>또한, 0번째 topic 정보를 보니 teeth, dental, bone, tooth 등의 입이나 뼈와 관련한 topic인 것 같다. 그러나 was나 were와 같이 의미를 담고 있지 않은 단어들이 포함되어 있다. 추가적인 모델을 적용하여 개선할 필요가 있다. 그리고 topic modeling을 이용해서 키워드가 포함된 topic도 추출할 수 있다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fd2e6c60d2bceeb92f7a24d09ecbbf1/href">https://medium.com/media/5fd2e6c60d2bceeb92f7a24d09ecbbf1/href</a></iframe><p>또한, 각 주제를 나타내는 keyword를 시각화한 결과는 다음과 같다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68b8712a59cfe9727fb2172416540dea/href">https://medium.com/media/68b8712a59cfe9727fb2172416540dea/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGknS9SnWQ9LQLiJYdNvfQ.png" /><figcaption>각 topic별 주요 keyword</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*uSMV6kHj4pfodicY8cTlzQ.png" /><figcaption>topic별 유사도 관계</figcaption></figure><p>이제 Bertopic을 적용한 결과 reranking을 적용해보자. reranker 모델로는 KeyBERTInspired를 적용하여 변경된 결과를 확인해보자.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/372d28bfcfaa5d49c10d434e1138773b/href">https://medium.com/media/372d28bfcfaa5d49c10d434e1138773b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*Gs-W46MP_KRppOEVsN43hw.png" /></figure><p>마지막으로 지금까지 진행한 모델의 구성도를 확인해보자. embedding 모델로는 Stella 모델, 차원 축소 모델은 UMAP, 클러스터링 모델은 HDBSCAN, topic representation에는 Count Vetorizer와 c-TF-IDF 모델을 사용했으며 Reranker 모델은 keyBERT 모델을 사용했다. <a href="https://medium.com/noodle-ds/text-clustering-and-topic-modeling-d6b1d77d4a22">https://medium.com/noodle-ds/text-clustering-and-topic-modeling-d6b1d77d4a22</a>를 기반으로 실험을 진행했다. 많은 시도를 했지만 처음 embedding 모델의 중요성을 제일 크게 느낀 것 같다. 처음에는 cde-small-v2 모델을 사용하여 topic representation까지 진행했다. 하지만 아래와 같이 이후 단계가 어려울 정도로 topic modeling이 원활하게 되지 않는 것을 확인했다. 다양한 모델을 적용할 수 있는 것이 topic modeling의 장점이자 단점임을 다시 느낄 수 있었다. 이후에는 비교적 최근에 나온 fastopic과 다른 모델들을 적용하여 프로젝트를 진행해봐야겠다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NYuLWWL-alO80Hg4Th3o2A.png" /><figcaption>모델의 구성</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5FLzMC4hIuqN4IvRRDJtGw.png" /><figcaption>cde-small-v2 모델 사용 시 topic representation 결과</figcaption></figure><p>이후 진행 목표</p><ul><li>fastopic 적용해 실험</li><li>hyperparameter tuning</li><li>model 변경 후 실험</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e692ce5faa1a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/noodle-ds/scientific-paper-topic-modeling-e692ce5faa1a">scientific paper topic modeling</a> was originally published in <a href="https://medium.com/noodle-ds">noodle-ds</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangChain]]></title>
            <link>https://medium.com/noodle-ds/langchain-77b8d1e86d84?source=rss-43cf369de0eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/77b8d1e86d84</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[llm-memory]]></category>
            <dc:creator><![CDATA[oh9008@gmail.com]]></dc:creator>
            <pubDate>Fri, 10 Jan 2025 06:46:45 GMT</pubDate>
            <atom:updated>2025-01-10T06:46:45.597Z</atom:updated>
            <content:encoded><![CDATA[<p>LangChain은 LLM을 활용한 개발이나 업무 등의 행동을 단순하게 해주는 framework이다. LangChain은 복잡한 LLM 시스템을 쉽게 구축할 수 있도록 여러 요소가 연결되어 있는 구조를 갖고 있다.</p><ul><li>Model I/O : prompts, LLM, output parser</li><li>Memory : conversation memory, summarization</li><li>Retrieval : embeddings, documents, vector database</li><li>Agents : autonomous, ReAct, conversation</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YKSByjWKwpfVSgabS-Nl7w.png" /></figure><h3>Model I/O</h3><p>LangChain을 이용해서 모델을 loading하고 사용할 수 있다. 또한, quantized model도 사용할 수 있다. quantized model을 GGUF model이라고도 하는데, 원래의 model을 quantization을 통해서 압축한 모델이다. quantization이란 LLM의 parameter를 나타내는데 필요한 bits의 수를 줄이는 것을 말한다. quantization은 압축하는 것이기 때문에 모델이 가지고 있는 정보를 최대한 손실시키지 않고 보존하여 압축하는 것이 필요하다. 대체로 4-bit 이상의 크기로 압축된 quantized model이 사용되며 4-bit 아래의 모델은 성능이 많이 낮아지기 때문에 잘 사용되지 않는다.</p><h3>Chains</h3><p>chain은 LLM과 여러 다른 요소들(tool, prompt, feature, …)을 연결하는 역할을 하며, LLM의 능력을 확장시키는 역할을 한다. 가장 기본적인 형태는 single chain이며 다음과 같다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gn0KdNtXfNzCnZj8nvQSw.png" /></figure><p>우리는 원하는 output을 생성하기 위해 LLM과 prompt template을 연결해서 사용할 수 있다. 예시로 사용될 Phi-3 모델의 template은 4개의 요소를 이용한다.</p><ul><li>&lt;s&gt; : Beginning Of Sentence(BOS)</li><li>&lt;|user|&gt; : 사용자의 prompt 시작</li><li>&lt;|assistant|&gt; : model의 output 시작</li><li>&lt;|end|&gt; : prompt 종료, output 종료</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf2637f9572e81901bb16b303d6c6753/href">https://medium.com/media/bf2637f9572e81901bb16b303d6c6753/href</a></iframe><blockquote>Hello! It’s great to see you here. How can I assist you today?</blockquote><p>또한, 여러 개의 component를 연결하여 사용할 수도 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TxROlUOG7PnZRHO-8hW0-A.png" /></figure><p>예를 들어 캐릭터를 만든다고 하면 1개의 input과 여러 개의 prompt를 연결하여 다양한 특성(name, ability, birthplace, …)을 가진 캐릭터를 만들 수 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o6rNz00mAYi4uY-mIlrt1Q.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aae1b8f746b48ad4130a744df37f9c91/href">https://medium.com/media/aae1b8f746b48ad4130a744df37f9c91/href</a></iframe><pre>&#39;feature&#39;: &#39;a person that very strong and smart&#39;,<br> &#39;name&#39;: &#39; Dr. Evelyn Stronghart&#39;,<br> &#39;ability&#39;: &#39; Dr. Evelyn Stronghart is an exceptionally formidable and brilliant mind, renowned for her unwavering strength in both intellect and character.&#39;,<br> &#39;birthplace&#39;: &quot; Dr. Evelyn Stronghart hails from the historic city of Oxford, England, where she was born into a family known for their intellectual prowess and resilience. Raised in a prestigious academic environment surrounded by some of the world&#39;s leading scholars, her birthplace has played an instrumental role in shaping her exceptionally formidable and brilliant mind. Oxford&#39;s rich history of producing great minds cultivated Dr. Stronghart&#39;s unwavering strength in both intellect and character, making her a renowned figure not only within the academic world but also among those who recognize true leadership and brilliance.&quot;</pre><p>여러 개의 component를 연결하여 사용하는 방식의 장점은 각각의 component에 접근하여 수정하고 추가하는 등의 관리가 용이하다는 것이다.</p><h3>Memory</h3><p>LLM을 사용할 때, 모델만으로는 기억할 수 있는 능력이 없기 때문에 이전 prompt에서 받은 질문과 대화를 기억할 수 없다. 이러한 단점은 LLM이 작동하는 과정에서 불안정하게 만든다. 따라서 이전 내용을 기억하기 위해 2가지 방식이 존재한다.</p><ul><li>Conversation buffer</li><li>Conversation summary</li></ul><p>conversation buffer는 이전에 있던 전체 대화 내용을 prompt에 입력하여 기억하게 하는 방식이다. langchain의 ConversationBufferMemory를 이용한다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5225945e3fea1cebc0de124f698f5670/href">https://medium.com/media/5225945e3fea1cebc0de124f698f5670/href</a></iframe><pre> &#39;input_prompt&#39;: &#39;Can you recommend lunch menu??. only one menu and Use a sentence.&#39;,<br> &#39;chat_history&#39;: &#39;&#39;,<br> &#39;text&#39;: &#39; How about a delicious Mediterranean wrap filled with grilled chicken, fresh vegetables, and creamy tzatziki sauce for a satisfying and nutritious lunch option?&#39;</pre><pre> &#39;input_prompt&#39;: &#39;What is lunch menu you recommended before?&#39;,<br> &#39;chat_history&#39;: &#39;Human: Can you recommend lunch menu??. only one menu and Use a sentence.\nAI:  How about a delicious Mediterranean wrap filled with grilled chicken, fresh vegetables, and creamy tzatziki sauce for a satisfying and nutritious lunch option?&#39;,<br> &#39;text&#39;: &#39; I recommended a Mediterranean wrap with grilled chicken, fresh vegetables, and tzatziki sauce for lunch.</pre><p>가장 큰 고민인 점심 메뉴를 LLM에게 물어보았다. 처음에 추천해준 메뉴를 기억하고 있는 것을 확인할 수 있다.</p><p>하지만 이러한 방식은 정해진 token 수까지 모든 대화를 기억하므로 자원 사용과 운영에서 비효율적이다. 이를 개선하기 위해 정해진 숫자의 대화만 기억하는 ConversationBufferWindowMemory를 사용할 수 있다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a1cc6a6ed081acb2ad21ad79948297b/href">https://medium.com/media/5a1cc6a6ed081acb2ad21ad79948297b/href</a></iframe><pre>&#39;input_prompt&#39;: &#39;Can you recommend dinner menu??. only one menu and Use a sentence?&#39;,<br> &#39;chat_history&#39;: &#39;Human: Can you recommend breakfast menu??. only one menu and Use a sentence??\nAI:  A delicious and nutritious breakfast option is a Greek yogurt parfait with mixed berries, granola, and honey.\nHuman: Can you recommend lunch menu??. only one menu and Use a sentence.\nAI:  For a well-rounded and energizing lunch, I recommend a Quinoa Salad with roasted vegetables, chickpeas, feta cheese, and a lemon vinaigrette dressing. This meal is packed with protein, fiber, vitamins, and minerals to keep you satisfied throughout the afternoon.&#39;,<br> &#39;text&#39;: &#39; A delightful and comforting dinner option is Herb-Roasted Chicken served with a side of creamy mashed sweet potatoes, roasted Brussels sprouts, and a fresh mixed greens salad. This meal offers a balance of protein, healthy fats, fiber, and essential nutrients to nourish your body after a long day.&#39;</pre><pre>&#39;input_prompt&#39;: &#39;What is breakfast menu you recommended before?&#39;,<br> &#39;chat_history&#39;: &#39;Human: Can you recommend lunch menu??. only one menu and Use a sentence.\nAI:  For a well-rounded and energizing lunch, I recommend a Quinoa Salad with roasted vegetables, chickpeas, feta cheese, and a lemon vinaigrette dressing. This meal is packed with protein, fiber, vitamins, and minerals to keep you satisfied throughout the afternoon.\nHuman: Can you recommend dinner menu??. only one menu and Use a sentence?\nAI:  A delightful and comforting dinner option is Herb-Roasted Chicken served with a side of creamy mashed sweet potatoes, roasted Brussels sprouts, and a fresh mixed greens salad. This meal offers a balance of protein, healthy fats, fiber, and essential nutrients to nourish your body after a long day.&#39;,<br> &#39;text&#39;: &#39; For a nutritious and energizing breakfast, I recommend Avocado Toast topped with scrambled eggs, cherry tomatoes, and sprinkled with chili flakes on whole-grain bread. This meal is rich in healthy fats, protein, fiber, and vitamins to kickstart your day.&#39;</pre><p>아침과 점심 메뉴를 추천한 후 저녁 메뉴를 추천할 때까지는 chat_history에 추천했던 아침과 점심 메뉴가 있는 것을 확인할 수 있다. 하지만 이후 추천해준 아침 메뉴를 물어보면 chat_history에 아침 메뉴가 없는 것을 확인할 수 있다.</p><p>기억할 대화의 수를 지정하는 것은 자원과 운용을 효율적으로 만들 수는 있지만 기억할 대화의 수를 지정하는 것은 어렵고, 나중에 필요한 대화의 수를 예측하기 어렵다는 단점이 있다. 이러한 방식을 개선하기 위해 대화를 하는 역할의 LLM과 대화를 요약하는 역할의 LLM을 나누어서 사용하는 방식인 ConversationSummaryMemory를 사용하여 메모리를 효율적으로 운영하는 방식이 있다.</p><h3>Agents</h3><p>agents란 LLM이 할 수 있는 action 중에서 직접 선택하여 행동을 하는 system이다. agents는 앞서 살펴본 model I/O, chains, memory 등의 요소로 구성된다. 또한, 실제 상황과 유사하게 API나 계산기와 같은 tool을 LLM 모델이 사용할 수도 있다. 이러한 agents를 구현하기 위해 Reasoning and Acting(ReAct) 프레임워크를 사용한다. reasoning은 prompt engineering에서 사용된 CoT에서 나온 것과 같은 개념이다. Acting은 LLM이 사용할 수 있는 tool 등을 이해하게 함으로 행동할 수 있는 능력을 갖게 하는 것이다. ReAct는 다음과 같은 3단계를 반복한다.</p><ul><li>Thought(what it should do)</li><li>Action(what it will do)</li><li>Observation(the result of the action)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3babe2ea9b1de7eab88db62014dccabd/href">https://medium.com/media/3babe2ea9b1de7eab88db62014dccabd/href</a></iframe><pre>&gt; Entering new AgentExecutor chain...<br><br>Action: duckduck<br>Action Input: &quot;current price of a MacBook Pro in USD&quot;snippet: As of April 2024, the latest MacBook Pro 14-inch M3 model started with a retail price of 1,599 U.S. dollars while the 16-inch M3 Pro version began with a retail price of 2,499 U.S. dollars., title: Apple MacBook Pro price comparison 2024 - Statista, link: https://www.statista.com/statistics/1360426/apple-macbook-pro-price-comparison/, snippet: For the latest prices and sales, see our 14&quot; MacBook Pro Price Tracker, updated daily ... Read More. December 27, 2024. Holiday Sale: 16-inch M4 Max MacBook Pro for $400 off MSRP at B&amp;H. B&amp;H Photo is offering a $400 discount on new 16-inch MacBook Pros with an M4 Max CPU as part of their ongoing Holiday sales. B&amp;H offers free 1-2 day shipping ..., title: MacPrices.net | The original source for late-breaking Apple sales &amp; deals, link: https://www.macprices.net/, snippet: M3 Pro 16-inch MacBook Pro (512GB, 18GB RAM): was $2,499 now $2,199 @ Amazon Apple&#39;s powerful 16-inch MacBook Pro is on sale right now. The 16-inch MacBook Pro can be configured with the M3 Pro or ..., title: Every M3 MacBook Pro has dropped to its lowest price in huge pre-Prime ..., link: https://www.tomsguide.com/computing/macbooks/every-m3-macbook-pro-has-dropped-to-its-lowest-price-in-huge-pre-prime-day-sale-up-to-dollar500-off, snippet: We include prices for new as well as Apple Certified Refurbished models, along with any open-box MacBooks that might be available. Current sales range up to $300 off MSRP for new MacBooks and up to $1200 off clearance MacBook Pros: - 16″ MacBook Pros - 14″ MacBook Pros - 13″ MacBook Pros - 15″ MacBook Airs - 13″ MacBook Airs, title: Updated MacBook Pro and MacBook Air Price Trackers, link: https://www.macprices.net/2024/02/07/updated-macbook-pro-and-macbook-air-price-trackers/<br><br>&lt;|assistant|&gt; Question: What is the current price of a MacBook Pro in USD? How much would it cost in EUR if the exchange rate is 0.85 EUR for 1 USD.<br>Thought: The latest MacBook Pro prices can be found on various sources like Statista, MacPrices.net and Tom&#39;s Guide. I will use duckduck to search for the most recent price of a MacBook Pro in USD.<br>Action: duckduck<br>Action Input: &quot;current price of a MacBook Pro in USD&quot;snippet: As of April 2024, the latest MacBook Pro 14-inch M3 model started with a retail price of 1,599 U.S. dollars while the 16-inch M3 Pro version began with a retail price of 2,499 U.S. dollars., title: Apple MacBook Pro price comparison 2024 - Statista, link: https://www.statista.com/statistics/1360426/apple-macbook-pro-price-comparison/, snippet: This stellar MacBook deal knocks a staggering $300 off on the fan-favorite Apple MacBook Pro 14 with M3 Pro Chip. Launch date: October 2023 Price history: This is the lowest price we&#39;ve ever seen ..., title: The MacBook Pro 14 with M3 Pro dips $300 to its all-time-low price ..., link: https://www.laptopmag.com/laptops/macbooks/the-macbook-pro-14-with-m3-pro-dips-dollar300-to-its-all-time-low-price-right-before-school-starts, snippet: M3 Pro 16-inch MacBook Pro (512GB, 18GB RAM): was $2,499 now $2,199 @ Amazon Apple&#39;s powerful 16-inch MacBook Pro is on sale right now. The 16-inch MacBook Pro can be configured with the M3 Pro or ..., title: Every M3 MacBook Pro has dropped to its lowest price in huge pre-Prime ..., link: https://www.tomsguide.com/computing/macbooks/every-m3-macbook-pro-has-dropped-to-its-lowest-price-in-huge-pre-prime-day-sale-up-to-dollar500-off, snippet: We include prices for new as well as Apple Certified Refurbished models, along with any open-box MacBooks that might be available. Current sales range up to $300 off MSRP for new MacBooks and up to $1200 off clearance MacBook Pros: - 16″ MacBook Pros - 14″ MacBook Pros - 13″ MacBook Pros - 15″ MacBook Airs - 13″ MacBook Airs, title: Updated MacBook Pro and MacBook Air Price Trackers, link: https://www.macprices.net/2024/02/07/updated-macbook-pro-and-macbook-air-price-trackers/<br>The latest MacBook Pro starting prices are $1,599 and $2,499. I will convert the lower price to EUR using a hypothetical exchange rate of 0.85 EUR per USD.<br>Action: Calculator<br>Action Input: &quot;1599 * 0.85&quot;Answer: 1359.1499999999999<br>The current price of the MacBook Pro in EUR, using an exchange rate of 0.85 EUR per USD for the lowest priced model (14-inch M3), is approximately 1359.15 EUR.<br>Final Answer: The current price of a MacBook Pro in USD ranges from $1,599 to $2<br><br>&gt; Finished chain.<br>{&#39;input&#39;: &#39;What is the current price of a MacBook Pro in USD? How much would it cost in EUR if the exchange rate is 0.85 EUR for 1 USD.&#39;,<br> &#39;output&#39;: &#39;The current price of a MacBook Pro in USD ranges from $1,599 to $2&#39;}</pre><p>예를 들어, 유로화를 달러로 바꾸어 맥북을 구매하기 위해 가격을 알고자 할 경우 ReAct를 이용해서 LLM이 web에서 검색하고 직접 가격을 확인하여 알려줄 수 있다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77b8d1e86d84" width="1" height="1" alt=""><hr><p><a href="https://medium.com/noodle-ds/langchain-77b8d1e86d84">LangChain</a> was originally published in <a href="https://medium.com/noodle-ds">noodle-ds</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Engineering]]></title>
            <link>https://medium.com/noodle-ds/prompt-engineering-ee02cf8ee95a?source=rss-43cf369de0eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee02cf8ee95a</guid>
            <category><![CDATA[in-context-learning]]></category>
            <category><![CDATA[tree-of-thought]]></category>
            <category><![CDATA[chain-of-thought]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[oh9008@gmail.com]]></dc:creator>
            <pubDate>Tue, 07 Jan 2025 08:48:43 GMT</pubDate>
            <atom:updated>2025-01-31T11:35:43.916Z</atom:updated>
            <content:encoded><![CDATA[<p>GPT 등의 text를 생성하는 모델은 사용자의 prompt에 따라서 text를 생성하는데 뛰어난 능력을 나타낸다. prompt는 질문(question)이 될 수도 있고, 지시사항(instruction)이 될 수도 있고, 다양한 형태가 될 수 있다. 그러므로 prompt engineering을 통해서 모델에 의해서 생성되는 text를 원하는 방향으로 변경하여 기존 모델이 생성하는 것보다 높은 수준의 결과를 얻을 수 있다.</p><h3>Component of a Prompt</h3><p>LLM은 prompt(input)에 대하여 이후에 올 단어나 문장을 예측하는 것이다. LLM으로부터 원하는 결과를 이끌어내기 위하여 어떤 구조를 갖춘 prompt를 이용해야 한다. 여기서 구조란 여러 component로 구성되는 것을 뜻한다. component는 instruction, data, indicator 등의 다양한 요소를 뜻한다. 원하는 결과를 얻기까지 prompt component를 추가하거나 변경하는 등의 행동이 이루어져야 한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*inROsjlN8ZlwsEwM_AP9CQ.png" /></figure><p>추가적으로 사용되는 component는 다음과 같다.</p><ul><li>Persona(identity) : LLM의 역할(expert, teacher, …)</li><li>Instruction(main goal) : LLM이 해야하는 일</li><li>Context(additional info) : 추가적인 정보</li><li>Format(additional info) : output의 format 지정</li><li>Audience(for whom?) : 생성된 text를 사용하는 대상</li><li>Tone(style of text) : LLM의 text style(professonal, clear, kind, …)</li><li>etc</li></ul><p>component에 따라 output의 결과가 달라지기 때문에 component를 추가하고 삭제하는 등 다양한 실험을 통해서 prompt의 component를 사용하는 것이 중요하다.</p><h3>Instruction-Based Prompting</h3><p>prompting은 LLM에게 어떤 문제를 해결하거나 원하는 질문에 대한 정답을 얻으려고 하는 것이다. 이를 instruction-based prompting이라고 한다. instruction-based prompting은 supervised classification, search, summarization, code generation, entity recognition 등의 다양한 분야에서 사용되고 있다. 이렇게 많은 분야에서 사용되고 있지만, prompt engineering을 통해 원하는 결과를 얻기 위해서 생각해야 하는 요소는 다음과 같다.</p><ul><li>Specificity : 원하는 것을 구체적이고 정확하게 설명</li><li>Hallucination : LLM이 정확하지 않은 정보를 생성하는 것</li><li>Order : 문장이 길어질수록 prompt의 시작이나 끝에 지시사항 입력</li></ul><h3>In-context Learning</h3><p>LLM에게 우리가 원하는 것을 예시를 통해서 설명하는 것을 in-context learning이라고 한다. 예시를 사용하지 않는 것을 Zero-shot prompting, 1개의 예시를 사용하는 것을 One-shot prompting, 1개보다 많은 예시를 사용하는 것을 Few-shot prompting이라고 한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CgqYZsPN_s0zKPIEJ05ywg.png" /></figure><p>코드에서는 질문하는 역할을 user로 정하고, 모델이 해야하는 일을 알려주는 역할을 assistant로 정한다.</p><h3>Chain Prompting</h3><p>in-context learning의 경우 prompt가 복잡해지거나 component가 많아질 경우 이용하기 어렵다는 단점이 존재한다. 이러한 문제를 해결하기 위해 prompt의 output을 다른 prompt에서 이용하는 chain prompting이 사용됐다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*5Ini3xDerOO9XxvwMtA_0Q.png" /></figure><h3>Chain-of-Thought(CoT)</h3><p>chain-of-thought는 생성 모델이 추론없이 바로 생성하는 것이 아닌 모델이 생각 과정을 가지도록 하는 것이다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b107b2fe434c792b205ca2fe1417b971/href">https://medium.com/media/b107b2fe434c792b205ca2fe1417b971/href</a></iframe><blockquote>The cafeteria started with 23 apples. They used 20 apples for lunch, so they had 23–20 = 3 apples left. After buying 6 more apples, they now have 3 + 6 = 9 apples. The answer is 9.</blockquote><p>모델이 생각한 과정과 정답을 모두 생성한 것을 확인할 수 있다. chain-of-thought에서도 동일하게 예시를 들지 않고 추론 과정과 정답을 모두 생성한 것을 zero-shot chain-of-thought라고 한다. 또한, “Let’s think step-by-step”, “show your work” 등의 문장을 prompt에 포함하면 모델이 추론하는 과정을 알 수 있다.</p><h3>Controlling Model output except prompt engineering</h3><p>prompt engineering 외에도 모델의 parameter를 변경하여 다른 결과를 얻을 수 있다. 대체로 모델의 temperature parameter와 top_p parameter를 변경하여 이를 조정한다. 여기서 LLM이 재미있는 부분은 같은 prompt에도 parameter를 변경하여 다른 결과를 얻을 수 있다는 것이다.</p><p>예를 들어, 아래와 같이 다음 token이 생성될 가능성은 모델 학습 시 사용된 vocabulary에 속한 word마다 각각 부여된다. 이때, 생성될 가능성이 높은 word가 있고 낮은 word가 있기 때문에 다른 결과가 나올 수 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KsNgJRs0cBDBN3DpobpArQ.png" /></figure><p>temperature와 top_p parameter를 사용하기 위해서는 do_sample=True로 지정해야 한다.</p><h4>Temparature</h4><p>temperature parameter는 생성된 text의 randomness를 정한다. 즉, temparature가 0에 가까울수록(낮을수록) 같은 prompt에 대해서 거의 유사한 text를 생성한다. 하지만 temparature가 커질수록 같은 prompt에 대해서 다른 text를 생성할 확률이 증가한다. temparature를 적용한 수식은 다음과 같으며 t를 뜻한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*s9AxG6Z12o_Blv9hTipU5A.png" /></figure><h4>top_p</h4><p>nucleus sampling이라고도 하며, LLM이 이용할 수 있는 token subset을 제한한다. 원하는 누적 확률(cumulative probability)이 일정한 값(top_p)를 넘지않도록 지정한다. token별로 확률이 높은 token부터 선택된다.</p><h4>top_k</h4><p>top_p가 누적 확률을 기준으로 하는 것과는 다르게 top_k는 확률이 높은 token의 수를 지정한다. k=0일 경우는 모든 token을 고려하는 것을 뜻한다.</p><h3>Self-Consistency(SC)</h3><p>self-consistency는 top_k와 temparature 등의 parameter를 변경하여 같은 prompt를 이용해 모델이 생성한 여러 text에 majority voting 방식을 적용해 최종 결과를 얻는 방법이다. 하지만 여러 번 같은 prompt를 이용해서 생성하므로 속도가 느리다는 단점이 존재한다.</p><h3>Tree-of-Thought(ToT)</h3><p>tree-of-thought는 많은 추론 과정을 요구하는 문제가 주어졌을 때, 문제를 쪼개어서 해결하는 과정이다. 각 트리의 단계에서 모델이 다른 노드(다음 단계)로 갈 것인지 prompt를 이용하여 진행한다. 이때, 생성되는 생각의 수는 parameter로 지정할 수 있다. 또한, 각 단계마다 생성된 노드에 등급을 부여하여 등급이 낮은 경우에는 그 뒤에 있는 생각은 탐색하지 않는다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*vj5NuPBQpJvTjMczB8UrZQ.png" /><figcaption>출처 : Tree of Thoughts: Deliberate Problem Solving with Large Language Models</figcaption></figure><p>ToT 역시 모델을 여러 번 호출하기 때문에 속도가 느리다는 단점이 존재한다. 이러한 단점을 개선하기 위해 prompt에서 마치 여러 명의 답변을 받은 것처럼 prompt를 이용할 수 있다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9535364848dcdf2636b096e5b7de44ab/href">https://medium.com/media/9535364848dcdf2636b096e5b7de44ab/href</a></iframe><blockquote>Step 1: Expert A Initially, the cafeteria had 23 apples. They used 20 apples to make lunch, so we subtract 20 from 23. 23–20 = 3 apples remaining</blockquote><blockquote>Step 2: Expert B After using 20 apples for lunch, the cafeteria had 3 apples left. They then bought 6 more apples. We add 6 to the remaining 3 apples. 3 + 6 = 9 apples</blockquote><blockquote>Step 3: Expert C The cafeteria started with 23 apples, used 20 for lunch, and then bought 6 more. To find the total number of apples, we subtract the used apples and add the purchased apples. 23–20 + 6 = 9 apples</blockquote><blockquote>All experts agree that the cafeteria now has 9 apples.</blockquote><p>예시는 3명의 전문가들이 문제에 대한 답을 하는 것처럼 보인다. 이와 같이 prompt를 이용하는 방법에 따라서 시간의 효율성도 고려할 수 있다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee02cf8ee95a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/noodle-ds/prompt-engineering-ee02cf8ee95a">Prompt Engineering</a> was originally published in <a href="https://medium.com/noodle-ds">noodle-ds</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[text clustering and topic modeling]]></title>
            <link>https://medium.com/noodle-ds/text-clustering-and-topic-modeling-d6b1d77d4a22?source=rss-43cf369de0eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6b1d77d4a22</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[topic-modeling]]></category>
            <category><![CDATA[text-clustering]]></category>
            <category><![CDATA[reranking]]></category>
            <category><![CDATA[bertopic]]></category>
            <dc:creator><![CDATA[oh9008@gmail.com]]></dc:creator>
            <pubDate>Thu, 02 Jan 2025 07:14:38 GMT</pubDate>
            <atom:updated>2025-01-02T07:14:38.523Z</atom:updated>
            <content:encoded><![CDATA[<p>text clustering은 semantic content, meaning, relationship 등의 언어적으로 유사한 text를 grouping하는 task를 뜻한다. 여기서 semantic content란 언어적 표현이나 개념 또는 단어나 문장이 전달하는 의미를 말한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZiqiLqGjhwPh0lv0GA9h7A.png" /></figure><p>text clustering과 topic modeling은 다양한 language 모델을 결합하는 방법을 사용한다.</p><h3>A Pipeline for Text Clustering</h3><p>text clustering에는 graph-based NN, centroid-based clustering 등 많은 방법이 사용되지만, 대체로 많이 사용되는 방법은 3단계 과정을 통한 pipeline을 이용하는 것이다.</p><ol><li>embedding 모델을 사용하여 input을 embedding으로 변환</li><li>차원 축소 모델을 사용하여 embedding 차원 축소</li><li>cluster 모델을 사용하여 유사한 document group 찾기</li></ol><h3>documents to embeddings</h3><p>embedding은 documents 데이터의 의미를 나타내는 numerical representation이다. 즉, documents 데이터를 다른 차원으로 mapping(projection)시켜 얻은, 의미를 나타내는 값이다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*y-cVMVsStH7DIyBHDr5tYg.png" /></figure><p>embedding 차원은 64,128,256,512,… 등 다양한 parameter를 사용할 수 있다. 이러한 embedding을 위한 모델은 많은 모델이 사용되기 때문에 MTEB leaderboard를 확인하여 원하는 목적을 이루기 위해 좋은 성능을 나타내는 다양한 모델을 적용해보는 것이 중요하다.</p><h3>Reducing the Dimensionality of Embeddings</h3><p>embedding 차원의 수가 증가함으로써 각 차원에 존재하는 값들의 수가 증가하게 된다. 이러한 경우에 각 차원에 속한 subspace들을 확인하는 것은 복잡하다. 즉, 차원이 증가할수록 의미있는 cluster를 확인하는 것이 어려워지므로 고차원의 데이터에 clustering 기술을 적용하는 것이 어려워진다. 따라서 embedding 차원의 수를 줄이기 위한 기술을 적용하는 것이 필요하다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*7R8XwD7c2owSE760Rx36Gg.png" /></figure><p>잘 알려진 차원축소 방법은 Principal Component Analysis(PCA), Uniform Manifold Approximation and Projection(UMAP) 등의 방법이 존재한다. 최근에는 UMAP가 좋은 성능을 나타내는 것으로 알려져있다.</p><p>하지만 차원 축소의 경우 고차원의 데이터를 저차원의 데이터로 축소하는 것이기 때문에 정보가 손실될 수 있다. 이러한 단점을 고려하여 차원 축소와 정보를 유지하는 정도 사이에서 균형을 잡는 것이 중요하다.</p><h3>Clustering the Reduced Embeddings</h3><p>차원 축소된 embedding을 clustering하는 방법은 centroid-based 알고리즘(ex. k-means), density-based 알고리즘(ex. DBSCAN, HDBSCAN) 등의 방법이 존재한다. 하지만 centroid-based 알고리즘은 cluster의 수를 설정해야 하기 때문에 cluster의 수를 알지 못하는 상황에서 사용하기에는 위험이 존재한다. 따라서 density-based 알고리즘이 centroid-based 알고리즘보다 많이 사용된다. 특히, 최근에는 데이터의 outlier를 확인하여 어떤 cluster에도 포함시키지 않는 방법인 HDBSCAN이 많이 사용된다.</p><h3>Text Clustering to Topic Modeling</h3><p>text clustering은 언어적 의미가 유사한 documents 데이터를 각각의 cluster로 묶어서 구분하는 것을 말한다. topic modeling은 언어 데이터를 설명할 수 있는 숨겨진 주제나 의미를 발견하는 것을 말한다. 여기서 topic이란 데이터를 대표할 수 있는 단어 그룹을 뜻한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z8HDSeqDGekAGjNhLy_Scg.png" /></figure><p>위 예시에서 Topic 1을 보면 Input 데이터들을 먼저 dog cluster, cat cluster 등의 동물을 나타내는 cluster들을 구성한다. 그래서 동물을 나타내는 다양한 keyword들을 이용해 동물이라는 topic을 나타낼 수 있도록 하는 것이다.</p><p>즉, topic modeling은 1개의 label을 topic으로 사용하는 것이 아닌 다양한 keyword들을 이용하여 topic의 의미를 이해할 수 있도록 하는 것이다. 최근에는 BERTopic을 이용하여 topic modeling을 하는 방법이 많이 사용되고 있다.</p><h3>BERTopic</h3><p>BERTopic은 topic representations를 얻기 위해 유사한 text들의 cluster들을 이용하는 topic modeling 기술이다. BERTopic은 4단계로 진행된다.</p><ol><li>Embed documents</li><li>Reducing the dimensionality of embeddings</li><li>Clustering compressed embeddings</li><li>Modeling a distribution over words</li></ol><p>3단계까지는 위에서 진행한 순서와 동일하다. 추가된 단계는 4단계이다. 4단계에서는 class-based variant of Term Frequency-Inverse Document Frequency(c-TF-IDF)를 사용한다. c-TF-IDF는 cluster에서 많은 의미를 담고있는 단어에 더 많은 weight를 부여하고, 여러 cluster에서 많이 사용된 단어는 적은 weight를 부여하는 방법이다. 즉, cluster마다 데이터에 등장한 word들의 빈도수와(c-TF) weight역할을 하는 IDF값을 곱하는 방법이다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sa0cZCtP1KXPKBkjtbOBeg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6GWUJFaJNAjXLMHsFngGFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*5KCJb1Q5LHj_sJfEjgNVpQ.png" /></figure><p>결과적으로 c-TF-IDF를 사용할 경우 모든 documents에 등장한 words의 weight는 작아지고, cluster를 분별할 수 있는 words의 weight는 커진다. 따라서 topic에서 word의 weight가 높을수록 topic을 더 잘 나타낸다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9Nu4CsLU0yvg8wWqm8_hg.png" /></figure><p>BERTopic의 pipeline은 clustering과 topic representation으로 구성되어 있다. pipeline은 clustering과 topic representation이 독립적으로 되어있기 때문에 각각의 과정에서 다양한 모델을 적용하여 좋은 성능을 얻을 수 있다는 장점이 있다.</p><h3>Using a reranker</h3><p>앞서 설명한 BERTopic의 Topic representation은 결국 bag-of-words를 이용하기 때문에 문맥의 의미적인 관계를 파악하기 어렵다는 단점이 있다. 이러한 단점을 개선하기 위해 embedding 모델과 같은 추가적인 기술을 기존 방법에 적용하여 representation을 효율적으로 파악하는 방법이 있다. 기존 방법에 여러 방법을 추가하여 topic의 ranking을 개선하는 것을 reranking이라고 하며, 추가적으로 적용된 방법이나 모델을 reranker model(representation model)이라고 한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DK5bj9poysFbv4h1x6uTig.png" /></figure><p>reranker model의 장점은 topic representation의 최적화 과정에서 데이터 input의 수가 아닌 topic의 수만큼 반복함으로써 시간과 자원을 효율적으로 줄일 수 있다는 것이다. 또한, model을 1가지가 아닌 여러 개의 모델을 이용하여 개선된 결과를 얻을 수 있다.</p><h3>KeyBERTInspired</h3><p>KeyBERTInspired는 word embedding과 document embedding 값의 cosine similarity를 이용하여 keywords를 얻는 방법이다. 즉, c-TF-IDF 값을 이용하여 topic마다 가장 값이 높은 words와 documents를 추출하고, cosine similarity를 이용하여 document들의 average embedding 값과 각 word들의 embedding 값의 유사한 정도를 확인해 keyword를 추출한다. 이때, word와 document embedding은 같은 embedding 모델을 이용한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*OUJFCdBH-DCfQT4jvrmZaQ.png" /></figure><h3>Maximal Marginal Relevance(MMR)</h3><p>c-TF-IDF와 KeyBERTInspired 기술은 중복되는 결과를 고려하지 않기 때문에 중복이 되는 keyword가 존재한다. 이러한 중복을 줄이고 topic representation을 다양하게 하기 위해 MMR을 사용할 수 있다. MMR의 목적은 representation의 중복을 줄이고 다양한 representation을 파악하는 것이다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*XPlXJSV8WfG-b6_XEYlpfA.png" /></figure><h3><strong>Reranking using g</strong>enerative model</h3><p>데이터 input을 활용하여 topic을 생성하는 방법도 있지만, 이전의 얻은 keyword와 document 데이터를 이용해 label을 생성하는 방법도 있다. generative model을 이용해 이전에 생성된 keyword와 적은 양의 representative document 데이터들을 이용해 모델에게 질의함으로써 label을 생성하는 방법이다. 이때, 2가지의 tag를 이용해야 하는데 먼저 [DOCUMENTS] tag를 이용해 document 데이터들을 지정한다. 이러한 데이터들은 c-TF-IDF와 cosine similarity를 이용해 선택할 수 있다. 그리고 이전에 얻은 keyword들은 [KEYWORDS] tag를 이용해 지정해야 한다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6b1d77d4a22" width="1" height="1" alt=""><hr><p><a href="https://medium.com/noodle-ds/text-clustering-and-topic-modeling-d6b1d77d4a22">text clustering and topic modeling</a> was originally published in <a href="https://medium.com/noodle-ds">noodle-ds</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text Classification]]></title>
            <link>https://medium.com/noodle-ds/text-classification-a413b957949b?source=rss-43cf369de0eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a413b957949b</guid>
            <category><![CDATA[text-classification]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[oh9008@gmail.com]]></dc:creator>
            <pubDate>Sun, 29 Dec 2024 12:34:06 GMT</pubDate>
            <atom:updated>2024-12-29T12:34:06.231Z</atom:updated>
            <content:encoded><![CDATA[<p>NLP에서 많이 수행하는 task는 classification이다. 이러한 task의 목적은 모델이 학습을 통해 예측해야 하는 input text에 label(class)를 부여하는 일이다. 대체로 sentiment analysis부터 intent detection까지 많은 분야에서 사용되고 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*g1HPZOAtsU5dzIo-gsCrRg.png" /></figure><p>LLM에서 classification을 위해 representation model과 generative model 둘 다 사용할 수 있다. 하지만 두 모델의 classification은 차이가 있다.</p><h4>Representation model for text classification</h4><p>classification에 사용된 representation model은 task-specific model과 embedding model로 나누어진다. bert와 같은 모델들은 task에 따라서 2가지 형태로 나눌 수 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_gNQ3O4YdsNixDvNMS6tGg.png" /></figure><p>task-specific model은 sentiment analysis와 같이 정해진 task를 위해 사용되는 모델이다. 이와 다르게 embedding model은 classification 외에도 다양한 task를 위하여 사용되는 model로 특정한 task를 위해 사용되는 모델이 아니므로 general-purpose model이라고 한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kzBg3_C-G2zflB49ce-0Mw.png" /></figure><h4>Generative model for text classification</h4><p>generative model의 방식은 representation model이 classification하는 방식과 다르다. generative model은 token을 순차적으로 생성함으로써 classification을 수행하기 때문에 sequence-to-sequence model이라고 한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2rPelXnzS8mUrAYY2EliFw.png" /></figure><p>하지만 generative model은 input의 context와 token 간의 관계에 영향을 많이 받기 때문에 원하는 classification을 수행하기 위해 추가적으로 prompt를 변경하여 올바른 답을 찾는 과정을 필요로 한다.</p><h3>if we don’t have labeled data</h3><p>만약 label이 정해진 데이터를 가지고 있지 않다면 다양한 방법이 존재하겠지만 Zero-shot model을 사용하여 classification을 수행할 수 있다. 우리가 label이 의미하는 뜻은 알고 있지만, label이 정해진 데이터가 없기 때문에 여러 후보 label과 데이터를 input으로 사용하여 데이터에 label을 부여하는 방법을 사용할 수 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*ek1wBRH1NCAgZABOXusFKg.png" /></figure><p>또한, embedding을 적용하여 input embedding 값과 후보 label들의 거리를 측정하여 거리가 가까운 쪽의 label을 input의 label로 적용하는 방법도 존재한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zFSJdiuF_H6pCBe8sNaY5A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a413b957949b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/noodle-ds/text-classification-a413b957949b">Text Classification</a> was originally published in <a href="https://medium.com/noodle-ds">noodle-ds</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>