일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- 원-핫 인코딩
- 풀링층
- 출력층
- 양방향 RNN
- RNN
- 프로그래머스
- 입력층
- 자연어 전처리
- 카운트 벡터
- 시계열 분석
- 임베딩
- 생성모델
- 코랩
- KONLPY
- NLTK
- COLAB
- 순환 신경망
- 전이학습
- 텍스트 마이닝
- 합성곱층
- 합성곱 신경망
- 클러스터링
- 망각 게이트
- 딥러닝
- 과적합
- 이미지 분류
- 완전연결층
- 성능 최적화
- 코딩테스트
- cnn
Archives
- Today
- Total
Colab으로 하루에 하나씩 딥러닝
자연어 전처리_2.전처리_1) 토큰화 본문
728x90
토큰화
- 주어진 텍스트를 단어 / 문자 단위로 자르는 것
- 문장 토큰화 / 단어 토큰화로 구분
문장 토큰화
- 마침표(,), 느낌표(!), 물음표(?) 등 문장의 마지막을 뜻하는 기호에 따라 분리
### 문장 토큰화
import nltk
nltk.download('punkt')
from nltk import sent_tokenize
text_sample = """Natural Language Processing, or NLP, is the process of extracting the meaning, or intent, behind human language.
In the field of Conversational artifical intelligence(AI), NLP allows machine and applications to understand the intent of
human language inputs, and then generate responses, resulting in a natural conversation flow."""
tokenized_sentences = sent_tokenize(text_sample)
print(tokenized_sentences)

단어 토큰화
- 띄어쓰기를 기준으로 문장을 구분
- 한국어는 띄어쓰기만으로 토큰을 구분하기 어려워서 KoNLPy를 사용
### 단어 토큰화
from nltk import word_tokenize
sentence = "This book is for deep learning learners"
words = word_tokenize(sentence)
print(words)

### 아포스트로피가 포함된 문장에서 단어 토큰화
from nltk.tokenize import WordPunctTokenizer
sentence = "it's nothing that you don't already know except most people aren't aware of how their inner world works."
words = WordPunctTokenizer().tokenize(sentence)
print(words)

### 케라스를 이용한 단어 토큰화
import tensorflow
from tensorflow.keras.preprocessing.text import text_to_word_sequence
sentence = "it's nothing that you don't already know except most people aren't aware of how their inner world works."
word = text_to_word_sequence(sentence)
print(words)

한글 토큰화 예제
- https://github.com/e9t/nsmc 의 ratings_train.txt 데이터 파일 사용
- 한글 형태소 분석을 위해 오픈 소스 한글 형태소 분석기(Twitter(Okt)) 사용
- 코랩에서 원활하게 사용하기 위하여
### 코랩 사용 전 준비 (1.드라이브 마운트하기)
from google.colab import drive
drive.mount('/content/drive')
### 코랩 사용 전 준비 (2.github 클론하기)
%cd /content
!git clone https://github.com/e9t/nsmc.git
### 라이브러리 호출 및 데이터셋 준비
import csv
import konlpy
import gensim
from konlpy.tag import Okt
from gensim.models import word2vec
f = open('/content/nsmc/ratings_train.txt','r', encoding='utf-8')
rdr = csv.reader(f, delimiter='\t')
rdw = list(rdr)
f.close()
### 오픈 소스 한글 형태소 분석기 호출
twitter = Okt()
result = []
for line in rdw: # 텍스트 한 줄씩 처리
malist = twitter.pos(line[1],norm=True, stem=True) # 형태소 분석
r = []
for word in malist:
if not word[1] in ["Josa", "Eomi","Punctuation"]: # 조사, 어미, 문장 부호는 제외하고 처리
r.append(word[0])
rl = (" ".join(r)).strip() # 형태소 사이에 공백 " "을 넣고, 양쪽 공백은 삭제
result.append(rl)
print(rl)

### 형태소 저장
with open("NaverMovie.nlp", 'w', encoding='utf-8') as fp:
fp.write("\n".join(result))
### Word2Vec 모델 생성
mData = word2vec.LineSentence("NaverMovie.nlp")
mModel = word2vec.Word2Vec(mData, size=200, window=10, hs=1, min_count=2, sg=1)
mModel.save("NaverMovie.model") # 모델 저장

출처: 서지영, 『딥러닝 텐서플로 교과서』, 길벗(2022)
'딥러닝_개념' 카테고리의 다른 글
자연어 전처리_3.임베딩_1) 희소 표현 기반 임베딩(원-핫 인코딩) (0) | 2022.12.12 |
---|---|
자연어 전처리_2.전처리_4) 정규화 (1) | 2022.12.10 |
자연어 전처리_2.전처리_3) 어간 추출 / 표제어 추출 (0) | 2022.12.09 |
자연어 전처리_2.전처리_2) 불용어 제거 (0) | 2022.12.09 |
자연어 전처리_1.자연어 처리 (2) | 2022.12.07 |