Now Loading ...
-
-
-
-
Llamaindex pipeline
pipeline(W. document, node)
documentd와 node를 하나의 pipeline으로 엮어서 사용하는 방식을 말합니다.
{% highlight python %}
import re
from llama_index.core import Document
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.core.node_parser import SentenceSplitter
from llama_index.core.ingestion import IngestionPipeline
from llama_index.core.schema import TransformComponent
class TextCleaner(TransformComponent):
def call(self, nodes, **kwargs):
for node in nodes:
node.text = re.sub(r”[^0-9A-Za-z ]”, “”, node.text)
return nodes
use in a pipeline
pipeline = IngestionPipeline(
transformations=[
SentenceSplitter(chunk_size=25, chunk_overlap=0),
TextCleaner(),
OpenAIEmbedding(),
],
)
nodes = pipeline.run(documents=[Document.example()])
{% endhighlight %}
pipeline(W. document, node, index)
{% highlight python %}
from llama_index.core import VectorStoreIndex
from llama_index.core.extractors import (
TitleExtractor,
QuestionsAnsweredExtractor,
)
from llama_index.core.ingestion import IngestionPipeline
from llama_index.core.node_parser import TokenTextSplitter
transformations = [
TokenTextSplitter(chunk_size=512, chunk_overlap=128),
TitleExtractor(nodes=5),
QuestionsAnsweredExtractor(questions=3),
]
global
from llama_index.core import Settings
Settings.transformations = [text_splitter, title_extractor, qa_extractor]
per-index
index = VectorStoreIndex.from_documents(
documents, transformations=transformations
)
{% endhighlight %}
AI
/
NLP
/
llama index
· 2024-03-14
-
Llamaindex embedding
what is embedding
embedding은 입력을 받은 document or node에 있어서 vector로 나타내는것입니다. 이를 통하여 코사인 유사도와 같이 문서들간의 유사성을 계산하여 문서를 효율적으로 사용할 수 있게 됩니다. llama는 기본적으로 코사인 유사도를 사용하고 있으며 아래의 방식으로 다양한 embedding을 사용해 볼 수 있습니다.
W. OpenAI
OpenAI에서 사용하는 embedding을 사용하려면 아래와 같이 사용하면 됩니다. 하지만 유료인점을 참고해야합니다.
{% highlight shell %}
pip install llama-index-embeddings-openai
{% endhighlight %}
{% highlight python %}
import os
OPENAI_API_TOKEN = “sk-“
os.environ[“OPENAI_API_KEY”] = OPENAI_API_TOKEN
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.core import Settings
global
Settings.embed_model = OpenAIEmbedding(embed_batch_size=42) # default is 10
per-index
index = VectorStoreIndex.from_documents(documents, embed_model=embed_model)
{% endhighlight %}
W. hugging face
hugging face를 사용하여 enbedding을 하는 방식은 아래와 같습니다.
{% highlight shell %}
pip install llama-index-embeddings-huggingface
{% endhighlight %}
{% highlight python %}
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.core import Settings
Settings.embed_model = HuggingFaceEmbedding(
model_name=”BAAI/bge-small-en-v1.5”
)
{% endhighlight %}
W. hugging face(W. ONNX)
hugging face를 ONNX로 사용하는 법은 아래와 같습니다.
{% highlight shell %}
pip install transformers optimum[exporters]
pip install llama-index-embeddings-huggingface-optimum
{% endhighlight %}
{% highlight python %}
from llama_index.embeddings.huggingface_optimum import OptimumEmbedding
OptimumEmbedding.create_and_save_optimum_model(
“BAAI/bge-small-en-v1.5”, “./bge_onnx”
)
Settings.embed_model = OptimumEmbedding(folder_name=”./bge_onnx”)
{% endhighlight %}
W. langchain
langchain에서 지원하는 다양한 embedding을 사용할 수 있습니다.
langchain embeddings list
{% highlight shell %}
pip install llama-index-embeddings-langchain
{% endhighlight %}
{% highlight python %}
from langchain.embeddings.huggingface import HuggingFaceBgeEmbeddings
from llama_index.core import Settings
Settings.embed_model = HuggingFaceBgeEmbeddings(model_name=”BAAI/bge-base-en”)
{% endhighlight %}
W. custom embedding
위에서 사용할 수 있는 다양한 embedding 이외에 다른 embedding을 직접 만들어서 활용하려면 아래와 같이 해볼 수 있습니다.
{% highlight python %}
from typing import Any, List
from InstructorEmbedding import INSTRUCTOR
from llama_index.core.embeddings import BaseEmbedding
class InstructorEmbeddings(BaseEmbedding):
def init(
self,
instructor_model_name: str = “hkunlp/instructor-large”,
instruction: str = “Represent the Computer Science documentation or question:”,
kwargs: Any,
) -> None:
self._model = INSTRUCTOR(instructor_model_name)
self._instruction = instruction
super().__init__(kwargs)
def _get_query_embedding(self, query: str) -> List[float]:
embeddings = self._model.encode([[self._instruction, query]])
return embeddings[0]
def _get_text_embedding(self, text: str) -> List[float]:
embeddings = self._model.encode([[self._instruction, text]])
return embeddings[0]
def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]:
embeddings = self._model.encode(
[[self._instruction, text] for text in texts]
)
return embeddings
async def _get_query_embedding(self, query: str) -> List[float]:
return self._get_query_embedding(query)
async def _get_text_embedding(self, text: str) -> List[float]:
return self._get_text_embedding(text) {% endhighlight %}
other embeddings
이외에도 다양한 embedding을 사용할 수 있으며 아래는 지원하는 embedding list 입니다.
embeddings list
AI
/
NLP
/
llama index
· 2024-03-13
-
Llamaindex index
what is index
index는 RAG와 같이 검색을 하는 구조에서 빠르게 검색하기 위한 구조입니다. 추가적인 활용처로는 채팅봇과 같이 QA로 사용할 수 있습니다.
vector store index
index 기법에서 가장 흔하게 사용이 되는 방법입니다. 이는 vector store를 활용하여 indexing을 하는 방법입니다.
아래와 같이 document을 바로 활용하는 방법과 node를 활용하는 방법 2가지로 이루어져 있습니다.
{% highlight python %}
from llama_index.core import VectorStoreIndex
index = VectorStoreIndex.from_documents(documents)
{% endhighlight %}
{% highlight python %}
from llama_index.core.schema import TextNode
node1 = TextNode(text=”", id_="")
node2 = TextNode(text="", id_="")
nodes = [node1, node2]
index = VectorStoreIndex(nodes)
{% endhighlight %}
default vectorstore이외에도 다양한 custom vectorstore를 사용할 수 있으며 아래는 간단한 예시를 나타냅니다.
{% highlight python %}
import pinecone
from llama_index.core import (
VectorStoreIndex,
SimpleDirectoryReader,
StorageContext,
)
from llama_index.vector_stores.pinecone import PineconeVectorStore
init pinecone
pinecone.init(api_key=”", environment="")
pinecone.create_index(
"quickstart", dimension=1536, metric="euclidean", pod_type="p1"
)
construct vector store and customize storage context
storage_context = StorageContext.from_defaults(
vector_store=PineconeVectorStore(pinecone.Index(“quickstart”))
)
Load documents and build index
documents = SimpleDirectoryReader(
“../../examples/data/paul_graham”
).load_data()
index = VectorStoreIndex.from_documents(
documents, storage_context=storage_context
)
{% endhighlight %}
other index guides
vector store가 가장 흔한 indexing 기법이지만 그 이외에도 아래와 같이 다양한 기법들이 있습니다.
other index guides
W. other embedding module
기본적으로 llama에서 제공하는 embedding으로 동작이 되지만 다른 embedding을 사용하고 싶으면 아래를 참고하여 변경이 가능합니다.
embedding module
pipeline
documents advance(1)와 nodes advance(1)까지 확인 이후 pipeline을 아래와 같이 도입 가능합니다.
document node index pipeline
AI
/
NLP
/
llama index
· 2024-03-12
-
Llamaindex nodes Advance(1)
create node by async
node를 만들때 다음과 같이 비동기로 만들 수 있습니다.
{% highlight python %}
from llama_index.core.node_parser import SentenceSplitter
node_parser = SentenceSplitter(chunk_size=512)
nodes = await node_parser.acall(documents)
{% endhighlight %}
file base node parser
노드를 생성하는데 있어서 document들이 다양한 형태의 데이터를 가질 수 있으며, 각 데이터에 최적화된 node parser를 사용하는것이 성능에 영향을 미칠 수 있습니다.
simple file
가장 기본적인 형태의 txt와 같은 파일에 적절한 파서입니다. 이는 flat document 와 같이 활용하기에 적합합니다.
{% highlight python %}
from llama_index.core.node_parser import SimpleFileNodeParser
parser = SimpleFileNodeParser()
md_nodes = parser.get_nodes_from_documents(md_docs)
{% endhighlight %}
html file
HTML 파일을 사용하는데 최적화된 파서입니다. tag들을 기본적으로 제공하며 custom tag를 세팅할 수 있습니다.
{% highlight python %}
from llama_index.core.node_parser import HTMLNodeParser
parser = HTMLNodeParser(tags=[“p”, “h1”]) # optional list of tags
nodes = parser.get_nodes_from_documents(html_docs)
{% endhighlight %}
json file
JSON 파일을 사용하는데 최적화된 파서입니다.
{% highlight python %}
from llama_index.core.node_parser import JSONNodeParser
parser = JSONNodeParser()
nodes = parser.get_nodes_from_documents(json_docs)
{% endhighlight %}
markdown file
markdown 파일을 사용하는데 최적화된 파서입니다.
{% highlight python %}
from llama_index.core.node_parser import MarkdownNodeParser
parser = MarkdownNodeParser()
nodes = parser.get_nodes_from_documents(markdown_docs)
{% endhighlight %}
text base node parser
노드를 생성하는데 있어서 text를 기반으로 생성이 필요한 경우 아래의 방식을 사용할 수 있습니다.
code splitter
code 파일을 사용하는데 최적화된 파서입니다. 지원되는 code 목록은 다음과 같습니다.
available code file
{% highlight python %}
from llama_index.core.node_parser import CodeSplitter
splitter = CodeSplitter(
language=”python”,
chunk_lines=40, # lines per chunk
chunk_lines_overlap=15, # lines overlap between chunks
max_chars=1500, # max chars per chunk
)
nodes = splitter.get_nodes_from_documents(documents)
{% endhighlight %}
langchain splitter
langchain에서 사용하는 textsplitter를 사용할 수 있는 파서입니다.
{% highlight python %}
from langchain.text_splitter import RecursiveCharacterTextSplitter
from llama_index.core.node_parser import LangchainNodeParser
parser = LangchainNodeParser(RecursiveCharacterTextSplitter())
nodes = parser.get_nodes_from_documents(documents)
{% endhighlight %}
지원하지 않는 langchain parser의 경우 아래와 같이 생성하여 사용할 수 있습니다.
create langchain parser
sentence splitter
문장과 문장의 끊어짐을 보장하며 분할을 할 수 있는 파서입니다.
{% highlight python %}
from llama_index.core.node_parser import SentenceSplitter
splitter = SentenceSplitter(
chunk_size=1024,
chunk_overlap=20,
)
nodes = splitter.get_nodes_from_documents(documents)
{% endhighlight %}
sentence window splitter
sentence splitter와 유사하지만 해당 노드 주변의 window_size만큼의 값을 가지게 됩니다. 이것은 다음 예시와 같이 활용이 가능합니다. MetadataReplacementNodePostProcessor
{% highlight python %}
import nltk
from llama_index.core.node_parser import SentenceWindowNodeParser
node_parser = SentenceWindowNodeParser.from_defaults(
# how many sentences on either side to capture
window_size=3,
# the metadata key that holds the window of surrounding sentences
window_metadata_key=”window”,
# the metadata key that holds the original sentence
original_text_metadata_key=”original_sentence”,
)
{% endhighlight %}
semantic splitter
고정된 크기의 chunk로 node가 구성이 되지만, embedding을 활용하여 유사성을 고려한 방식으로 효과적인 방식입니다.
{% highlight python %}
from llama_index.core.node_parser import SemanticSplitterNodeParser
from llama_index.embeddings.openai import OpenAIEmbedding
embed_model = OpenAIEmbedding()
splitter = SemanticSplitterNodeParser(
buffer_size=1, breakpoint_percentile_threshold=95, embed_model=embed_model
)
{% endhighlight %}
token splitter
token 크기에 기반하여 chunking을 하는 방식입니다.
{% highlight python %}
from llama_index.core.node_parser import TokenTextSplitter
splitter = TokenTextSplitter(
chunk_size=1024,
chunk_overlap=20,
separator=” “,
)
nodes = splitter.get_nodes_from_documents(documents)
{% endhighlight %}
relation base node parser
노드를 생성하는데 있어서 관계성을 기반으로 생성이 필요한 경우 아래의 방식을 사용할 수 있습니다.
hierarchical splitter
계층 구조로 chunking을 진행하여, 하위 레벨의 node는 상위 레벨의 node와 같이 활용 되어 좋은 결과를 도출할 수 있습니다. 다음의 예시와 같이 활용하면 적절합니다. AutoMergingRetriever
{% highlight python %}
from llama_index.core.node_parser import HierarchicalNodeParser
node_parser = HierarchicalNodeParser.from_defaults(
chunk_sizes=[2048, 512, 128]
)
{% endhighlight %}
pipeline
documents advance(1)까지 확인 이후 pipeline을 아래와 같이 도입 가능합니다.
document node pipeline
AI
/
NLP
/
llama index
· 2024-03-11
-
-
Llamaindex documents Advance(1)
documents loaders
flat document
documents는 다양한 형태를 가진 파일들을 불러오는데 사용이 될 수 있으나, 단순한 파일을 불러올 수도 있습니다. 단순한 파일을 불러올때는 아래와 같이 단순한 방식이 제공됩니다.
{% highlight python %}
from llama_index.readers.file import FlatReader
from pathlib import Path
md_docs = FlatReader().load_data(Path(“./test.md”))
{% endhighlight %}
other document loader
other document loader
metadata extraction usage pattern
다음과 같이 LLM을 사용하여 metadata를 추출해낼 수 있습니다.
{% highlight shell %}
pip install llama-index-extractors-entity
{% endhighlight %}
{% highlight python %}
import os
OPENAI_API_TOKEN = “sk-“
os.environ[“OPENAI_API_KEY”] = OPENAI_API_TOKEN
llm = OpenAI(temperature=0.1, model=”gpt-3.5-turbo”, max_tokens=512)
from llama_index.core.extractors import (
TitleExtractor,
QuestionsAnsweredExtractor,
SummaryExtractor,
KeywordExtractor,
BaseExtractor,
)
from llama_index.extractors.entity import EntityExtractor
class CustomExtractor(BaseExtractor):
def extract(self, nodes):
metadata_list = [
{
“custom”: (
node.metadata[“document_title”]
+ “\n”
+ node.metadata[“excerpt_keywords”]
)
}
for node in nodes
]
return metadata_list
title_extractor = TitleExtractor(nodes=5)
qa_extractor = QuestionsAnsweredExtractor(questions=3)
summary_extractor = SummaryExtractor(summaries=[“prev”, “self”,”next”])
keyword_extractor = KeywordExtractor(keywords=10, llm=llm),
custom_extractor = CustomExtractor()
entity_extractor = EntityExtractor(
prediction_threshold=0.5,
label_entities=False, # include the entity label in the metadata (can be erroneous)
device=”cpu”, # set to “cuda” if you have a GPU
)
{% endhighlight %}
pipeline
nodes advance(1)까지 확인 이후 pipeline을 아래와 같이 도입 가능합니다.
document node pipeline
AI
/
NLP
/
llama index
· 2024-03-07
-
Llamaindex documents
what is documents
documents는 다양한 NLP process에서 사용할 문서를 불러오는 방식을 말합니다.
How to use documents tutorial
documents를 사용하는데 있어서 가장 기초적인 예시는 아래와 같습니다.
{% highlight python %}
from llama_index.core import Document, VectorStoreIndex
document = Document.example()
build index
index = VectorStoreIndex.from_documents(documents)
{% endhighlight %}
read documents
documents를 사용하는방법은 다양하게 존재합니다. 다음은 documents를 만드는 두가지 방법을 나타냅니다.
Directory Reader
다음의 방식은 directory에 있는 문서들을 읽는 방식입니다. 해당방식은 지정한 폴더에 있는 문서는 읽을 수 있으나 하위 폴더에 있는 문서를 읽을 수는 없습니다.
{% highlight python %}
from llama_index.core import SimpleDirectoryReader
documents = SimpleDirectoryReader(“./data”).load_data()
{% endhighlight %}
custom setting
다음의 방식은 사용자가 직접 지정한 문서들을 입력하는 방식입니다. 이는 text를 하나씩 지정해야하는 방식입니다.
{% highlight python %}
from llama_index.core import Document
text_list = [text1, text2, …]
documents = [Document(text=t) for t in text_list]
{% endhighlight %}
documents metadata
문서들은 다양한 metadata를 가지게 됩니다. 해당하는 metadata는 NLP process에서 중요한 역활을 하게 되며 해당하는 값들을 상세히 지정하는것은 중요합니다.
add metadata(pre read)
document constructor를 만들기 이전에 metadata를 지정하는 방식은 다음과 같습니다.
W. dir reader
다음과 같이 dir reader를 사용하면서 metadata들을 지정 할 수 있습니다.
{% highlight python %}
from llama_index.core import SimpleDirectoryReader
filename_fn = lambda filename: {“file_name”: filename}
automatically sets the metadata of each document according to filename_fn
documents = SimpleDirectoryReader(
“./data”,
file_metadata=filename_fn,
filename_as_id=True,
).load_data()
{% endhighlight %}
W. custom reader
다음과 같이 custom reader를 사용하면서 metadata들을 지정 할 수 있습니다.
{% highlight python %}
document = Document(
text=”text”,
metadata={
“filename”: “",
"category": "",
"doc_id": ""},
)
{% endhighlight %}
add metadata(after read)
document constructor를 만든 이후에 잘못된 metadata를 변경하는 방식은 다음과 같습니다.
{% highlight python %}
document.metadata = {“filename”: “"}
document.doc_id = "My new document id!"
{% endhighlight %}
advance metadata setting
다양한 metadata는 NLP process에 다양한 강점을 가질 수 있지만, 오히려 과한 정보로 혼란을 줄 수 있습니다. 이럴 경우 필요없는 정보를 배제할 수 있습니다.
다음은 LLM이 metadata를 활용하는지 설정하는것입니다.
{% highlight python %}
document.excluded_llm_metadata_keys = [“file_name”]
{% endhighlight %}
다음은 embedding 과정에서 metadata를 활용하는지 설정하는것입니다.
{% highlight python %}
document.excluded_embed_metadata_keys = [“file_name”]
{% endhighlight %}
다음은 위에서 설정한 metadata 배제를 한 이외의 값이 어떻게 보여지는지 확인하는 방법입니다.
{% highlight python %}
from llama_index.core.schema import MetadataMode
print(document.get_content(metadata_mode=MetadataMode.LLM))
print(document.get_content(metadata_mode=MetadataMode.EMBED))
{% endhighlight %}
이외에도 metadata의 format을 설정 가능합니다. 다음 예시에서는 format을 사용한 전체적인 사용법을 나타냅니다.
advance metadata setting example
{% highlight python %}
from llama_index.core import Document
from llama_index.core.schema import MetadataMode
document = Document(
text=”This is a super-customized document”,
metadata={
“file_name”: “super_secret_document.txt”,
“category”: “finance”,
“author”: “LlamaIndex”,
},
excluded_llm_metadata_keys=[“file_name”],
metadata_seperator=”::”,
metadata_template=”{key}=>{value}”,
text_template=”Metadata: {metadata_str}\n—–\nContent: {content}”,
)
print(
“The LLM sees this: \n”,
document.get_content(metadata_mode=MetadataMode.LLM),
)
print(
“The Embedding model sees this: \n”,
document.get_content(metadata_mode=MetadataMode.EMBED),
)
{% endhighlight %}
Advance
documents advance(1)
AI
/
NLP
/
llama index
· 2024-03-06
-
Llamaindex intro
How to start
라마 인덱스를 활용하는 방법은 3가지가 있습니다. 첫번째는 initial setting, 두번째는 custom setting, 세번째는 source에서 직접 설치하는 방법입니다.
init install
기초적인 설치방법으로 OpenAI와 같이 대표적인 LLM을 활용하는데 있어서 적절합니다.
{% highlight shell %}
pip install llama-index
{% endhighlight %}
custom install
개별적 모델을 활용하기 위한 설치방법으로 OpenAI와 같이 대표적인 LLM 이외에도 다양한 모델을 Ollama 또는 huggingface등에서 가져와서 활용이 가능합니다.
{% highlight shell %}
pip install llama-index-core llama-index-readers-file llama-index-llms-ollama llama-index-embeddings-huggingface
{% endhighlight %}
source install
위 두가지 설치가 작동이 되지 않거나, source에서 직접 원하는것들만 설치를 하고 싶을때 사용할 수 있습니다.
{% highlight shell %}
git clone https://github.com/jerryjliu/llama_index.git
pip install -e llama-index-integrations/llms/llama-index-llms-ollama
{% endhighlight %}
simple start example
아래의 예시는 RAG를 활용한 예시입니다. ./data/paul_graham/ 폴더를 생성하여 RAG에 사용할 txt 데이터를 넣으면 됩니다. 또는 아래의 코드를 통하여 공식적인 예시 데이터를 사용할 수 있습니다.
{% highlight shell %}
mkdir -p ‘data/paul_graham/’
wget ‘https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt’ -O ‘data/paul_graham/paul_graham_essay.txt’
{% endhighlight %}
W. OpenAI
OpenAI를 사용하여 활용을 하려면 우선 아래와 같이 환경설정이 필요합니다.
{% highlight shell %}
export OPENAI_API_KEY=XXXXX # linux
set OPENAI_API_KEY=XXXXX # window
{% endhighlight %}
이후 아래의 코드로 간단하게 활용이 가능합니다.
{% highlight python %}
import os
from llama_index.core import (
VectorStoreIndex,
SimpleDirectoryReader,
StorageContext,
load_index_from_storage,
)
check if local storage already exists
PERSIST_DIR = “./storage”
if not os.path.exists(PERSIST_DIR):
# load the documents and create the index
documents = SimpleDirectoryReader(“./data/paul_graham/”).load_data()
index = VectorStoreIndex.from_documents(documents)
# store it for later
index.storage_context.persist(persist_dir=PERSIST_DIR)
else:
# load the existing index
storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
index = load_index_from_storage(storage_context)
Either way we can now query the index
query_engine = index.as_query_engine()
response = query_engine.query(“{Question}”)
print(response)
{% endhighlight %}
W. Custom model(ollama)
ollama를 사용하기 위하여 기본 설치 및 사용법을 알아야합니다. 사용법은 아래를 참고하면 됩니다.
how to use ollama
ollama 사용법 숙지 이후 사용할 모델을 다운 받고 아래의 코드로 진행이 가능합니다.
{% highlight python %}
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings
from llama_index.core.embeddings import resolve_embed_model
from llama_index.llms.ollama import Ollama
documents = SimpleDirectoryReader(“./data/paul_graham/”).load_data()
bge embedding model
Settings.embed_model = resolve_embed_model(“local:BAAI/bge-small-en-v1.5”)
ollama
Settings.llm = Ollama(model=, request_timeout=30.0)
index = VectorStoreIndex.from_documents(
documents,
)
query_engine = index.as_query_engine()
response = query_engine.query(“{Question}”)
print(response)
{% endhighlight %}
W. Custom model(hugging face)
hugging face를 사용하기 위하여 기본 설치 및 사용법을 알아야합니다. 사용법은 아래를 참고하면 됩니다.
how to use hugging face
hugging face 사용법 숙지 이후 추가적으로 아래의 필요 모듈을 다운받아야 합니다.
{% highlight shell %}
pip install llama-index-llms-huggingface
pip install llama-index
{% endhighlight %}
이후 아래의 코드로 실행해 볼 수 있습니다.
{% highlight python %}
setup prompts - specific to StableLM
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings, PromptTemplate
from llama_index.llms.huggingface import HuggingFaceLLM
import torch
load documents
documents = SimpleDirectoryReader(“./data/paul_graham/”).load_data()
This will wrap the default prompts that are internal to llama-index
taken from https://huggingface.co/Writer/camel-5b-hf
query_wrapper_prompt = PromptTemplate(
“Below is an instruction that describes a task. “
“Write a response that appropriately completes the request.\n\n”
“### Instruction:\n{query_str}\n\n### Response:”
)
llm = HuggingFaceLLM(
context_window=2048,
max_new_tokens=256,
generate_kwargs={“temperature”: 0.25, “do_sample”: False},
query_wrapper_prompt=query_wrapper_prompt,
tokenizer_name=”Writer/camel-5b-hf”,
model_name=”Writer/camel-5b-hf”,
device_map=”auto”,
tokenizer_kwargs={“max_length”: 2048},
# uncomment this if using CUDA to reduce memory usage
# model_kwargs={“torch_dtype”: torch.float16}
)
Settings.chunk_size = 512
Settings.llm = llm
index = VectorStoreIndex.from_documents(documents)
set Logging to DEBUG for more detailed outputs
query_engine = index.as_query_engine()
response = query_engine.query(“What did the author do growing up?”)
print(response)
{% endhighlight %}
streaming service
스트리밍 서비스로 작동을 하기 위하여 index.as_query_engine()에서 부터 아래와 같이 변경을 해주면 됩니다.
{% highlight python %}
query_engine = index.as_query_engine(streaming=True)
set Logging to DEBUG for more detailed outputs
response_stream = query_engine.query(“What did the author do growing up?”)
can be slower to start streaming since llama-index often involves many LLM calls
response_stream.print_response_stream()
can also get a normal response object
response = response_stream.get_response()
print(response)
{% endhighlight %}
AI
/
NLP
/
llama index
· 2024-03-05
-
-
-
-
-
-
-
3. Evaluation metrics of deep learning
mean_absolute_error(regression)
mse라고 불리는 지표로 결과값과 예측값간의 차의 절대값 평균이다.
{% highlight python %}
from sklearn.metrics import mean_absolute_error
mean_absolute_error(Y_test, pred_value)
{% endhighlight %}
mean_squared_error(regression)
mse라고 불리는 지표로 가장 일반적으로 사용되는 값으로 결과값과 예측값간의 차의 제곱합의 절대값이다.
{% highlight python %}
from sklearn.metrics import mean_squared_error
mean_squared_error(Y_test, pred_value)
{% endhighlight %}
accuracy_score(classification)
결과와 예측간의 정확도를 나타내는 지표이다.
{% highlight python %}
from sklearn.metrics import accuracy_score
accuracy_score(Y_test, pred_value)
{% endhighlight %}
confusion_matrix(classification)
예측값과 결과값간의 값을 matrix로 나타낸값
{% highlight python %}
from sklearn.metrics import confusion_matrix
confusion_matrix(Y_test, pred_value)
{% endhighlight %}
classification_report(classification)
{% highlight python %}
from sklearn.metrics import classification_report
classification_report(Y_test, pred_value)
{% endhighlight %}
precision -> 예측1(positive, type1) 정확도
recall -> 실제1(Type2) 정확도
F-1 Score precision, recall의 유사성 높으면 유사함(기하 평균)
roc_auc_score(classification)
{% highlight python %}
from sklearn.metrics import roc_auc_score
roc_auc_score(Y_test, pred_value, multi_class)
{% endhighlight %}
roc x축을 실제값이 1일때 예측값의 1의 비율, y축을 실제값이 0일때 예측값의 1의 비율로 하여 나타내지는 그래프를 의미한다.
auc -> roc그래프에서 desity를 나타내고, 0.5~1의 값을 나타내며 높을수록 정확도가 높다
multi_class는 1대1 매칭은 ovo 1대 다 매칭은 ovr로 입력값을 받는다.
silhouette_score(clustering)
{% highlight python %}
from sklearn.metrics import silhouette_score
for i in range():
model = KMeans(n_cluster=i)
model.fit()
pred = model.predict()
[].append(silhouette_score(, pred))
{% endhighlight %}
값이 높을 수록 효과가 좋은 결과
AI
/
DL
/
basic
· 2023-11-01
-
-
-
-
4. Models of machine learning
supervised Learning
LinearRegression
선형적인 모델로 예측이 될때 사용
{% highlight python %}
from sklearn.linear_model import LinearRegression
{% endhighlight %}
LogisticRegression
0과1 처럼 나뉘어지는 형태 또는 0~1로 나뉘어지는 모델
{% highlight python %}
from sklearn.linear_model import LogisticRegression
{% endhighlight %}
DecisionTreeRegressor
tree 형태로 구분이 되며 feature들에 따라 결과를 다각형의 직선으로 표현하는 형태이다
분류된 값의 평균
{% highlight python %}
from sklearn.tree import DecisionTreeRegressor
from sklearn.tree import export_graphviz
from graphviz import Source
model = DecisionTreeRegressor(random_state=100, min_samples_leaf=1, min_samples_split=5, max_depth=5)
export_graphviz(model, out_file=/.)
Source.from_file(/.)
{% endhighlight %}
random_state 시드값
max_depth 최대 깊이
min_samples_leaf 리프 원소의 최소갯수
min_samples_split root 원소의 최소갯수
export_graphviz tree를 그림으로 저장
Source.from_file tree를 저장된 그림 가시화
feature_importances_ 모든 decision tree가 가지는 특성
RandomForestClassifier
다수의 트리들을 랜덤하게 학습하는 방법으로 과적합을 방지하기 위해 탄생하였으나 비교적 느리다. feature들에 따라 결과를 구역으로 나뉘는 형태이다.
복원 추출하는것을 bootstrap이라하며 복원추출로 subset을만들어 모델을 만드는것을 bagging이라고 함.
subset을 만들기 때문에 특정 feature의 과적합을 조절할 수 있다.
트리들이 각각 독립적이다.
GINI index(default)
$1-\sum_{i=1}^n(p_i)^2$로 노드의 순도를 알 수있고 최하 0.5에서 최고 0까지 나타남
cross entropy
$-\sum_{i=1}^n(p_i)^2*\log_2(p_i)$로 노드의 순도를 알 수있고 최하 1에서 최고 0까지 나타남
{% highlight python %}
from sklearn.ensemble import RandomForestClassifier
{% endhighlight %}
XGBoost
boosting은 각트리가 이전 트리의 결과를 참조하는것.
gradient descent(경사하강법)
위의 기법들을 활용을 하며 level wise한 방법
LightGBM
boosting은 각트리가 이전 트리의 결과를 참조하는것.
gradient descent(경사하강법)
위의 기법들을 활용을 하며 leaf wise한 방법
{% highlight python %}
from lightgbm import LGBMClassifier
{% endhighlight %}
unsupervised Learning
KMeans
cluster형태의 문제에서 포인트를 지정 후 근처값을 찾고 중심이동을 반복해 최종값을 구하게된다.(거리 기반 측정법)
{% highlight python %}
from sklearn.cluster import KMeans
model = KMeans(n_clusters = )
model.fit(X)
model.inertia_
{% endhighlight %}
inertia_
얼마나 밀집해있는지 알 수 있음(n의 갯수가 높으면 낮아지는 문제도 있음)
survival analysis
KaplanMelerFitter(survival analysis)
구독시간과 이탈률만을 가지고 평가하는 기본형
{% highlight python %}
from lifelines import KaplanMelerFitter
model = KaplanMelerFitter()
model.fit(, )
model.survival_function_
model.event_table
{% endhighlight %}
survival_function_는 시간에 따른 이탈치
event_table
removed 이탈량
observed 데이터 내의 이탈량
censored 데이터 이후 이탈 예상량
entrance 유입량
at_risk 잔류량
CoxPH(survival analysis)
모든 데이터를 이용해서 평가하는 복합형으로 logistic regression에서 차용되었다.
{% highlight python %}
from lifelines import CoxPHFitter
model = CoxPHFitter()
model.fit(, , )
model.baseline_survival_
model.print_summary()
model.plot_partial_effects_on_outcome(covariates= , values= [0,1,...])
model.predict_survival_function()
{% endhighlight %}
baseline_survival_는 시간에 따른 이탈치
print_summary
coef의 값과 exp(coef)등등의 값을 알 수 있으며 exp(coef)이 1에서 차이나는 만큼이 이탈률의 변화량에 미치는 비율을 말한다.
plot_partial_effects_on_outcome
<column_name>이 value일때 미친 영향 그래프
predict_survival_function
추가적인 데이터의 예측값
AI
/
ML
/
basic
· 2023-10-26
-
3. Evaluation metrics of machine learning
mean_absolute_error(regression)
mse라고 불리는 지표로 결과값과 예측값간의 차의 절대값 평균이다.
{% highlight python %}
from sklearn.metrics import mean_absolute_error
mean_absolute_error(Y_test, pred_value)
{% endhighlight %}
mean_squared_error(regression)
mse라고 불리는 지표로 가장 일반적으로 사용되는 값으로 결과값과 예측값간의 차의 제곱합의 절대값이다.
{% highlight python %}
from sklearn.metrics import mean_squared_error
mean_squared_error(Y_test, pred_value)
{% endhighlight %}
accuracy_score(classification)
결과와 예측간의 정확도를 나타내는 지표이다.
{% highlight python %}
from sklearn.metrics import accuracy_score
accuracy_score(Y_test, pred_value)
{% endhighlight %}
confusion_matrix(classification)
예측값과 결과값간의 값을 matrix로 나타낸값
{% highlight python %}
from sklearn.metrics import confusion_matrix
confusion_matrix(Y_test, pred_value)
{% endhighlight %}
classification_report(classification)
{% highlight python %}
from sklearn.metrics import classification_report
classification_report(Y_test, pred_value)
{% endhighlight %}
precision -> 예측1(positive, type1) 정확도
recall -> 실제1(Type2) 정확도
F-1 Score precision, recall의 유사성 높으면 유사함(기하 평균)
roc_auc_score(classification)
{% highlight python %}
from sklearn.metrics import roc_auc_score
roc_auc_score(Y_test, pred_value, multi_class)
{% endhighlight %}
roc x축을 실제값이 0일때 예측값의 1의 비율(FPR), y축을 실제값이 1일때 예측값의 1의 비율(TPR)로 하여 나타내지는 그래프를 의미한다.
auc -> roc그래프에서 desity를 나타내고, 0.5~1의 값을 나타내며 높을수록 정확도가 높다
multi_class는 1대1 매칭은 ovo 1대 다 매칭은 ovr로 입력값을 받는다.
silhouette_score(clustering)
{% highlight python %}
from sklearn.metrics import silhouette_score
for i in range():
model = KMeans(n_cluster=i)
model.fit()
pred = model.predict()
[].append(silhouette_score(, pred))
{% endhighlight %}
값이 높을 수록 효과가 좋은 결과
AI
/
ML
/
basic
· 2023-10-25
-
2. EDA of machine learning
ordinal encoder
어떠한 컬럼값이 object형일 경우 학습을 시키기 힘들기 때문에 값들을 0, 1, … 으로 넘버링하는 방법(높고 낮음의 연관성이 있을때)
replace()
{% highlight python %}
data[] = data[].replace({"name": num})
{% endhighlight %}
OrdinalEncoder
{% highlight python %}
from sklearn.preprocessing import OrdinalEncoder
ohe = OrdinalEncoder()
train_ = ohe.fit_transform(train([])) # 분류된 데이터가 도출됨
{% endhighlight %}
factorize
{% highlight python %}
pd.factorize()
{% endhighlight %}
onehot encoder
어떠한 컬럼값이 object형일 경우 학습을 시키기 힘들기 때문에 값들을 0과 1로 이루어진 데이터로 변환하는 방법
train, test 카테고리 차이가 없을때 쉽게하는법
{% highlight python %}
pd.get_dummies(data=[], columns=[], drop_first=False)
{% endhighlight %}
data는 참조가 되는 데이터들을 나타낸다.
columns는 데이터중 onehotencoding을 하려는 컬럼값들을 나타낸다.
drop_first는 encoding하여 분할되는 컬럼들중 첫번째를 넣을지 뺄것인지 정하는것으로 선택적이다.
train, test 카테고리 차이가 있을때 진행하는법
{% highlight python %}
from sklearn.preprocessing import OneHotEncoder
ohe = OneHotEncoder(sparse=False)
train_ = ohe.fit_transform(train([])) # 분류된 데이터가 도출됨
ohe.categories_ # 카테고리 값이 도출됨
{% endhighlight %}
StandardScaler
평균이 0 분산이 1인 값으로 데이터를 표준화하는 작업으로 보통 정규분포의 경우에서 성능향상을 위해 사용이 된다.(outlier 영향 강함)
{% highlight python %}
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
df_scaled = scaler.fit_transform(df)
{% endhighlight %}
min max scaler
데이터를 0~1의 값으로 변환을 하게 되며 정규분포가 아닐경우 사용하게 된다.
{% highlight python %}
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
df_scaled = scaler.fit_transform(df)
{% endhighlight %}
robust scaler
해당하는 값에서 중앙값을뺀값을 IQR로 나누어 만들어지며, ourlier 영향이 적게 스케일링이 가능하다.
{% highlight python %}
from sklearn.preprocessing import RobustScaler
{% endhighlight %}
train/test data split
데이터가 학습및 학습결과 확인을 위하여 데이터를 분할해주는 작업이다.
train_test_split
{% highlight python %}
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X ,y, test_size=0.2, random_state=54)
{% endhighlight %}
random_state는 일종의 시드값으로 변화가없으면 계속 같은 값이 나온다.
StratifiedShuffleSplit
특정 <data_>를 동일한 비율로 나누고 싶을때 사용
{% highlight python %}
split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=54)
for train_idx, test_idx in split.split(X, ):
X_train = X[train_idx]
X_test = X[test_idx]
y_train = y[train_idx]
y_test = y[test_idx] {% endhighlight %}
random_state는 일종의 시드값으로 변화가없으면 계속 같은 값이 나온다.
Kfold
StratifiedKfold
cross validation issue
train/test로 나누어서 진행함에 있어서 보면 매번 결과가 뒤죽박죽으로 나올 수 있다. 이러한 이유는 train, test에 해당하는값이 치우쳐진 값으로 가질 수 있기 때문이며 이를 위해 아래와 같이 여러갯수로 분할하여 시행하는것이 더욱 정확하다고 볼 수있다.
{% highlight python %}
from sklearn.model_selection import KFold
kf = KFold(n_splits=5, random_state=100)
for train_index, test_index in kf.split(range(len(data))):
{% endhighlight %}
AI
/
ML
/
basic
· 2023-10-24
-
1. Theory of machine learning
Linear Regression
종속변수와 독립변수간에 관계를 예측하는 모델로 선형적 모델을 가지고 종속변수와 독립변수의 관계를 도출하는 방법이다. 변수가 증가함에 따라 시간 복잡도가 많이 증가한다. 일반적으로 아래의 정규방정식을 통하여 계산이 가능하지만
\[\theta = (X^TX)^{-1}X^Ty\]
역행렬이 존재하지 않거나 하는 경우 유사 역행렬인
\[\theta = X^+y\]
를 이용하여 계산을 하며 이는 sklearn에서 기본으로 제공이 된다.(np.linalg.pinv()를 통하여 직접 계산도 가능)
Ridge Regression(규제형)
학습 모델의 가중치를 컨트롤하기 위한 모델로 규제항을 포함하여 훈련하고 성능평가에서 사라진다.
$MSE(\theta)$에 L2 norm(규제항)을 추가된 모형으로 아래와 같은 loss function을 가진다.
\[J(\theta) = MSE(\theta) + \alpha \tfrac{1}{2}\sum_{i=1}^n\theta_i^2\]
Lasso Regression(규제형)
학습 모델의 가중치를 컨트롤하기 위한 모델로 규제항을 포함하여 훈련하고 성능평가에서 사라진다.Ridge회기는 중요도가 낮은 변수를 규제하지만 Lasso는 0이 될수있다.
$MSE(\theta)$에 L1 norm(규제항)을 추가된 모형으로 아래와 같은 loss function을 가진다.
\[J(\theta) = MSE(\theta) + \alpha \sum_{i=1}^n|\theta_i|\]
Elastic Net Regression(규제형)
학습 모델의 가중치를 컨트롤하기 위한 모델로 규제항을 포함하여 훈련하고 성능평가에서 사라진다.Ridge, Lasso를 융합시킨 형태이다.
$MSE(\theta)$에 L2 norm(규제항)을 추가된 모형으로 아래와 같은 loss function을 가진다.(r=0에서 Ridge r=1에서 Lasso가 된다.)
\[J(\theta) = MSE(\theta) + r\alpha \sum_{i=1}^n|\theta_i| + \tfrac{1-r}{2}\sum_{i=1}^n\theta_i^2\]
Early Stopping Regression(규제형)
경사하강법과 같은 반복적 학습에서 과적합되기전에 멈추게 하는 방법
Gradient Descent
비용함수를 최소화하여 계산복잡도를 감소시킨 방법이다. 시간 및 정확도를 위하여 scaler를 통하여 특성을 유사하게 만들어야한다. $\eta$는 학습률을 의미한다.
\[cost \, function := MSE(\theta) = \tfrac{(\hat{y}-y)^2}{m}\]
\[\tfrac{\partial}{\partial\theta}MSE(\theta) = \tfrac{2X^T(X\theta-y)}{m}\]
\[\theta^{next step} = \theta - \eta\tfrac{\partial}{\partial\theta}MSE(\theta)\]
Batch Gradient Descent
전체 데이터셋의 에러를 통한 기울기로 한번만 모델의 파라미터를 업데이트하는 방법
장점
연산횟수가 적다.
전체 데이터셋을 활용하기 때문에 안정적으로 수렴한다.
단점
지역 최적화에 걸리기 쉽다.
스텝마다 학습량이 많아 시간이 오래걸린다.
Stomatic Gradient Descent
매 스탭마다 무작위 샘플을 구하여 미분을 취하는 방법
장점
알고리즘이 빠르다.
단점
최적의 값을 구하기 힘들다.
샘플 데이터를 활용하기 때문에 불안정적으로 수렴한다.
Mini-Batch Gradient Descent
임의의 작은 샘플 세트를 활용하여 기울기를 구하는 방법
장점
batch-size를 키우면 SGD보다 안정적이다.
단점
정해진 샘플의 사용으로 SGD보다 지역 최적화에 걸리기 쉽다.
PolynomialFeatures
다항 회기방법으로 변수들을 이용해 고차항을 만드는 방법
n이 변수의 갯수, d가 차원일때 아래와 같은 수의 변수가 생성이된다.
\[\tfrac{(n+d)!}{n!d!}\]
Logistic Regression
종속변수와 독립변수간에 관계를 예측하는 모델로 linear regression과 다르게 이항, 다항과 같이 항을 기준으로 classification을 한다.
odds
성공확률과 실패 확률의 비율
\[odds = \tfrac{p(y=1|x)}{1-p(y=1|x)}\]
logit
odds에 log를 취한 함수
\[logit(p) = log(\tfrac{p}{1-p})\]
sigmoid function
logit 함수의 입력과 출력을 바꾼함수
\[p(X) = \tfrac{1}{1+e^{-\beta X}}\]
logistic function
sigmoid 함수 만들어진 예측 모델
Logistic Regression은 $x$가 변할때 $y$가 1이 되는 경향성을 따지는 모델로서 아래와 같은 확률에서 시작된다.
\[p(X) = Pr(y=1|X)\]
우리가 parameter Estimation을 통하여 구하려고 하는 sigmoid의 $\hat{\beta}$는 이상 적으로 2가지 경우로 나뉜다.
$y=1$이라서 $\hat{Pr(y=1|X)}$이 1에 수렴하는 경우
$y=0$이라서 $1-\hat{Pr(y=1|X)}$이 1에 수렴하는 경우
1.의 경우 최대 확률은 $\prod_{s \, in \, y_i=1} p(x_i)$
2.의 경우 최대 확률은 $\prod_{s \, in \, y_i=0} (1-p(x_i))$
종합적인 최대 확률은 $L(\beta) = \prod_{s \, in \, y_i=1} p(x_i) \times \prod_{s \, in \, y_i=0} (1-p(x_i))$ 가 된다.
이 수식을 단순화 하면 아래의 수식이 된다.
\[L(\beta) = \prod_s p(x_i)^{y_i} \times \prod_s (1-p(x_i))^{1-y_i}\]
loss function을 활용해 최적의 함수를 찾아야하는 위의 수식은 미분에 있어서 쉽지 않다. 그래서 log를 이용한 log likelihood 함수를 만들고 음수를 취해주고 전체 샘플수로 나눠주면 loss function을 만들 수 있다.
\[J(\beta) = -\tfrac{1}{n}(\sum_{i=1}^n y_i log(p(x_i)) \times \sum_{i=1}^n (1-y_i) log(1-p(x_i)))\]
\[\tfrac{\partial}{\partial\beta_j}J(\beta) = \tfrac{1}{n}(\sum_{i=1}^n p(x^{(i)})-y^{(i)})x_j^{(i)}\]
SoftMax
Logistic Regression의 경우 binary classification의 방법을 위하여 고안이 되었으나 multinomial classificaion에 활용할 수 있게 하는 방법이 SoftMax 기법이다.
이는 도출된 경향성 점수를 $s(y_i) = \tfrac{e^{y_i}}{\sum e^y}$로 총합 1의 확률로 만들게된다.
이러한 확률을 이용하여 크로스 엔트로피(주어진 정답의 불확실성의 정도) 비용함수가 최소가 되게한다.
Decision Tree
Tree 구조로 형성된 의사결정 분류 알고리즘
데이터의 회전성에 취약하여 PCA(주성분 분석, 차원축소)를 사용하면 좋다
CART(Classification And Regression Tree)
tree가 subset을 나누는데 있어 gini가 작은 subset을 만드는 방법으로 greedy algorithm이다. loss function은 아래와 같다.
\[J = \tfrac{m_{left}}{m}G_{left}+\tfrac{m_{right}}{m}G_{right}\]
Naive Bayes
특성들 사이의 독립을 가정하는 베이즈 정리를 이용한 확률 분류기
Bayes Theorem
어떠한 기존의 확률을 토대로 새로운 데이터의 확률을 구하는 방법
\[P(c\|x)=\tfrac{P(x\|c)P(c)}{P(x)}\]
elements
$P(c|x)$ posterior probabillity
$P(x)$ predictor prior probabillity
어떠한 기존의 발생 확률
$P(c)$ class prior probabillity
어떠한 특성을 가질 확률
$P(x|c)$ likelihood
특성에서의 발생이 될 확률
Support Vector Machine(SVM)(SVC,SVR)
카테고리들이 있을때 데이터들의 사상된 공간의 경계중 가장 큰 너비를 가진 경계를 찾는 방법
(복잡, 작거나 중간 데이터셋에 적합, scaler를 하면 효율 증가)
(SVC는 kernel을 통해 PolynoialFeature없이도 고차원 적용가능, 실제로 변수가 만들어지지 않아 속도빠름)
margin
서로 다른 두가지 클래스의 데이터에서 어떠한 선으로 구분을 할경우 해당 선의 너비를 의미한다.
support vectors
margin에 해당하는 위치에 놓여있는 elements를 의미한다.
RBF(Radial Basis Fuction) Kernel
방사형 기저 함수라 불리며 비선형 데이터에서 차원을 높여서 margin을 설계하는 방법
Clustering
흩어져있는 원소들을 군집화하여 유사한 데이터끼리 묶는 방식으로 하는 비지도학습
K Nearest Neighbors(KNN)
새로운 데이터를 입력받을때 가까운 데이터들의 분포에 따라 통계적으로 분류를 하는 알고리즘
K means
임의의 centroid를 지정후 근접합 데이터를 군집화 한다음 centroid를 재설정하는것을 반복하여 군집을 구하는 방법(변수들의 스케일링을 하면 효과가 좋다)
DB Scan
밀도 기반 군집화 기법으로 범위내에 있는 샘플들의 갯수가 군집화가 되는 기준이다.
가우시안 혼합 모델(GMM)
Gaussian Mixture Model은 분류가될 집합이 가우시안 분포로 되어있다고 가정하여 클러스터를 구성하는 확률 모델이다.
흩어져있는 원소들을 군집화하여 유사한 데이터끼리 묶는 방식으로 하는 비지도학습
Bagging VS Boosting
bagging
분산을 감소시키는 방법으로
복원 추출을 통해 n개의 샘플을 만드는 boostraping을 통해 나온 샘플을 학습시켜서 선형 결합한것
boosting
편항을 감소시키는 방법으로
weak learner를 생성해서 구한 error를 토대로 가중치를 가해 error를 줄이는 방법이다.
Decision Tree ensemble
ensemble
우수한 모델들에서 나온 결과를 선형적으로 결합하여 성능을 향상하는 방법
Random Forest
bagging을 사용한 알고리즘으로 모든 변수를 기반으로 Tree 생성
Extra Trees
bagging을 사용하지 않는 random forest 알고리즘
AdaBoost
boosting을 사용하여 샘플의 가중치를 더해 순차적 학습을 하는 알고리즘
Decision Tree Gradient Boosting
Gradient Boosting은 미분을 통해 Residual을 줄이는 방향으로 weak learner들을 결합하는 방법(과적합 이슈의 발생)
Extreme Gradient Boosting(XGB)
Regularization과 다양한 loss function을 지원하여 과적합을 감소시킨 방법
Light Gradient Boosting
histogram-based/GOSS/EFB와 같은 알고리즘으로 학습데이터를 감소시켜 속도를 향상시킨 방법
GBM은 Level-wise한데 LGBM은 Leaf-wise해서 시간은 적게 걸려도 깊은 트리형으로 문제없이 작업한다.
GOSS(Gradient-based One-Side Sampling)으로 infomation gain을 계산할때 기울기(가중치)가 작은 변수에 승수 상수로 데이터를 증폭시킴
(데이터가 적으면 과적합 위험)
Categorical Gradient Boosting
범주형 변수를 위한 알고리즘으로 one-hot encoding사용시 증폭되는 메모리 이슈를 보완하였음
(oblivious Decision Tree, Feature Combination)
Natural Gradient Boosting
각 예측값에 대한 신뢰도를 도출해주는 알고리즘으로 시간이 오래걸리는 단점이 있음
차원축소
대부분의 데이터는 고차원으로 구성이 되어있어도 가까이에 있는 경향이 많아 저차원 공간으로 투영(projection)과 같은 차원축소 기법을 통해 해결할 수 있다.
매니폴트
고차원에서 휘어져있는 형태로 고차원에서 가까워 보이지만 실제로는 멀리있는 데이터를 효과적으로 차원 축소 하는 방법
주성분 분석(PCA)
Principal Component Analysis는 보편적인 차원축소 기법으로 분포도를 최대한 유지하는 방향으로 차원을 축소하는 방법이다.(평균이 0인 StandardScaler가 필요하다, sklearn은 자체 지원)
sklearn은 explained_variance_ratio를 통하여 축소한 차원에서 얼마나 분산의 손실이 발생했는지 알 수 있다.
특잇값 분해(SVD)
Singular Value Decomposition은 주성분을 찾는 방법으로 $m \times n$인 행렬 $A_1$에 대한 특잇값 분해는 $U_1\sum_1V_1^T$이다. 이는 유사역행렬을 구하는 방법과 유사하지만 유사역행렬의 $\sum$은 $k \times k$로 변동성이 있지만 SVD는 $m \times n$이다.(thin SVD와 같이 축소기법을 사용하면 크기가 감소하기도 한다.)
SVD를 통하여 구한 $V$의 각 열을 순서대로 $c_1, c_2, …$로 주성분의 축을 구할 수 있다.
$c_1, c_2, …$의 갯수를 통하여 투영하려는 차원을 정할 수 있다.
\[X_{d-proj} = XW_d\]
지역선형임베딩(LLE)
Locally Linear Embedding은 투영을 하지않고 매니폴드를 활용하는 기법이다. 이웃 원소와의 선형성을 측정하여 국부적 관계가 보존되는 저차원을 표현함
t-SNE
비슷한 샘플과 비슷하지 않은샘플로 구분하여 차원을 축소하는 방법
AI
/
ML
/
basic
· 2023-10-23
-
Touch background to close