일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- Container
- Package
- format
- LLM
- judge
- CUDA
- Laravel
- docker
- Mac
- Linux
- Flask
- enV
- Paper
- DB
- pytorch
- TORCH
- list
- PostgreSQL
- numpy
- Python
- KAKAO
- Windows
- pandas
- file
- AI
- GitLab
- Converting
- Database
- evaluation
- git
Archives
- Today
- Total
Daily Develope
[AI] Hugginface, sklearn, torch 샘플 코드 및 설명 본문
Huggingface Model/Tokenizer
설치
pip install transformers
사용 예시
Tokenizer 선언 (불러오기)
from transformers import AutoTokenizer
model = "klue/bert-base"
tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
Encoding (Tokenize-토큰화) & Decoding (디코딩)
### [pre-condition] Tokenizer 선언 이후
### Encoding
my_data = "text of target data"
tokenized_input = tokenizer(my_data, padding='max_length', truncation=True, return_tensors='pt')
# padding = 모델에서 입력으로 들어가는 최대 토큰 중 padding을 어느 길이까지 넣을 것인지 설정.
# truncation = 너무 긴 경우 잘라서 넣을 것인지 설정.
# return_tensors = 어떤 텐서형태로 반환할 것인지 설정. (tf:TensorFlow, pt:PyTorch, np:Numpy)
### Decoding
token_decoded = tokenizer.decode(tokenized_input['input_ids'])
pprint(token_decoded) # from pprint import pprint
sklearn
설치
pip install scikit-learn
사용 예시
TF-IDF
### [pre-condition] Tokenizer 선언 이후
from sklearn.feature_extraction.text import TfidfVectorizer
### TF-IDF Vectorizer 선언 및 초기화
vectorizer = TfidfVectorizer(
tokenizer=tokenizer.tokenize, # 토큰화
ngram_range=(1,2) # n-gram 설정 (unigram & bigram)
)
# corpus = train dataset의 context 리스트
vectorizer.fit(corpus) # corpus(문서/데이터)에 맞게 vector 차원 조정
sp_matrix = vectorizer.transform(corpus) # corpus(문서/데이터)를 vector 차원으로 임베딩
# 앞선 두 줄 합쳐서 vectorizer.fit_transform(corpus) 메소드 사용 가능
### Vectorizer를 사용해 유사도 계산
sample_idx = random.choice(range(len(dataset["train"]))) # sample 중 랜덤하게 하나 선택
sample_query = dataset["train"][sample_idx]["question"] # 샘플의 쿼리 텍스트
sample_query_vec = vectorizer.transform([query]) # 샘플의 쿼리 벡터(임베딩)값
sample_gt = dataset["train"][sample_idx]["context"] # 샘플의 정답 텍스트
sample_score = sample_query_vec * sp_matrix.T # 샘플의 쿼리 벡터값을 모든 샘플에 대해 유사도 검사
### 점수기준으로 정렬 & 정렬된 점수 및 해당 context id 값 생성
sorted_scores = np.argsort(-sp_scores.data)
doc_scores = sp_scores.data[sorted_scores]
doc_ids = sp_scores.indices[sorted_scores]
### Top-k 출력
k=5
doc_scores[:k], doc_ids[:k]
Tensor
설치
사용 예시
View
텐서의 차원을 변경하기 위한 용도
### 3차원 텐서를 2차원으로 변경
# 3차원 텐서 선언
ft = torch.FloatTensor([ [[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]] ])
print(ft.shape) # torch.Size([2, 2, 3])
# 2차원 텐서로 변환
ft = ft.view([-1, 3])
print(ft) # tensor([[0., 1., 2.], [3., 4., 5.], [6., 7., 8.,], [9., 10., 11.]])
print(ft.shape) # torch.Size([4, 3])
Squeeze
각 텐서 차원에 대해 원소의 개수가 1인 차원을 제거
ft = torch.FloatTensor([[0], [1], [2]])
print(ft.shape) # torchSize([3, 1])
ft = ft.squeeze()
print(ft) # tensor([0., 1., 2.])
print(ft.shape) # torchSize([3])
참고
'AI' 카테고리의 다른 글
[Article] LLM Judge (0) | 2024.01.03 |
---|---|
[Paper] 2023 gemini technical report (LLM/MMLU 관련내용) 정리 (1) | 2023.12.12 |
[AI] Optimizer 옵티마이저 참조 (0) | 2023.10.18 |
[AI] CUDA & PyTorch Windows 설치 / 환경설정 (with WSL2) (0) | 2023.08.01 |
[AI] Research 시황 조사 (0) | 2023.04.05 |