일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- hadoop
- tensorflow text
- GCP
- requests
- top_k
- API Gateway
- login crawling
- TensorFlow
- Counterfactual Explanations
- chatGPT
- 공분산
- flask
- 유튜브 API
- session 유지
- 상관관계
- BigQuery
- spark udf
- XAI
- grad-cam
- correlation
- API
- UDF
- gather_nd
- integrated gradient
- Airflow
- Retry
- airflow subdag
- subdag
- GenericGBQException
- youtube data
- Today
- Total
데이터과학 삼학년
Ch3. Text Data: Flattening, Filtering,and Chunking 본문
**[참고]**
한글 형태소 분석기¶
- Konlpy : kkoma, mecab, twitter, konoran, hannanum
- Kakao : khaiii -> 딥러닝 기반
형태소 분석기 성능비교
[기본 개념]¶
-
#### BoW : 텍스트 문서를 단어의 카운트를 이용하여 플랫벡터로 변환 시퀀스를 갖지 못함
단지 각 단어가 몇번 나타나는지만 확인
#### 즉 단어의 수(n)만큼의 n-dimensional한 vector 형성
문장의 의미 파괴할 수 있으며, 앞뒤 문맥을 고려하지 못함
- #### Bag of n-grams : token n개의 시퀀스를 볼 수 있어, 약간은 문장의 의미 훼손을 줄일 수도 있음 ex) Bow : 1-gram(unigram) /// 2-grams(bigram) : Emma knocked, knocked on => 2개씩 토큰
연산량이 증가
import pandas as pd
import json
from sklearn.feature_extraction.text import CountVectorizer
%matplotlib notebook
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
Example 3-1. Computing n-grams¶
Dataset = https://www.yelp.com/dataset/download
- biz, review dataset을 나눠서 실행
def load_json_df(filename, num_bytes = -1):
'''Load the first `num_bytes` of the filename as a json blob, convert each line into a row in a Pandas data frame.'''
# windows에서 실행하는 경우 기본 인코딩이 cp949 이므로 encoding 값 지정해야 함.
fs = open(filename, encoding='utf-8')
df = pd.DataFrame([json.loads(x) for x in fs.readlines(num_bytes)])
fs.close()
return df
biz_df = load_json_df('business.json')
biz_df.shape
biz_df.head()
# 처음 10,000개의 리뷰만 로드
f = open('review.json', encoding='utf-8')
js = []
for i in range(10000):
js.append(json.loads(f.readline()))
f.close()
review_df = pd.DataFrame(js)
review_df.shape
review_df.head()
review_df['text'][0]
unigrams, bigrams, trigrams에 대한 피쳐 변환기 생성.
기본 옵션은 하나의 문자로 된 단어를 무시한다.
실전에서는 의미없는 단어들을 제거하기 때문에 매우 유용하지만,
이 예제에서는 설명을 위해 명시적으로 포함시킨다.
# bag of words
bow_converter = CountVectorizer(token_pattern='(?u)\\b\\w+\\b') #re 구문 참고...
## def로 함수를 만들어서 내입맛에 맞게 토큰나이저 가능 CountVectorizer(tokennizer = myfunc, stop_words = mylist)
x = bow_converter.fit_transform(review_df['text'])
x
words = bow_converter.get_feature_names()
len(words)
from random import *
a = randint(5000, 10000)
print(a)
print(words[a:a+10])
# words[:10]
# bigrams
bigram_converter = CountVectorizer(ngram_range=(2,2), token_pattern='(?u)\\b\\w+\\b')
x2 = bigram_converter.fit_transform(review_df['text'])
x2
bigrams = bigram_converter.get_feature_names()
len(bigrams)
### 여러나라말이 섞여서 원코드로 돌리면 일본어(?)가 나옴)
### 2 단어씩 묶여서 이루어진 것을 볼 수 있음
bigrams[-150:-140]
# trigrams
trigram_converter = CountVectorizer(ngram_range=(3,3), token_pattern='(?u)\\b\\w+\\b')
x3 = trigram_converter.fit_transform(review_df['text'])
x3
trigrams = trigram_converter.get_feature_names()
len(trigrams)
trigrams[:10]
print (len(words), len(bigrams), len(trigrams))
# 그림 3-6
sns.set_style("darkgrid")
counts = [len(words), len(bigrams), len(trigrams)]
plt.plot(counts, color='cornflowerblue')
plt.plot(counts, 'bo')
plt.margins(0.1)
plt.xticks(range(3), ['unigram', 'bigram', 'trigram'])
plt.tick_params(labelsize=14)
plt.title('Number of ngrams in the first 10,000 reviews of the Yelp dataset', fontsize=14)
[정제된 피처를 위한 필터링]¶
Stopwords¶
Stopwords : filtering할 단어 리스트_의미없는...¶
- 분류,검색 : 대명사, 관사, 전치사의 가치가 크지 않을 수 있음
- 감성 분석 : 섬세한 의미가 중요
(a, an, and, the, i'll, 은, 는, 이, 가, 나, 그리고) 같은 분석에 큰 영향을 미치지 않을 거라 판단되는 단어들을 리스트에 저장 -> stopwords
영어 : NLTK에서 stopword 제공
한글 : stopword 제공하는 것은 딱히...경험상 직접 만들어 쓰는게 나을 수도¶
빈도기반 filtering¶
빈출 단어¶
stopwords도 이에 포함될수 있음, 각 문서마다 빈번히 나타는 단어
-> 이를 통해 분석가가 판단하여 stopword list와 결함
희귀 단어¶
희귀 단어 : 잘 알려져 있지 않거나, 철자가 틀린 것들
-> 휴지통을 만들어서 따로 카운트 가능
어간 추출(stemming)¶
단어의 의미는 비슷하지만 표현 방식이 서로 다른 토큰은 다르게 카운트되면 안돼~
어근으로 형태를 변형 시킨 후 카운트
stemming을 이용하면 단어의 의미가 매우 다름에도 불구하고 하나의 단어로 인식하는 경우가 있기 때문에 주의해야함!(ex. new, news ->new)
*참고 stemming은 룰 기반 구분 lemmatizing은 문맥을 고려해 어간 구분-> 문장에서 어떤 품사로 쓰였는지 고려해서 자름 stemming : flies -> 단순히 어근으로 구분 lemmatizing : flies -> '날다', '파리' 인지 문맥에 따라 고려해서 구분(시간이 오래걸림)
한국어 -> 형태소분석기 사용
의미 단위¶
파싱과 토큰화¶
파싱 : 필요한 부분을 따오는 것_웹 페이지 경우 여러정보가 있고 필요한 txt 따옴
토큰화 : 문자열을 토큰의 시퀀스로 변환 -> BoW 만드는 과정, 영어의 경우 띄어쓰기(공백)을 이용ㅎ하여 주로 구분
연어 추출¶
연어 : 한 합성(복합)단어가 각 부분 단어의 합보다 큰 의미를 갖는 단어
<span style= "color:red"> Ex. strong tea = 강한(strong) + 차(tea) 라는 의미가 아니지. 이건 아닌듯</span>
cute pupy = cute + pupy -> 오키 인정!
- 연어 추출 방법
- 직접 정의... -> 시간 많이 걸리고, 현실적이지 않음
- 빈도 기반 : 빈번히 등장하는 n-gram이 연어는 아닌 문제가 있음
- 우도비율 검정을 통한 방법 : 우도비율에 따라 bigram을 오름차순 정렬하여 상위 feature 뽑기 -> 한글에선...사실상 불가능할 것 같음... => <span style= "color:green"> 우도비율검정에 대해 설명해주실 분 구함</span>
청킹과 품사태깅(pos-tagging)¶
청킹 : 품사를 인지하고 토큰_한글 morph
품사태깅 : 청킹을 통해 토큰한 단어들과 그 단어의 품사가 태깅된 것을 추출
참고) http://konlpy.org/ko/v0.4.3/morph/
특히 한글은 라이브러리마다 분석형태가 매우 달라서 잘...잘..아주 잘...분석해야함...stopword도 잘 설정하고...
ps. 개인적으로 mecab에 사전 추가해서 사용¶
Example 3-2. PoS tagging and chunking¶
# 처음 10개의 리뷰 로드
f = open('review.json', encoding='utf-8')
js = []
for i in range(10):
js.append(json.loads(f.readline()))
f.close()
review_df = pd.DataFrame(js)
review_df.shape
1. spacy 사용 : spacy 설치 가이드¶
import spacy
# 언어 모델 로드
nlp = spacy.load('en')
print(spacy.info('en'))
# model meta data
# error 날 경우, data 폴더에 파일이 없기 때문...
# 당황하지말고, 프롬프트창에
# python -m spacy download en
# 이것도 안된다면...아래로...
import en_core_web_sm
nlp = en_core_web_sm.load()
# 데이터 프레임에 적용
doc_df = review_df['text'].apply(nlp)
type(doc_df)
type(doc_df[0])
doc_df[0]
# spaCy는 품사(.pos_)와 태그(.tag_)를 모두 제공
for doc in doc_df[0]:
print(doc.text, doc.pos_, doc.tag_)
# spaCy는 명사구 추출 기능도 제공한다.
print([chunk for chunk in doc_df[0].noun_chunks])
from textblob import TextBlob
# Textblob에서는 기본값으로 PatternTagger를 사용하며, 이 예제에서는 이걸로 충분하다.
# NLTK tagger를 사용할 수도 있지만 이것은 불완전한 문장에 대해 더 잘 동작한다.
blob_df = review_df['text'].apply(TextBlob)
type(blob_df)
type(blob_df[0])
blob_df[0].tags
# Textblob도 명사구 추출 가능
print([np for np in blob_df[0].noun_phrases])
[정리]¶
-
3장에서는 물에 발만 담그는 정도로 간단한 피처 생성 기법들을 살펴봄
'Feature Engineering' 카테고리의 다른 글
Ch.6 Dimensionality Reduction: Squashing the Data Pancake with PCA (0) | 2020.05.06 |
---|---|
Ch.5 Categorical Variables: Counting Eggs in theAge of Robotic Chickens (0) | 2020.04.14 |
Ch4. The Effects of Feature Scaling: From Bag-of-Words to Tf-Idf (0) | 2020.04.02 |
Ch2. Fancy Tricks with Simple Numbers (0) | 2020.03.27 |
Ch1. The Machine Learning Pipeline (0) | 2020.03.27 |