회고기간 : 2025.03.31월~2025.04.04금
이번 주차는 프로젝트 발표와 NLP의 코사인 유사도, 전처리 등을 학습했다.
NLTK
설치
!conda install nltk -y
import nltk
# nltk 설치 후에는 기본 패키지들을 별도로 다운로드 해야함
nltk.download('punkt')
nltk.download('punkt_tab')
nltk.download('stopwords')
토큰화
from nltk.tokenize import word_tokenize, sent_tokenize
- 단어 토큰화 (word_tokenize)
- 단어 기준 토큰화
- ['NLTK', 'is', 'a', 'powerful', 'library', 'for', 'NLP', '!', '!', '!']
- 문장 토큰화 (sent_tokenize)
- 구두점 기준 문장 토큰화
- ['The Matrix is everywhere its all around us, here even in this room.', 'You can see it out your window or on your television.', 'You feel it when you go to work, or go to church or pay your taxes.']
ngrams
from nltk import ngrams
- n개 단위 기준으로 토큰화
from nltk import ngrams
text = '''The Matrix is everywhere its all around us, here even in this room.
You can see it out your window or on your television.
You feel it when you go to work, or go to church or pay your taxes.'''
tokens = word_tokenize(text)
bigram = ngrams(tokens, 2)
print([token for token in bigram])
[출력]
[('The', 'Matrix'), ('Matrix', 'is'), ('is', 'everywhere'), ..... ]
trigram = ngrams(tokens, 3)
print([token for token in trigram])
[출력]
[('The', 'Matrix', 'is'), ('Matrix', 'is', 'everywhere'), ('is', 'everywhere', 'its'), .... ]
불용어 제거
from nltk.corpus import stopwords
text = '''The Matrix is everywhere its all around us, here even in this room.
You can see it out your window or on your television.
You feel it when you go to work, or go to church or pay your taxes.'''
stopwords_lst = stopwords.words('english')
tokens = []
for word in word_tokenize(text): # 토큰화
word = word.lower() # 소문자 변환
if word not in stopwords_lst: # 불용어 처리
tokens.append(word)
tokens
특성 벡터화
1. BOW
- 문서 안에 있는 단어의 횟수를 사용해 벡터로 변환 (고차원 희소벡터)
2. Word Embedding
- 의미적으로 비슷한 단어를 밀집 벡터로 표현하는 방식
- 단어의 의미와 관계를 보존
3. TfidfVectorizer
- 단어 빈도와 희귀성을 곱해 가중치 부여한 벡터
4. 코사인 유사도
- 단어 간 코사인 각도를 사용해 유사도를 판단
BOW
from sklearn.feature_extraction.text import CountVectorizer
texts = [text1, text2]
count_vectorizer = CountVectorizer()
count_vectorizer.fit(texts)
text_vecs = count_vectorizer.transform(texts)
print(text_vecs)
[출력]
Coords Values
(0, 0) 1
(0, 2) 1
(0, 6) 1
(0, 7) 1
(0, 10) 1
(0, 11) 1
(0, 12) 1
(0, 13) 2
(0, 15) 1
(0, 18) 1
(0, 19) 1
(0, 20) 2
(0, 21) 1
print(count_vectorizer.get_feature_names_out())
[출력]
['all' 'and' 'around' 'bed' 'believe' 'blue' 'can' 'church' 'deep' 'ends'
'even' 'everywhere' 'feel' 'go' 'goes' ...]
print(count_vectorizer.vocabulary_)
[출력]
{'the': 38, 'matrix': 22, 'is': 19, 'everywhere': 11, ... }
Tfidf & Cosine similarity
from sklearn.feature_extraction.text import TfdifVecotrizer
from skleanr.metrcs.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
doc_list = [
'if you take the blue pill, the story ends' ,
'if you take the red pill, you stay in Wonderland',
'if you take the red pill, I show you how deep the rabbit hole goes'
]
# tfidf 벡터화
tfidf_vectorizer = TfidfVectorizer()
doc_vecs = tfidf_vectorizer.fit_transform(doc_list)
print(doc_vecs.shape)
# 단어가 벡터에서 차지하는 인덱스 번호 출력
print(sorted(tfidf_vectorizer.vocabulary_.items(), key=lambda x:x[1]))
# 코사인 유사도 계산
doc_arr = doc_vecs.toarray()
cosine_similarity(doc_arr[0:1], doc_arr)
[출력]
(3, 18)
[('blue', 0), ('deep', 1), ('ends', 2), ('goes', 3), ('hole', 4), ... ]
array([[1. , 0.40207758, 0.40425045]]) # 문장1과 1 / 문장 1과 2 / 문장 1과 3 의 유사도
품사태깅
import nltk
nltk.download('averaged_perceptron_tagger')
nltk.download('averaged_perceptron_tagger_eng')
from nltk.tag import pos_tag
text = "Time flies like an arrow."
tokens = word_tokenize(text)
pos_tag = pos_tag(tokens)
pos_tag
[출력]
[('Time', 'NNP'),
('flies', 'NNS'),
('like', 'IN'),
('an', 'DT'),
('arrow', 'NN')
('.', '.')]
정제 / 정규화
- 텍스트 대체
- text.replace(old 인자, new 인자)
- 대소문자 통합
- text.lower() (lower에는 인자가 없음!!!)
- 빈도수 계산
- from collections import Counter
- Counter 객체 생성 후 조건 걸어서 빈도수 낮은 단어 제거
어간 / 표제어 추출
- 어간 : 단어의 의미를 담고 있는 핵심 부분
from nltk.stem import PorterStemmer - 표제어 : 단어의 사전적 형태
from nltk.stem import WordNetLemmatizer
정규표현식
- 특정한 규칙을 가진 문자열을 찾기 위한 패턴
- 다량의 텍스트에서 패턴을 효율적으로 추출, 삭제, 대체할 수 있음
# 임의의 한글자 확인
reg_exp = re.compile('a.c')
print(reg_exp.search('abc')) # <re.Match object; span=(0, 3), match='abc'>
print(reg_exp.search('ac')) # None
# 수량자 * -> 0개 이상
reg_exp = re.compile('ab*c')
print(reg_exp.search('ac'))
print(reg_exp.search('ab')) # None
# 수량자 ? -> 0 또는 1개
reg_exp = re.compile('ab?c')
print(reg_exp.search('ac'))
print(reg_exp.search('ab')) # None
# 수량자 + -> a로 시작, b가 반드시 한개 이상 포함, c로 끝
reg_exp = re.compile('ab+c')
print(reg_exp.search('abc'))
print(reg_exp.search('ab')) # None
# 수량자 {n} -> a로 시작, b에 해당하는게 n개, c로 끝
reg_exp = re.compile('ab{3}c')
print(reg_exp.search('abbbc'))
print(reg_exp.search('abbbbc')) # None
# 수량자 {min, max} -> a로 시작, b가 min개 이상, max개 이하 , c로 끝
reg_exp = re.compile('ab{1,3}c')
print(reg_exp.search('abbbc'))
print(reg_exp.search('abbbbc')) # None
정규표현식 토큰화 : RegexpTokenizer
=> 구두점 및 , ' 를 제거
from nltk.tokenize import RegexpTokenizer
text = "He's a runner, but not a long_distance runner. His number is 1234."
tokenizer = RegexpTokenizer('[a-zA-Z0-9_]+') # +를 붙여 하나 이상의 텍스트 추출
tokenizer = RegexpTokenizer(r'\w+') # 위와 동일한 정규표현식
# 영문, 숫자, _ 를 허용함
tokens = tokenizer.tokenize(text)
tokens
정수인코딩 & 원핫인코딩
keras tokenizer
!pip install tensorflow
from tensorflow.keras.preprocessing.text import Tokenizer
tokenizer = Tokenizer(num_words=16, oov_token='<OOV>') # num_words = vocab size에 해당함 (인덱스는 0~14니까 밑에 결과가 15번까지 나오려면 인덱싱을 따로 해줘야함)
tokenizer.fit_on_texts(preprocessed_sentences)
tokenizer.word_index # corpus의 모든 단어를 대상으로 생성
tokenizer.index_word # corpus의 모든 단어를 대상으로 생성
tokenizer.word_counts
# 정수 인코딩
sequences = tokenizer.texts_to_sequences(preprocessed_sentences)
sequences
패딩
# 패딩처리
from tensorflow.keras.preprocessing.sequence import pad_sequences
padded_seqs = pad_sequences(sequences, maxlen=3)
padded_seqs
# 원핫인코딩
from tensorflow.keras.utils import to_categorical
one_hot_encoded = to_categorical(padded_seqs)
one_hot_encoded.shape
💡 Keep
프로젝트 마무리와 빅분기 필기공부.. 정신줄 부여잡기...
⚠️ Problem
이번주는 핑계같지만 복습할 시간이 진짜 없었다.. 프젝도 전처리 다시해야하는 상황인데 빅분기하고 또또 복습..밤을 꼬박 새게 생겼다 쉬는시간이나 점심시간에라도 꾸준히 해야겠다
🔥 Try
운동하기 ! ㅠㅡㅠ
'SKN > Remind' 카테고리의 다른 글
| sk네트웍스 family AI 캠프 11기 4월 4주차 회고록 (3) | 2025.04.28 |
|---|---|
| sk네트웍스 family AI 캠프 11기 4월 3주차 회고록 (1) | 2025.04.20 |
| sk네트웍스 family AI 캠프 11기 3월 3주차 회고록 (0) | 2025.03.24 |
| sk네트웍스 family AI 캠프 11기 5주차 회고록 (0) | 2025.03.11 |
| sk네트웍스 family AI 캠프 1차 프로젝트 회고 (0) | 2025.03.03 |